From scipy-svn at scipy.org Tue Jan 1 04:33:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 1 Jan 2008 03:33:12 -0600 (CST) Subject: [Scipy-svn] r3758 - in trunk/scipy/io: . matlab tests Message-ID: <20080101093312.841B039C048@new.scipy.org> Author: oliphant Date: 2008-01-01 03:33:02 -0600 (Tue, 01 Jan 2008) New Revision: 3758 Added: trunk/scipy/io/matlab/ trunk/scipy/io/matlab/__init__.py trunk/scipy/io/matlab/mio.py trunk/scipy/io/matlab/mio4.py trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/miobase.py trunk/scipy/io/matlab/setup.py Removed: trunk/scipy/io/datasource.py trunk/scipy/io/matlab/__init__.py trunk/scipy/io/matlab/mio.py trunk/scipy/io/matlab/mio4.py trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/miobase.py trunk/scipy/io/matlab/setup.py trunk/scipy/io/mio.py trunk/scipy/io/mio4.py trunk/scipy/io/mio5.py trunk/scipy/io/miobase.py Modified: trunk/scipy/io/__init__.py trunk/scipy/io/array_import.py trunk/scipy/io/data_store.py trunk/scipy/io/mmio.py trunk/scipy/io/npfile.py trunk/scipy/io/pickler.py trunk/scipy/io/setup.py trunk/scipy/io/tests/test_mio.py Log: Merge in changes from io_new branch -r 3655:3752 Modified: trunk/scipy/io/__init__.py =================================================================== --- trunk/scipy/io/__init__.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/__init__.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,24 +1,90 @@ - # # io - Data input and output # from info import __doc__ +from numpy import deprecate_with_doc + +# These are all deprecated (until the end deprecated tag) +from npfile import npfile +from data_store import save, load, create_module, create_shelf +from array_import import read_array, write_array +from pickler import objload, objsave + from numpyio import packbits, unpackbits, bswap, fread, fwrite, \ convert_objectarray + +fread = deprecate_with_doc(""" +scipy.io.fread is can be replaced with raw reading capabilities of NumPy +including fromfile as well as memory-mapping capabilities. +""")(fread) + +fwrite = deprecate_with_doc(""" +scipy.io.fwrite can be replaced with raw writing capabilities of +NumPy. Also, remember that files can be directly memory-mapped into NumPy +arrays which is often a better way of reading especially large files. + +Look at the tofile methods as well as save and savez for writing arrays into +easily transported files of data. +""")(fwrite) + +bswap = deprecate_with_doc(""" +scipy.io.bswap is easily replaced with the byteswap method on an array. +out = scipy.io.bswap(arr) --> out = arr.byteswap(True) +""")(bswap) + +packbits = deprecate_with_doc(""" +The functionality of scipy.io.packbits is now available as numpy.packbits +The calling convention is a bit different as the 2-d case is not specialized. + +However, you can simulate scipy.packbits by raveling the last 2 dimensions +of the array and calling numpy.packbits with an axis=-1 keyword: + +def scipy_packbits(inp): + a = np.asarray(inp) + if a.ndim < 2: + return np.packbits(a) + oldshape = a.shape + newshape = oldshape[:-2] + (oldshape[-2]*oldshape[-1],) + a = np.reshape(a, newshape) + return np.packbits(a, axis=-1).ravel() +""")(packbits) + +unpackbits = deprecate_with_doc(""" +The functionality of scipy.io.unpackbits is now available in numpy.unpackbits +The calling convention is different however as the 2-d case is no longer +specialized. + +Thus, the scipy.unpackbits behavior must be simulated using numpy.unpackbits. + +def scipy_unpackbits(inp, els_per_slice, out_type=None): + inp = np.asarray(inp) + num4els = ((els_per_slice-1) >> 3) + 1 + inp = np.reshape(inp, (-1,num4els)) + res = np.unpackbits(inp, axis=-1)[:,:els_per_slice] + return res.ravel() +""")(unpackbits) + +convert_objectarray = deprecate_with_doc(""" +The same functionality can be obtained using NumPy string arrays and the +.astype method (except for the optional missing value feature). +""")(convert_objectarray) + +# end deprecated + # matfile read and write -from mio import * +from matlab.mio import loadmat, savemat + # netCDF file support -from netcdf import * -from npfile import npfile +from netcdf import netcdf_file, netcdf_variable + from recaster import sctype_attributes, Recaster -from array_import import * -from data_store import * -from pickler import * +from data_store import save_as_module +from mmio import mminfo, mmread, mmwrite -from mmio import mminfo,mmread,mmwrite + __all__ = filter(lambda s:not s.startswith('_'),dir()) from numpy.testing import NumpyTest test = NumpyTest().test Modified: trunk/scipy/io/array_import.py =================================================================== --- trunk/scipy/io/array_import.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/array_import.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -17,7 +17,9 @@ # Numpy imports. import numpy -from numpy import array, take, concatenate, asarray, real, imag + +from numpy import array, take, concatenate, asarray, real, imag, \ + deprecate_with_doc # Sadly, this module is still written with typecodes in mind. from numpy.oldnumeric import Float @@ -310,6 +312,10 @@ return cols, atype + at deprecate_with_doc(""" +The functionality of read_array is in numpy.loadtxt which allows the same +functionality using different syntax. +""") def read_array(fileobject, separator=default, columns=default, comment="#", lines=default, atype=Float, linesep='\n', rowsize=10000, missing=0): @@ -437,6 +443,11 @@ return row_sep.join(thestr) + at deprecate_with_doc(""" + +This function is replaced by numpy.savetxt which allows the same functionality +through a different syntax. +""") def write_array(fileobject, arr, separator=" ", linesep='\n', precision=5, suppress_small=0, keep_open=0): """Write a rank-2 or less array to file represented by fileobject. Modified: trunk/scipy/io/data_store.py =================================================================== --- trunk/scipy/io/data_store.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/data_store.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -5,21 +5,27 @@ you to store data to a file and then load it back into the workspace. When the data is stored, a python module is also created as the "namespace for the data" - >>> import data_store + >>> import scipy.io >>> import os >>> a = 1 - >>> data_store.save('c:/temp/junker',{'a':a}) + >>> scipy.io.save_as_module('c:/temp/junker',{'a':a}) >>> os.chdir('c:/temp') >>> import junker >>> junker.a 1 """ -__all__ = ['load', 'save', 'create_module', 'create_shelf'] +__all__ = ['save_as_module', + # The rest of these are all deprecated + 'save', 'create_module', + 'create_shelf', 'load'] + import dumb_shelve import os -def load(module): +from numpy import deprecate_with_doc, deprecate + +def _load(module): """ Load data into module from a shelf with the same name as the module. """ @@ -34,15 +40,15 @@ # print i, 'loaded...' # print 'done' -def save(file_name=None,data=None): - """ Save the dictionary "data" into - a module and shelf named save - """ - import dumb_shelve - create_module(file_name) - create_shelf(file_name,data) +load = deprecate_with_doc(""" +This is an internal function used with scipy.io.save_as_module -def create_module(file_name): +If you are saving arrays into a module, you should think about using +HDF5 or .npz files instead. +""")(_load) + + +def _create_module(file_name): """ Create the module file. """ if not os.path.exists(file_name+'.py'): # don't clobber existing files @@ -50,10 +56,17 @@ f = open(file_name+'.py','w') f.write('import scipy.io.data_store as data_store\n') f.write('import %s\n' % module_name) - f.write('data_store.load(%s)' % module_name) + f.write('data_store._load(%s)' % module_name) f.close() -def create_shelf(file_name,data): +create_module = deprecate_with_doc(""" +This is an internal function used with scipy.io.save_as_module + +If you are saving arrays into a module, you should think about +using HDF5 or .npz files instead. +""")(_create_module) + +def _create_shelf(file_name,data): """Use this to write the data to a new file """ shelf_name = file_name.split('.')[0] @@ -63,3 +76,20 @@ f[i] = data[i] # print 'done' f.close() + +create_shelf = deprecate_with_doc(""" +This is an internal function used with scipy.io.save_as_module + +If you are saving arrays into a module, you should think about using +HDF5 or .npz files instead. +""")(_create_shelf) + + +def save_as_module(file_name=None,data=None): + """ Save the dictionary "data" into + a module and shelf named save + """ + _create_module(file_name) + _create_shelf(file_name,data) + +save = deprecate(save_as_module, 'save', 'save_as_module') Deleted: trunk/scipy/io/datasource.py =================================================================== --- trunk/scipy/io/datasource.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/datasource.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,457 +0,0 @@ -"""A file interface for handling local and remote data files. -The goal of datasource is to abstract some of the file system operations when -dealing with data files so the researcher doesn't have to know all the -low-level details. Through datasource, a researcher can obtain and use a -file with one function call, regardless of location of the file. - -DataSource is meant to augment standard python libraries, not replace them. -It should work seemlessly with standard file IO operations and the os module. - -DataSource files can originate locally or remotely: - -- local files : '/home/guido/src/local/data.txt' -- URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt' - -DataSource files can also be compressed or uncompressed. Currently only gzip -and bz2 are supported. - -Example: - - >>> # Create a DataSource, use os.curdir (default) for local storage. - >>> ds = datasource.DataSource() - >>> - >>> # Open a remote file. - >>> # DataSource downloads the file, stores it locally in: - >>> # './www.google.com/index.html' - >>> # opens the file and returns a file object. - >>> fp = ds.open('http://www.google.com/index.html') - >>> - >>> # Use the file as you normally would - >>> fp.read() - >>> fp.close() - -""" - -__docformat__ = "restructuredtext en" - -import bz2 -import gzip -import os -import tempfile -from shutil import rmtree -from urllib2 import urlopen, URLError -from urlparse import urlparse - -import warnings - -# datasource has been used for a while in the NIPY project for analyzing -# large fmri imaging files hosted over a network. Data would be fetched -# via URLs, cached locally and analyzed. Under these conditions the code -# worked well, however it needs to be documented, tested and reviewed -# before being fully exposed to SciPy. We hope to do this before the -# 0.7 release. -_api_warning = "The datasource API will be changing frequently before \ -the 0.7 release as the code is ported from the NIPY project to SciPy. \ -Some of the current public interface may become private during the port! \ -Use this module minimally, if at all, until it is stabilized." - -warnings.warn(_api_warning) - -# TODO: .zip support, .tar support? -_file_openers = {".gz":gzip.open, ".bz2":bz2.BZ2File, None:file} - - -def open(path, mode='r', destpath=os.curdir): - """Open ``path`` with ``mode`` and return the file object. - - If ``path`` is an URL, it will be downloaded, stored in the DataSource - directory and opened from there. - - *Parameters*: - - path : {string} - - mode : {string}, optional - - destpath : {string}, optional - Destination directory where URLs will be downloaded and stored. - - *Returns*: - - file object - - """ - - ds = DataSource(destpath) - return ds.open(path, mode) - - -class DataSource (object): - """A generic data source file (file, http, ftp, ...). - - DataSources could be local files or remote files/URLs. The files may - also be compressed or uncompressed. DataSource hides some of the low-level - details of downloading the file, allowing you to simply pass in a valid - file path (or URL) and obtain a file object. - - *Methods*: - - - exists : test if the file exists locally or remotely - - abspath : get absolute path of the file in the DataSource directory - - open : open the file - - *Example URL DataSource*:: - - # Initialize DataSource with a local directory, default is os.curdir. - ds = DataSource('/home/guido') - - # Open remote file. - # File will be downloaded and opened from here: - # /home/guido/site/xyz.txt - ds.open('http://fake.xyz.web/site/xyz.txt') - - *Example using DataSource for temporary files*:: - - # Initialize DataSource with 'None' for the local directory. - ds = DataSource(None) - - # Open local file. - # Opened file exists in a temporary directory like: - # /tmp/tmpUnhcvM/foobar.txt - # Temporary directories are deleted when the DataSource is deleted. - ds.open('/home/guido/foobar.txt') - - *Notes*: - BUG : URLs require a scheme string ('http://') to be used. - www.google.com will fail. - - >>> repos.exists('www.google.com/index.html') - False - - >>> repos.exists('http://www.google.com/index.html') - True - - """ - - def __init__(self, destpath=os.curdir): - """Create a DataSource with a local path at destpath.""" - if destpath: - self._destpath = os.path.abspath(destpath) - self._istmpdest = False - else: - self._destpath = tempfile.mkdtemp() - self._istmpdest = True - - def __del__(self): - # Remove temp directories - if self._istmpdest: - rmtree(self._destpath) - - def _iszip(self, filename): - """Test if the filename is a zip file by looking at the file extension. - """ - fname, ext = os.path.splitext(filename) - return ext in _file_openers.keys() - - def _iswritemode(self, mode): - """Test if the given mode will open a file for writing.""" - - # Currently only used to test the bz2 files. - _writemodes = ("w", "+") - for c in mode: - if c in _writemodes: - return True - return False - - def _splitzipext(self, filename): - """Split zip extension from filename and return filename. - - *Returns*: - base, zip_ext : {tuple} - - """ - - if self._iszip(filename): - return os.path.splitext(filename) - else: - return filename, None - - def _possible_names(self, filename): - """Return a tuple containing compressed filename variations.""" - names = [filename] - if not self._iszip(filename): - for zipext in _file_openers.keys(): - if zipext: - names.append(filename+zipext) - return names - - def _isurl(self, path): - """Test if path is a net location. Tests the scheme and netloc.""" - - # BUG : URLs require a scheme string ('http://') to be used. - # www.google.com will fail. - # Should we prepend the scheme for those that don't have it and - # test that also? Similar to the way we append .gz and test for - # for compressed versions of files. - - scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) - return bool(scheme and netloc) - - def _cache(self, path): - """Cache the file specified by path. - - Creates a copy of the file in the datasource cache. - - """ - - upath = self.abspath(path) - - # ensure directory exists - if not os.path.exists(os.path.dirname(upath)): - os.makedirs(os.path.dirname(upath)) - - # TODO: Doesn't handle compressed files! - if self._isurl(path): - try: - openedurl = urlopen(path) - file(upath, 'w').write(openedurl.read()) - except URLError: - raise URLError("URL not found: ", path) - else: - try: - # TODO: Why not just copy the file with shutils.copyfile? - fp = file(path, 'r') - file(upath, 'w').write(fp.read()) - except IOError: - raise IOError("File not found: ", path) - return upath - - def _findfile(self, path): - """Searches for ``path`` and returns full path if found. - - If path is an URL, _findfile will cache a local copy and return - the path to the cached file. - If path is a local file, _findfile will return a path to that local - file. - - The search will include possible compressed versions of the file and - return the first occurence found. - - """ - - # Build list of possible local file paths - if not self._isurl(path): - # Valid local paths - filelist = self._possible_names(path) - # Paths in self._destpath - filelist += self._possible_names(self.abspath(path)) - else: - # Cached URLs in self._destpath - filelist = self._possible_names(self.abspath(path)) - # Remote URLs - filelist = filelist + self._possible_names(path) - - for name in filelist: - if self.exists(name): - if self._isurl(name): - name = self._cache(name) - return name - return None - - def abspath(self, path): - """Return absolute path of ``path`` in the DataSource directory. - - If ``path`` is an URL, the ``abspath`` will be either the location - the file exists locally or the location it would exist when opened - using the ``open`` method. - - The functionality is idential to os.path.abspath. - - *Parameters*: - - path : {string} - Can be a local file or a remote URL. - - *Returns*: - - Complete path, rooted in the DataSource destination directory. - - *See Also*: - - `open` : Method that downloads and opens files. - - """ - - # TODO: This should be more robust. Handles case where path includes - # the destpath, but not other sub-paths. Failing case: - # path = /home/guido/datafile.txt - # destpath = /home/alex/ - # upath = self.abspath(path) - # upath == '/home/alex/home/guido/datafile.txt' - - # handle case where path includes self._destpath - splitpath = path.split(self._destpath, 2) - if len(splitpath) > 1: - path = splitpath[1] - scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) - return os.path.join(self._destpath, netloc, upath.strip(os.sep)) - - def exists(self, path): - """Test if ``path`` exists. - - Test if ``path`` exists as (and in this order): - - - a local file. - - a remote URL that have been downloaded and stored locally in the - DataSource directory. - - a remote URL that has not been downloaded, but is valid and - accessible. - - *Parameters*: - - path : {string} - Can be a local file or a remote URL. - - *Returns*: - - boolean - - *See Also*: - - `abspath` - - *Notes* - - When ``path`` is an URL, ``exist`` will return True if it's either - stored locally in the DataSource directory, or is a valid remote - URL. DataSource does not discriminate between to two, the file - is accessible if it exists in either location. - - """ - - # Test local path - if os.path.exists(path): - return True - - # Test cached url - upath = self.abspath(path) - if os.path.exists(upath): - return True - - # Test remote url - if self._isurl(path): - try: - netfile = urlopen(path) - del(netfile) - return True - except URLError: - return False - return False - - def open(self, path, mode='r'): - """Open ``path`` with ``mode`` and return the file object. - - If ``path`` is an URL, it will be downloaded, stored in the DataSource - directory and opened from there. - - *Parameters*: - - path : {string} - - mode : {string}, optional - - - *Returns*: - - file object - - """ - - # TODO: There is no support for opening a file for writing which - # doesn't exist yet (creating a file). Should there be? - - # TODO: Add a ``subdir`` parameter for specifying the subdirectory - # used to store URLs in self._destpath. - - if self._isurl(path) and self._iswritemode(mode): - raise ValueError("URLs are not writeable") - - # NOTE: _findfile will fail on a new file opened for writing. - found = self._findfile(path) - if found: - _fname, ext = self._splitzipext(found) - if ext == 'bz2': - mode.replace("+", "") - return _file_openers[ext](found, mode=mode) - else: - raise IOError("%s not found." % path) - - -class Repository (DataSource): - """A data Repository where multiple DataSource's share a base URL/directory. - - Repository extends DataSource by prepending a base URL (or directory) to - all the files it handles. Use a Repository when you will be working with - multiple files from one base URL. Initialize the Respository with the - base URL, then refer to each file by it's filename only. - - *Methods*: - - - exists : test if the file exists locally or remotely - - abspath : get absolute path of the file in the DataSource directory - - open : open the file - - *Toy example*:: - - # Analyze all files in the repository. - repos = Repository('/home/user/data/dir/') - for filename in filelist: - fp = repos.open(filename) - fp.analyze() - fp.close() - - # Similarly you could use a URL for a repository. - repos = Repository('http://www.xyz.edu/data') - - """ - - def __init__(self, baseurl, destpath=os.curdir): - """Create a Repository with a shared url or directory of baseurl.""" - DataSource.__init__(self, destpath=destpath) - self._baseurl = baseurl - - def __del__(self): - DataSource.__del__(self) - - def _fullpath(self, path): - """Return complete path for path. Prepends baseurl if necessary.""" - splitpath = path.split(self._baseurl, 2) - if len(splitpath) == 1: - result = os.path.join(self._baseurl, path) - else: - result = path # path contains baseurl already - return result - - def _findfile(self, path): - """Extend DataSource method to prepend baseurl to ``path``.""" - return DataSource._findfile(self, self._fullpath(path)) - - def abspath(self, path): - """Extend DataSource method to prepend baseurl to ``path``.""" - return DataSource.abspath(self, self._fullpath(path)) - - def exists(self, path): - """Extend DataSource method to prepend baseurl to ``path``.""" - return DataSource.exists(self, self._fullpath(path)) - - def open(self, path, mode='r'): - """Extend DataSource method to prepend baseurl to ``path``.""" - return DataSource.open(self, self._fullpath(path), mode) - - def listdir(self): - '''List files in the source Repository.''' - if self._isurl(self._baseurl): - raise NotImplementedError, \ - "Directory listing of URLs, not supported yet." - else: - return os.listdir(self._baseurl) Copied: trunk/scipy/io/matlab (from rev 3757, branches/io_new/matlab) Deleted: trunk/scipy/io/matlab/__init__.py =================================================================== Copied: trunk/scipy/io/matlab/__init__.py (from rev 3757, branches/io_new/matlab/__init__.py) Deleted: trunk/scipy/io/matlab/mio.py =================================================================== --- branches/io_new/matlab/mio.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/matlab/mio.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,133 +0,0 @@ -# Authors: Travis Oliphant, Matthew Brett - -""" -Module for reading and writing matlab (TM) .mat files -""" - -import os -import sys - -from mio4 import MatFile4Reader, MatFile4Writer -from mio5 import MatFile5Reader, MatFile5Writer - -__all__ = ['find_mat_file', 'mat_reader_factory', 'loadmat', 'savemat'] - -def find_mat_file(file_name, appendmat=True): - ''' Try to find .mat file on system path - - file_name - file name string - append_mat - If True, and file_name does not end in '.mat', appends it - ''' - if appendmat and file_name[-4:] == ".mat": - file_name = file_name[:-4] - if os.sep in file_name: - full_name = file_name - if appendmat: - full_name = file_name + ".mat" - else: - full_name = None - junk, file_name = os.path.split(file_name) - for path in [os.curdir] + list(sys.path): - test_name = os.path.join(path, file_name) - if appendmat: - test_name += ".mat" - try: - fid = open(test_name,'rb') - fid.close() - full_name = test_name - break - except IOError: - pass - return full_name - -def mat_reader_factory(file_name, appendmat=True, **kwargs): - """Create reader for matlab (TM) .mat format files - - See docstring for loadmat for input options - """ - if isinstance(file_name, basestring): - full_name = find_mat_file(file_name, appendmat) - if full_name is None: - raise IOError, "%s not found on the path." % file_name - byte_stream = open(full_name, 'rb') - else: - try: - file_name.read(0) - except AttributeError: - raise IOError, 'Reader needs file name or open file-like object' - byte_stream = file_name - - MR = MatFile4Reader(byte_stream, **kwargs) - if MR.format_looks_right(): - return MR - return MatFile5Reader(byte_stream, **kwargs) - -def loadmat(file_name, mdict=None, appendmat=True, basename='raw', **kwargs): - ''' Load Matlab(tm) file - - file_name - Name of the mat file - (do not need .mat extension if appendmat==True) - If name not a full path name, search for the file on - the sys.path list and use the first one found (the - current directory is searched first). - Can also pass open file-like object - m_dict - optional dictionary in which to insert matfile variables - appendmat - True to append the .mat extension to the end of the - given filename, if not already present - base_name - base name for unnamed variables (unused in code) - byte_order - byte order ('native', 'little', 'BIG') - in ('native', '=') - or in ('little', '<') - or in ('BIG', '>') - mat_dtype - return arrays in same dtype as loaded into matlab - (instead of the dtype with which they are saved) - squeeze_me - whether to squeeze matrix dimensions or not - chars_as_strings - whether to convert char arrays to string arrays - mat_dtype - return matrices with datatype that matlab would load as - (rather than in the datatype matlab saves as) - matlab_compatible - returns matrices as would be loaded by matlab - (implies squeeze_me=False, chars_as_strings=False, - mat_dtype=True) - - v4 (Level 1.0), v6 and v7.1 matfiles are supported. - - ''' - MR = mat_reader_factory(file_name, appendmat, **kwargs) - matfile_dict = MR.get_variables() - if mdict is not None: - mdict.update(matfile_dict) - else: - mdict = matfile_dict - return mdict - -def savemat(file_name, mdict, appendmat=True, format='4'): - """Save a dictionary of names and arrays into the MATLAB-style .mat file. - - This saves the arrayobjects in the given dictionary to a matlab - style .mat file. - - appendmat - if true, appends '.mat' extension to filename, if not present - format - '4' for matlab 4 mat files, '5' for matlab 5 onwards - """ - file_is_string = isinstance(file_name, basestring) - if file_is_string: - if appendmat and file_name[-4:] != ".mat": - file_name = file_name + ".mat" - file_stream = open(file_name, 'wb') - else: - try: - file_name.write('') - except AttributeError: - raise IOError, 'Writer needs file name or writeable '\ - 'file-like object' - file_stream = file_name - - if format == '4': - MW = MatFile4Writer(file_stream) - elif format == '5': - MW = MatFile5Writer(file_stream) - else: - raise ValueError, 'Format should be 4 or 5' - MW.put_variables(mdict) - if file_is_string: - file_stream.close() Copied: trunk/scipy/io/matlab/mio.py (from rev 3757, branches/io_new/matlab/mio.py) Deleted: trunk/scipy/io/matlab/mio4.py =================================================================== --- branches/io_new/matlab/mio4.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/matlab/mio4.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,345 +0,0 @@ -''' Classes for read / write of matlab (TM) 4 files -''' - -import numpy as N - -from miobase import * - -miDOUBLE = 0 -miSINGLE = 1 -miINT32 = 2 -miINT16 = 3 -miUINT16 = 4 -miUINT8 = 5 - -mdtypes_template = { - miDOUBLE: 'f8', - miSINGLE: 'f4', - miINT32: 'i4', - miINT16: 'i2', - miUINT16: 'u2', - miUINT8: 'u1', - 'header': [('mopt', 'i4'), - ('mrows', 'i4'), - ('ncols', 'i4'), - ('imagf', 'i4'), - ('namlen', 'i4')], - 'U1': 'U1', - } - -np_to_mtypes = { - 'f8': miDOUBLE, - 'c32': miDOUBLE, - 'c24': miDOUBLE, - 'c16': miDOUBLE, - 'f4': miSINGLE, - 'c8': miSINGLE, - 'i4': miINT32, - 'i2': miINT16, - 'u2': miUINT16, - 'u1': miUINT8, - 'S1': miUINT8, - } - -# matrix classes -mxFULL_CLASS = 0 -mxCHAR_CLASS = 1 -mxSPARSE_CLASS = 2 - -order_codes = { - 0: '<', - 1: '>', - 2: 'VAX D-float', #! - 3: 'VAX G-float', - 4: 'Cray', #!! - } - - -class Mat4ArrayReader(MatArrayReader): - ''' Class for reading Mat4 arrays - ''' - - def matrix_getter_factory(self): - ''' Read header, return matrix getter ''' - data = self.read_dtype(self.dtypes['header']) - header = {} - header['name'] = self.read_ztstring(data['namlen']) - if data['mopt'] < 0 or data['mopt'] > 5000: - ValueError, 'Mat 4 mopt wrong format, byteswapping problem?' - M,rest = divmod(data['mopt'], 1000) - O,rest = divmod(rest,100) - P,rest = divmod(rest,10) - T = rest - if O != 0: - raise ValueError, 'O in MOPT integer should be 0, wrong format?' - header['dtype'] = self.dtypes[P] - header['mclass'] = T - header['dims'] = (data['mrows'], data['ncols']) - header['is_complex'] = data['imagf'] == 1 - remaining_bytes = header['dtype'].itemsize * N.product(header['dims']) - if header['is_complex'] and not header['mclass'] == mxSPARSE_CLASS: - remaining_bytes *= 2 - next_pos = self.mat_stream.tell() + remaining_bytes - if T == mxFULL_CLASS: - getter = Mat4FullGetter(self, header) - elif T == mxCHAR_CLASS: - getter = Mat4CharGetter(self, header) - elif T == mxSPARSE_CLASS: - getter = Mat4SparseGetter(self, header) - else: - raise TypeError, 'No reader for class code %s' % T - getter.next_position = next_pos - return getter - - -class Mat4MatrixGetter(MatMatrixGetter): - - # Mat4 variables never global or logical - is_global = False - is_logical = False - - def read_array(self, copy=True): - ''' Mat4 read array always uses header dtype and dims - copy - copies array if True - (buffer is usually read only) - a_dtype is assumed to be correct endianness - ''' - dt = self.header['dtype'] - dims = self.header['dims'] - num_bytes = dt.itemsize - for d in dims: - num_bytes *= d - arr = N.ndarray(shape=dims, - dtype=dt, - buffer=self.mat_stream.read(num_bytes), - order='F') - if copy: - arr = arr.copy() - return arr - - -class Mat4FullGetter(Mat4MatrixGetter): - def __init__(self, array_reader, header): - super(Mat4FullGetter, self).__init__(array_reader, header) - if header['is_complex']: - self.mat_dtype = N.dtype(N.complex128) - else: - self.mat_dtype = N.dtype(N.float64) - - def get_raw_array(self): - if self.header['is_complex']: - # avoid array copy to save memory - res = self.read_array(copy=False) - res_j = self.read_array(copy=False) - return res + (res_j * 1j) - return self.read_array() - - -class Mat4CharGetter(Mat4MatrixGetter): - def get_raw_array(self): - arr = self.read_array().astype(N.uint8) - # ascii to unicode - S = arr.tostring().decode('ascii') - return N.ndarray(shape=self.header['dims'], - dtype=N.dtype('U1'), - buffer = N.array(S)).copy() - - -class Mat4SparseGetter(Mat4MatrixGetter): - ''' Read sparse matrix type - - Matlab (TM) 4 real sparse arrays are saved in a N+1 by 3 array - format, where N is the number of non-zero values. Column 1 values - [0:N] are the (1-based) row indices of the each non-zero value, - column 2 [0:N] are the column indices, column 3 [0:N] are the - (real) values. The last values [-1,0:2] of the rows, column - indices are shape[0] and shape[1] respectively of the output - matrix. The last value for the values column is a padding 0. mrows - and ncols values from the header give the shape of the stored - matrix, here [N+1, 3]. Complex data is saved as a 4 column - matrix, where the fourth column contains the imaginary component; - the last value is again 0. Complex sparse data do _not_ have the - header imagf field set to True; the fact that the data are complex - is only detectable because there are 4 storage columns - ''' - def get_raw_array(self): - res = self.read_array() - tmp = res[:-1,:] - dims = res[-1,0:2] - I = N.ascontiguousarray(tmp[:,0],dtype='intc') #fixes byte order also - J = N.ascontiguousarray(tmp[:,1],dtype='intc') - I -= 1 # for 1-based indexing - J -= 1 - if res.shape[1] == 3: - V = N.ascontiguousarray(tmp[:,2],dtype='float') - else: - V = N.ascontiguousarray(tmp[:,2],dtype='complex') - V.imag = tmp[:,3] - if have_sparse: - return scipy.sparse.coo_matrix((V,(I,J)), dims) - return (dims, I, J, V) - - -class MatFile4Reader(MatFileReader): - ''' Reader for Mat4 files ''' - def __init__(self, mat_stream, *args, **kwargs): - self._array_reader = Mat4ArrayReader( - mat_stream, - None, - None, - ) - super(MatFile4Reader, self).__init__(mat_stream, *args, **kwargs) - self._array_reader.processor_func = self.processor_func - - def set_dtypes(self): - self.dtypes = self.convert_dtypes(mdtypes_template) - self._array_reader.dtypes = self.dtypes - - def matrix_getter_factory(self): - return self._array_reader.matrix_getter_factory() - - def format_looks_right(self): - # Mat4 files have a zero somewhere in first 4 bytes - self.mat_stream.seek(0) - mopt_bytes = N.ndarray(shape=(4,), - dtype=N.uint8, - buffer = self.mat_stream.read(4)) - self.mat_stream.seek(0) - return 0 in mopt_bytes - - def guess_byte_order(self): - self.mat_stream.seek(0) - mopt = self.read_dtype(N.dtype('i4')) - self.mat_stream.seek(0) - if mopt < 0 or mopt > 5000: - return ByteOrder.swapped_code - return ByteOrder.native_code - - -class Mat4MatrixWriter(MatStreamWriter): - - def write_header(self, P=0, T=0, imagf=0, dims=None): - ''' Write header for given data options - P - mat4 data type - T - mat4 matrix class - imagf - complex flag - dims - matrix dimensions - ''' - if dims is None: - dims = self.arr.shape - header = N.empty((), mdtypes_template['header']) - M = not ByteOrder.little_endian - O = 0 - header['mopt'] = (M * 1000 + - O * 100 + - P * 10 + - T) - header['mrows'] = dims[0] - header['ncols'] = dims[1] - header['imagf'] = imagf - header['namlen'] = len(self.name) + 1 - self.write_bytes(header) - self.write_string(self.name + '\0') - - def arr_to_2d(self): - self.arr = N.atleast_2d(self.arr) - dims = self.arr.shape - if len(dims) > 2: - self.arr = self.arr.reshape(-1,dims[-1]) - - def write(self): - assert False, 'Not implemented' - - -class Mat4NumericWriter(Mat4MatrixWriter): - - def write(self): - self.arr_to_2d() - imagf = self.arr.dtype.kind == 'c' - try: - P = np_to_mtypes[self.arr.dtype.str[1:]] - except KeyError: - if imagf: - self.arr = self.arr.astype('c128') - else: - self.arr = self.arr.astype('f8') - P = miDOUBLE - self.write_header(P=P, - T=mxFULL_CLASS, - imagf=imagf) - if imagf: - self.write_bytes(self.arr.real) - self.write_bytes(self.arr.imag) - else: - self.write_bytes(self.arr) - - -class Mat4CharWriter(Mat4MatrixWriter): - - def write(self): - self.arr_to_chars() - self.arr_to_2d() - dims = self.arr.shape - self.write_header(P=miUINT8, - T=mxCHAR_CLASS) - if self.arr.dtype.kind == 'U': - # Recode unicode to ascii - n_chars = N.product(dims) - st_arr = N.ndarray(shape=(), - dtype=self.arr_dtype_number(n_chars), - buffer=self.arr) - st = st_arr.item().encode('ascii') - self.arr = N.ndarray(shape=dims, dtype='S1', buffer=st) - self.write_bytes(self.arr) - - -class Mat4SparseWriter(Mat4MatrixWriter): - - def write(self): - ''' Sparse matrices are 2D - See docstring for Mat4SparseGetter - ''' - imagf = self.arr.dtype.kind == 'c' - nnz = self.arr.nnz - ijd = N.zeros((nnz+1, 3+imagf), dtype='f8') - for i in range(nnz): - ijd[i,0], ijd[i,1] = self.arr.rowcol(i) - ijd[:-1,0:2] += 1 # 1 based indexing - if imagf: - ijd[:-1,2] = self.arr.data.real - ijd[:-1,3] = self.arr.data.imag - else: - ijd[:-1,2] = self.arr.data - ijd[-1,0:2] = self.arr.shape - self.write_header(P=miDOUBLE, - T=mxSPARSE_CLASS, - dims=ijd.shape) - self.write_bytes(ijd) - - -def matrix_writer_factory(stream, arr, name): - ''' Factory function to return matrix writer given variable to write - stream - file or file-like stream to write to - arr - array to write - name - name in matlab (TM) workspace - ''' - if have_sparse: - if scipy.sparse.issparse(arr): - return Mat4SparseWriter(stream, arr, name) - arr = N.array(arr) - dtt = arr.dtype.type - if dtt is N.object_: - raise TypeError, 'Cannot save object arrays in Mat4' - elif dtt is N.void: - raise TypeError, 'Cannot save void type arrays' - elif dtt in (N.unicode_, N.string_): - return Mat4CharWriter(stream, arr, name) - else: - return Mat4NumericWriter(stream, arr, name) - - -class MatFile4Writer(MatFileWriter): - - def put_variables(self, mdict): - for name, var in mdict.items(): - matrix_writer_factory(self.file_stream, var, name).write() Copied: trunk/scipy/io/matlab/mio4.py (from rev 3757, branches/io_new/matlab/mio4.py) Deleted: trunk/scipy/io/matlab/mio5.py =================================================================== --- branches/io_new/matlab/mio5.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/matlab/mio5.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,807 +0,0 @@ -''' Classes for read / write of matlab (TM) 5 files -''' - -# Small fragments of current code adapted from matfile.py by Heiko -# Henkelmann - -## Notice in matfile.py file - -# Copyright (c) 2003 Heiko Henkelmann - -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: - -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. - -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -# DEALINGS IN THE SOFTWARE. - -import zlib -from copy import copy as pycopy -from cStringIO import StringIO -import numpy as N - -from miobase import * - -try: # Python 2.3 support - from sets import Set as set -except: - pass - -miINT8 = 1 -miUINT8 = 2 -miINT16 = 3 -miUINT16 = 4 -miINT32 = 5 -miUINT32 = 6 -miSINGLE = 7 -miDOUBLE = 9 -miINT64 = 12 -miUINT64 = 13 -miMATRIX = 14 -miCOMPRESSED = 15 -miUTF8 = 16 -miUTF16 = 17 -miUTF32 = 18 - -mxCELL_CLASS = 1 -mxSTRUCT_CLASS = 2 -mxOBJECT_CLASS = 3 -mxCHAR_CLASS = 4 -mxSPARSE_CLASS = 5 -mxDOUBLE_CLASS = 6 -mxSINGLE_CLASS = 7 -mxINT8_CLASS = 8 -mxUINT8_CLASS = 9 -mxINT16_CLASS = 10 -mxUINT16_CLASS = 11 -mxINT32_CLASS = 12 -mxUINT32_CLASS = 13 - -mdtypes_template = { - miINT8: 'i1', - miUINT8: 'u1', - miINT16: 'i2', - miUINT16: 'u2', - miINT32: 'i4', - miUINT32: 'u4', - miSINGLE: 'f4', - miDOUBLE: 'f8', - miINT64: 'i8', - miUINT64: 'u8', - miUTF8: 'u1', - miUTF16: 'u2', - miUTF32: 'u4', - 'file_header': [('description', 'S116'), - ('subsystem_offset', 'i8'), - ('version', 'u2'), - ('endian_test', 'S2')], - 'tag_full': [('mdtype', 'u4'), ('byte_count', 'u4')], - 'array_flags': [('data_type', 'u4'), - ('byte_count', 'u4'), - ('flags_class','u4'), - ('nzmax', 'u4')], - 'U1': 'U1', - } - -mclass_dtypes_template = { - mxINT8_CLASS: 'i1', - mxUINT8_CLASS: 'u1', - mxINT16_CLASS: 'i2', - mxUINT16_CLASS: 'u2', - mxINT32_CLASS: 'i4', - mxUINT32_CLASS: 'u4', - mxSINGLE_CLASS: 'f4', - mxDOUBLE_CLASS: 'f8', - } - - -np_to_mtypes = { - 'f8': miDOUBLE, - 'c32': miDOUBLE, - 'c24': miDOUBLE, - 'c16': miDOUBLE, - 'f4': miSINGLE, - 'c8': miSINGLE, - 'i1': miINT8, - 'i2': miINT16, - 'i4': miINT32, - 'u1': miUINT8, - 'u4': miUINT32, - 'u2': miUINT16, - 'S1': miUINT8, - 'U1': miUTF16, - } - - -np_to_mxtypes = { - 'f8': mxDOUBLE_CLASS, - 'c32': mxDOUBLE_CLASS, - 'c24': mxDOUBLE_CLASS, - 'c16': mxDOUBLE_CLASS, - 'f4': mxSINGLE_CLASS, - 'c8': mxSINGLE_CLASS, - 'i4': mxINT32_CLASS, - 'i2': mxINT16_CLASS, - 'u2': mxUINT16_CLASS, - 'u1': mxUINT8_CLASS, - 'S1': mxUINT8_CLASS, - } - - - -''' Before release v7.1 (release 14) matlab (TM) used the system -default character encoding scheme padded out to 16-bits. Release 14 -and later use Unicode. When saving character data, R14 checks if it -can be encoded in 7-bit ascii, and saves in that format if so.''' - -codecs_template = { - miUTF8: {'codec': 'utf_8', 'width': 1}, - miUTF16: {'codec': 'utf_16', 'width': 2}, - miUTF32: {'codec': 'utf_32','width': 4}, - } - -miUINT16_codec = sys.getdefaultencoding() - -mx_numbers = ( - mxDOUBLE_CLASS, - mxSINGLE_CLASS, - mxINT8_CLASS, - mxUINT8_CLASS, - mxINT16_CLASS, - mxUINT16_CLASS, - mxINT32_CLASS, - mxUINT32_CLASS, - ) - -class mat_struct(object): - ''' Placeholder for holding read data from structs ''' - pass - -class mat_obj(object): - ''' Placeholder for holding read data from objects ''' - pass - -class Mat5ArrayReader(MatArrayReader): - ''' Class to get Mat5 arrays - - Provides element reader functions, header reader, matrix reader - factory function - ''' - - def __init__(self, mat_stream, dtypes, processor_func, codecs, class_dtypes): - super(Mat5ArrayReader, self).__init__(mat_stream, - dtypes, - processor_func, - ) - self.codecs = codecs - self.class_dtypes = class_dtypes - - def read_element(self, copy=True): - raw_tag = self.mat_stream.read(8) - tag = N.ndarray(shape=(), - dtype=self.dtypes['tag_full'], - buffer = raw_tag) - mdtype = tag['mdtype'].item() - byte_count = mdtype >> 16 - if byte_count: # small data element format - if byte_count > 4: - raise ValueError, 'Too many bytes for sde format' - mdtype = mdtype & 0xFFFF - dt = self.dtypes[mdtype] - el_count = byte_count / dt.itemsize - return N.ndarray(shape=(el_count,), - dtype=dt, - buffer=raw_tag[4:]) - byte_count = tag['byte_count'].item() - if mdtype == miMATRIX: - return self.current_getter(byte_count).get_array() - if mdtype in self.codecs: # encoded char data - raw_str = self.mat_stream.read(byte_count) - codec = self.codecs[mdtype] - if not codec: - raise TypeError, 'Do not support encoding %d' % mdtype - el = raw_str.decode(codec) - else: # numeric data - dt = self.dtypes[mdtype] - el_count = byte_count / dt.itemsize - el = N.ndarray(shape=(el_count,), - dtype=dt, - buffer=self.mat_stream.read(byte_count)) - if copy: - el = el.copy() - mod8 = byte_count % 8 - if mod8: - self.mat_stream.seek(8 - mod8, 1) - return el - - def matrix_getter_factory(self): - ''' Returns reader for next matrix at top level ''' - tag = self.read_dtype(self.dtypes['tag_full']) - mdtype = tag['mdtype'].item() - byte_count = tag['byte_count'].item() - next_pos = self.mat_stream.tell() + byte_count - if mdtype == miCOMPRESSED: - getter = Mat5ZArrayReader(self, byte_count).matrix_getter_factory() - elif not mdtype == miMATRIX: - raise TypeError, \ - 'Expecting miMATRIX type here, got %d' % mdtype - else: - getter = self.current_getter(byte_count) - getter.next_position = next_pos - return getter - - def current_getter(self, byte_count): - ''' Return matrix getter for current stream position - - Returns matrix getters at top level and sub levels - ''' - if not byte_count: # an empty miMATRIX can contain no bytes - return Mat5EmptyMatrixGetter(self) - af = self.read_dtype(self.dtypes['array_flags']) - header = {} - flags_class = af['flags_class'] - mc = flags_class & 0xFF - header['mclass'] = mc - header['is_logical'] = flags_class >> 9 & 1 - header['is_global'] = flags_class >> 10 & 1 - header['is_complex'] = flags_class >> 11 & 1 - header['nzmax'] = af['nzmax'] - header['dims'] = self.read_element() - header['name'] = self.read_element().tostring() - if mc in mx_numbers: - return Mat5NumericMatrixGetter(self, header) - if mc == mxSPARSE_CLASS: - return Mat5SparseMatrixGetter(self, header) - if mc == mxCHAR_CLASS: - return Mat5CharMatrixGetter(self, header) - if mc == mxCELL_CLASS: - return Mat5CellMatrixGetter(self, header) - if mc == mxSTRUCT_CLASS: - return Mat5StructMatrixGetter(self, header) - if mc == mxOBJECT_CLASS: - return Mat5ObjectMatrixGetter(self, header) - raise TypeError, 'No reader for class code %s' % mc - - -class Mat5ZArrayReader(Mat5ArrayReader): - ''' Getter for compressed arrays - - Reads and uncompresses gzipped stream on init, providing wrapper - for this new sub-stream. - ''' - def __init__(self, array_reader, byte_count): - '''Reads and uncompresses gzipped stream''' - data = array_reader.mat_stream.read(byte_count) - super(Mat5ZArrayReader, self).__init__( - StringIO(zlib.decompress(data)), - array_reader.dtypes, - array_reader.processor_func, - array_reader.codecs, - array_reader.class_dtypes) - - -class Mat5MatrixGetter(MatMatrixGetter): - ''' Base class for getting Mat5 matrices - - Gets current read information from passed array_reader - ''' - - def __init__(self, array_reader, header): - super(Mat5MatrixGetter, self).__init__(array_reader, header) - self.class_dtypes = array_reader.class_dtypes - self.codecs = array_reader.codecs - self.is_global = header['is_global'] - self.mat_dtype = None - - def read_element(self, *args, **kwargs): - return self.array_reader.read_element(*args, **kwargs) - - -class Mat5EmptyMatrixGetter(Mat5MatrixGetter): - ''' Dummy class to return empty array for empty matrix - ''' - def __init__(self, array_reader): - self.array_reader = array_reader - self.mat_stream = array_reader.mat_stream - self.data_position = self.mat_stream.tell() - self.header = {} - self.is_global = False - self.mat_dtype = 'f8' - - def get_raw_array(self): - return N.array([[]]) - - -class Mat5NumericMatrixGetter(Mat5MatrixGetter): - - def __init__(self, array_reader, header): - super(Mat5NumericMatrixGetter, self).__init__(array_reader, header) - if header['is_logical']: - self.mat_dtype = N.dtype('bool') - else: - self.mat_dtype = self.class_dtypes[header['mclass']] - - def get_raw_array(self): - if self.header['is_complex']: - # avoid array copy to save memory - res = self.read_element(copy=False) - res_j = self.read_element(copy=False) - res = res + (res_j * 1j) - else: - res = self.read_element() - return N.ndarray(shape=self.header['dims'], - dtype=res.dtype, - buffer=res, - order='F') - - -class Mat5SparseMatrixGetter(Mat5MatrixGetter): - def get_raw_array(self): - rowind = self.read_element() - indptr = self.read_element() - if self.header['is_complex']: - # avoid array copy to save memory - data = self.read_element(copy=False) - data_j = self.read_element(copy=False) - data = data + (data_j * 1j) - else: - data = self.read_element() - ''' From the matlab (TM) API documentation, last found here: - http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/ - rowind are simply the row indices for all the (res) non-zero - entries in the sparse array. rowind has nzmax entries, so - may well have more entries than len(res), the actual number - of non-zero entries, but rowind[len(res):] can be discarded - and should be 0. indptr has length (number of columns + 1), - and is such that, if D = diff(colind), D[j] gives the number - of non-zero entries in column j. Because rowind values are - stored in column order, this gives the column corresponding to - each rowind - ''' - if have_sparse: - dims = self.header['dims'] - return scipy.sparse.csc_matrix((data,rowind,indptr), dims) - else: - return (dims, data, rowind, indptr) - - -class Mat5CharMatrixGetter(Mat5MatrixGetter): - def get_raw_array(self): - res = self.read_element() - # Convert non-string types to unicode - if isinstance(res, N.ndarray): - if res.dtype.type == N.uint16: - codec = miUINT16_codec - if self.codecs['uint16_len'] == 1: - res = res.astype(N.uint8) - elif res.dtype.type in (N.uint8, N.int8): - codec = 'ascii' - else: - raise TypeError, 'Did not expect type %s' % res.dtype - res = res.tostring().decode(codec) - return N.ndarray(shape=self.header['dims'], - dtype=N.dtype('U1'), - buffer=N.array(res), - order='F').copy() - - -class Mat5CellMatrixGetter(Mat5MatrixGetter): - def get_raw_array(self): - # Account for fortran indexing of cells - tupdims = tuple(self.header['dims'][::-1]) - length = N.product(tupdims) - result = N.empty(length, dtype=object) - for i in range(length): - result[i] = self.get_item() - return result.reshape(tupdims).T - - def get_item(self): - return self.read_element() - - -class Mat5StructMatrixGetter(Mat5CellMatrixGetter): - def __init__(self, *args, **kwargs): - super(Mat5StructMatrixGetter, self).__init__(*args, **kwargs) - self.obj_template = mat_struct() - - def get_raw_array(self): - namelength = self.read_element()[0] - # get field names - names = self.read_element() - splitnames = [names[i:i+namelength] for i in \ - xrange(0,len(names),namelength)] - self.obj_template._fieldnames = [x.tostring().strip('\x00') - for x in splitnames] - return super(Mat5StructMatrixGetter, self).get_raw_array() - - def get_item(self): - item = pycopy(self.obj_template) - for element in item._fieldnames: - item.__dict__[element] = self.read_element() - return item - - -class Mat5ObjectMatrixGetter(Mat5StructMatrixGetter): - def __init__(self, *args, **kwargs): - super(Mat5StructMatrixGetter, self).__init__(*args, **kwargs) - self.obj_template = mat_obj() - - def get_raw_array(self): - self.obj_template._classname = self.read_element().tostring() - return super(Mat5ObjectMatrixGetter, self).get_raw_array() - - -class MatFile5Reader(MatFileReader): - ''' Reader for Mat 5 mat files - - Adds the following attribute to base class - - uint16_codec - char codec to use for uint16 char arrays - (defaults to system default codec) - ''' - - def __init__(self, - mat_stream, - byte_order=None, - mat_dtype=False, - squeeze_me=True, - chars_as_strings=True, - matlab_compatible=False, - uint16_codec=None - ): - self.codecs = {} - self._array_reader = Mat5ArrayReader( - mat_stream, - None, - None, - None, - None, - ) - super(MatFile5Reader, self).__init__( - mat_stream, - byte_order, - mat_dtype, - squeeze_me, - chars_as_strings, - matlab_compatible, - ) - self._array_reader.processor_func = self.processor_func - self.uint16_codec = uint16_codec - - def get_uint16_codec(self): - return self._uint16_codec - def set_uint16_codec(self, uint16_codec): - if not uint16_codec: - uint16_codec = sys.getdefaultencoding() - # Set length of miUINT16 char encoding - self.codecs['uint16_len'] = len(" ".encode(uint16_codec)) \ - - len(" ".encode(uint16_codec)) - self.codecs['uint16_codec'] = uint16_codec - self._array_reader.codecs = self.codecs - self._uint16_codec = uint16_codec - uint16_codec = property(get_uint16_codec, - set_uint16_codec, - None, - 'get/set uint16_codec') - - def set_dtypes(self): - ''' Set dtypes and codecs ''' - self.dtypes = self.convert_dtypes(mdtypes_template) - self.class_dtypes = self.convert_dtypes(mclass_dtypes_template) - codecs = {} - postfix = self.order_code == '<' and '_le' or '_be' - for k, v in codecs_template.items(): - codec = v['codec'] - try: - " ".encode(codec) - except LookupError: - codecs[k] = None - continue - if v['width'] > 1: - codec += postfix - codecs[k] = codec - self.codecs.update(codecs) - self.update_array_reader() - - def update_array_reader(self): - self._array_reader.codecs = self.codecs - self._array_reader.dtypes = self.dtypes - self._array_reader.class_dtypes = self.class_dtypes - - def matrix_getter_factory(self): - return self._array_reader.matrix_getter_factory() - - def guess_byte_order(self): - self.mat_stream.seek(126) - mi = self.mat_stream.read(2) - self.mat_stream.seek(0) - return mi == 'IM' and '<' or '>' - - def file_header(self): - ''' Read in mat 5 file header ''' - hdict = {} - hdr = self.read_dtype(self.dtypes['file_header']) - hdict['__header__'] = hdr['description'].item().strip(' \t\n\000') - v_major = hdr['version'] >> 8 - v_minor = hdr['version'] & 0xFF - hdict['__version__'] = '%d.%d' % (v_major, v_minor) - return hdict - - def format_looks_right(self): - # Mat4 files have a zero somewhere in first 4 bytes - self.mat_stream.seek(0) - mopt_bytes = N.ndarray(shape=(4,), - dtype=N.uint8, - buffer = self.mat_stream.read(4)) - self.mat_stream.seek(0) - return 0 not in mopt_bytes - - -class Mat5MatrixWriter(MatStreamWriter): - - mat_tag = N.zeros((), mdtypes_template['tag_full']) - mat_tag['mdtype'] = miMATRIX - - def __init__(self, file_stream, arr, name, is_global=False): - super(Mat5MatrixWriter, self).__init__(file_stream, arr, name) - self.is_global = is_global - - def write_dtype(self, arr): - self.file_stream.write(arr.tostring()) - - def write_element(self, arr, mdtype=None): - # write tag, data - tag = N.zeros((), mdtypes_template['tag_full']) - if mdtype is None: - tag['mdtype'] = np_to_mtypes[arr.dtype.str[1:]] - else: - tag['mdtype'] = mdtype - tag['byte_count'] = arr.size*arr.itemsize - self.write_dtype(tag) - self.write_bytes(arr) - # do 8 byte padding if needed - if tag['byte_count']%8 != 0: - pad = (1+tag['byte_count']//8)*8 - tag['byte_count'] - self.write_bytes(N.zeros((pad,),dtype='u1')) - - def write_header(self, mclass, - is_global=False, - is_complex=False, - is_logical=False, - nzmax=0): - ''' Write header for given data options - mclass - mat5 matrix class - is_global - True if matrix is global - is_complex - True is matrix is complex - is_logical - True if matrix is logical - nzmax - max non zero elements for sparse arrays - ''' - self._mat_tag_pos = self.file_stream.tell() - self.write_dtype(self.mat_tag) - # write array flags (complex, global, logical, class, nzmax) - af = N.zeros((), mdtypes_template['array_flags']) - af['data_type'] = miUINT32 - af['byte_count'] = 8 - flags = is_complex << 3 | is_global << 2 | is_logical << 1 - af['flags_class'] = mclass | flags << 8 - af['nzmax'] = nzmax - self.write_dtype(af) - # write array shape - self.arr=N.atleast_2d(self.arr) - self.write_element(N.array(self.arr.shape, dtype='i4')) - # write name - self.write_element(N.ndarray(shape=len(self.name), dtype='S1', buffer=self.name)) - - def update_matrix_tag(self): - curr_pos = self.file_stream.tell() - self.file_stream.seek(self._mat_tag_pos) - self.mat_tag['byte_count'] = curr_pos - self._mat_tag_pos - 8 - self.write_dtype(self.mat_tag) - self.file_stream.seek(curr_pos) - - def write(self): - assert False, 'Not implemented' - - -class Mat5NumericWriter(Mat5MatrixWriter): - - def write(self): - imagf = self.arr.dtype.kind == 'c' - try: - mclass = np_to_mxtypes[self.arr.dtype.str[1:]] - except KeyError: - if imagf: - self.arr = self.arr.astype('c128') - else: - self.arr = self.arr.astype('f8') - mclass = mxDOUBLE_CLASS - self.write_header(mclass=mclass,is_complex=imagf) - if imagf: - self.write_element(self.arr.real) - self.write_element(self.arr.imag) - else: - self.write_element(self.arr) - self.update_matrix_tag() - -class Mat5CharWriter(Mat5MatrixWriter): - codec='ascii' - def write(self): - self.arr_to_chars() - self.write_header(mclass=mxCHAR_CLASS) - if self.arr.dtype.kind == 'U': - # Recode unicode using self.codec - n_chars = N.product(self.arr.shape) - st_arr = N.ndarray(shape=(), - dtype=self.arr_dtype_number(n_chars), - buffer=self.arr) - st = st_arr.item().encode(self.codec) - self.arr = N.ndarray(shape=(len(st)), dtype='u1', buffer=st) - self.write_element(self.arr,mdtype=miUTF8) - self.update_matrix_tag() - -class Mat5UniCharWriter(Mat5CharWriter): - codec='UTF8' - - -class Mat5SparseWriter(Mat5MatrixWriter): - - def write(self): - ''' Sparse matrices are 2D - See docstring for Mat5SparseGetter - ''' - imagf = self.arr.dtype.kind == 'c' - N = self.arr.nnz - ijd = N.zeros((N+1, 3+imagf), dtype='f8') - for i in range(N): - ijd[i,0], ijd[i,1] = self.arr.rowcol(i) - ijd[:-1,0:2] += 1 # 1 based indexing - if imagf: - ijd[:-1,2] = self.arr.data.real - ijd[:-1,3] = self.arr.data.imag - else: - ijd[:-1,2] = self.arr.data - ijd[-1,0:2] = self.arr.shape - self.write_header(P=miDOUBLE, - T=mxSPARSE_CLASS, - dims=ijd.shape) - self.write_bytes(ijd) - - -class Mat5WriterGetter(object): - ''' Wraps stream and options, provides methods for getting Writer objects ''' - def __init__(self, stream, unicode_strings): - self.stream = stream - self.unicode_strings = unicode_strings - - def rewind(self): - self.stream.seek(0) - - def matrix_writer_factory(self, arr, name, is_global=False): - ''' Factory function to return matrix writer given variable to write - stream - file or file-like stream to write to - arr - array to write - name - name in matlab (TM) workspace - ''' - if have_sparse: - if scipy.sparse.issparse(arr): - return Mat5SparseWriter(self.stream, arr, name, is_global) - arr = N.array(arr) - if arr.dtype.hasobject: - types, arr_type = self.classify_mobjects(arr) - if arr_type == 'c': - return Mat5CellWriter(self.stream, arr, name, is_global, types) - elif arr_type == 's': - return Mat5StructWriter(self.stream, arr, name, is_global) - elif arr_type == 'o': - return Mat5ObjectWriter(self.stream, arr, name, is_global) - if arr.dtype.kind in ('U', 'S'): - if self.unicode_strings: - return Mat5UniCharWriter(self.stream, arr, name, is_global) - else: - return Mat5CharWriter(self.stream, arr, name, is_global) - else: - return Mat5NumericWriter(self.stream, arr, name, is_global) - - def classify_mobjects(self, objarr): - ''' Function to classify objects passed for writing - returns - types - S1 array of same shape as objarr with codes for each object - i - invalid object - a - ndarray - s - matlab struct - o - matlab object - arr_type - one of - c - cell array - s - struct array - o - object array - ''' - n = objarr.size - types = N.empty((n,), dtype='S1') - types[:] = 'i' - type_set = set() - flato = objarr.flat - for i in range(n): - obj = flato[i] - if isinstance(obj, N.ndarray): - types[i] = 'a' - continue - try: - fns = tuple(obj._fieldnames) - except AttributeError: - continue - try: - cn = obj._classname - except AttributeError: - types[i] = 's' - type_set.add(fns) - continue - types[i] = 'o' - type_set.add((cn, fns)) - arr_type = 'c' - if len(set(types))==1 and len(type_set) == 1: - arr_type = types[0] - return types.reshape(objarr.shape), arr_type - - -class MatFile5Writer(MatFileWriter): - ''' Class for writing mat5 files ''' - def __init__(self, file_stream, - do_compression=False, - unicode_strings=False, - global_vars=None): - super(MatFile5Writer, self).__init__(file_stream) - self.do_compression = do_compression - if global_vars: - self.global_vars = global_vars - else: - self.global_vars = [] - self.writer_getter = Mat5WriterGetter( - StringIO(), - unicode_strings) - # write header - import os, time - hdr = N.zeros((), mdtypes_template['file_header']) - hdr['description']='MATLAB 5.0 MAT-file Platform: %s, Created on: %s' % ( - os.name,time.asctime()) - hdr['version']= 0x0100 - hdr['endian_test']=N.ndarray(shape=(),dtype='S2',buffer=N.uint16(0x4d49)) - file_stream.write(hdr.tostring()) - - def get_unicode_strings(self): - return self.write_getter.unicode_strings - def set_unicode_strings(self, unicode_strings): - self.writer_getter.unicode_strings = unicode_strings - unicode_strings = property(get_unicode_strings, - set_unicode_strings, - None, - 'get/set unicode strings property') - - def put_variables(self, mdict): - for name, var in mdict.items(): - is_global = name in self.global_vars - self.writer_getter.rewind() - self.writer_getter.matrix_writer_factory( - var, - name, - is_global, - ).write() - stream = self.writer_getter.stream - if self.do_compression: - str = zlib.compress(stream.getvalue(stream.tell())) - tag = N.empty((), mdtypes_template['tag_full']) - tag['mdtype'] = miCOMPRESSED - tag['byte_count'] = len(str) - self.file_stream.write(tag.tostring() + str) - else: - self.file_stream.write(stream.getvalue(stream.tell())) Copied: trunk/scipy/io/matlab/mio5.py (from rev 3757, branches/io_new/matlab/mio5.py) Deleted: trunk/scipy/io/matlab/miobase.py =================================================================== --- branches/io_new/matlab/miobase.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/matlab/miobase.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,379 +0,0 @@ -# Authors: Travis Oliphant, Matthew Brett - -""" -Base classes for matlab (TM) file stream reading -""" - -import sys - -import numpy as N - -try: - import scipy.sparse - have_sparse = 1 -except ImportError: - have_sparse = 0 - - -def small_product(arr): - ''' Faster than product for small arrays ''' - res = 1 - for e in arr: - res *= e - return res - -class ByteOrder(object): - ''' Namespace for byte ordering ''' - little_endian = sys.byteorder == 'little' - native_code = little_endian and '<' or '>' - swapped_code = little_endian and '>' or '<' - - def to_numpy_code(code): - if code is None: - return ByteOrder.native_code - if code in ('little', '<', 'l', 'L'): - return '<' - elif code in ('BIG', '>', 'B', 'b'): - return '>' - elif code in ('native', '='): - return ByteOrder.native_code - elif code in ('swapped'): - return ByteOrder.swapped_code - else: - raise ValueError, 'We cannot handle byte order %s' % byte_order - to_numpy_code = staticmethod(to_numpy_code) - - -class MatStreamAgent(object): - ''' Base object for readers / getters from mat file streams - - Attaches to initialized stream - - Base class for "getters" - which do store state of what they are - reading on itialization, and therefore need to be initialized - before each read, and "readers" which do not store state, and only - need to be initialized once on object creation - - Implements common array reading functions - - Inputs mat_steam - MatFileReader object - ''' - - def __init__(self, mat_stream): - self.mat_stream = mat_stream - - def read_dtype(self, a_dtype): - ''' Generic get of byte stream data of known type - - Inputs - a_dtype - dtype of array - - a_dtype is assumed to be correct endianness - ''' - num_bytes = a_dtype.itemsize - arr = N.ndarray(shape=(), - dtype=a_dtype, - buffer=self.mat_stream.read(num_bytes), - order='F') - return arr - - def read_ztstring(self, num_bytes): - return self.mat_stream.read(num_bytes).strip('\x00') - - -class MatFileReader(MatStreamAgent): - """ Base object for reading mat files - - mat_stream - initialized byte stream object - file io interface object - byte_order - byte order ('native', 'little', 'BIG') - in ('native', '=') - or in ('little', '<') - or in ('BIG', '>') - mat_dtype - return arrays in same dtype as loaded into matlab - (instead of the dtype with which they are saved) - squeeze_me - whether to squeeze unit dimensions or not - chars_as_strings - whether to convert char arrays to string arrays - mat_dtype - return matrices with datatype that matlab would load as - (rather than in the datatype matlab saves as) - matlab_compatible - returns matrices as would be loaded by matlab - (implies squeeze_me=False, chars_as_strings=False - mat_dtype=True) - - To make this class functional, you will need to override the - following methods: - - set_dtypes - sets data types defs from byte order - matrix_getter_factory - gives object to fetch next matrix from stream - format_looks_right - returns True if format looks correct for - this file type (Mat4, Mat5) - guess_byte_order - guesses file byte order from file - """ - - def __init__(self, mat_stream, - byte_order=None, - mat_dtype=False, - squeeze_me=True, - chars_as_strings=True, - matlab_compatible=False, - ): - # Initialize stream - self.mat_stream = mat_stream - self.dtypes = {} - if not byte_order: - byte_order = self.guess_byte_order() - self.order_code = byte_order # sets dtypes and other things too - if matlab_compatible: - self.set_matlab_compatible() - else: - self._squeeze_me = squeeze_me - self._chars_as_strings = chars_as_strings - self._mat_dtype = mat_dtype - self.processor_func = self.get_processor_func() - - def set_matlab_compatible(self): - ''' Sets options to return arrays as matlab (tm) loads them ''' - self._mat_dtype = True - self._squeeze_me = False - self._chars_as_strings = False - self.processor_func = self.get_processor_func() - - def get_mat_dtype(self): - return self._mat_dtype - def set_mat_dtype(self, mat_dtype): - self._mat_dtype = mat_dtype - self.processor_func = self.get_processor_func() - mat_dtype = property(get_mat_dtype, - set_mat_dtype, - None, - 'get/set mat_dtype property') - - def get_squeeze_me(self): - return self._squeeze_me - def set_squeeze_me(self, squeeze_me): - self._squeeze_me = squeeze_me - self.processor_func = self.get_processor_func() - squeeze_me = property(get_squeeze_me, - set_squeeze_me, - None, - 'get/set squeeze me property') - - def get_chars_as_strings(self): - return self._chars_as_strings - def set_chars_as_strings(self, chars_as_strings): - self._chars_as_strings = chars_as_strings - self.processor_func = self.get_processor_func() - chars_as_strings = property(get_chars_as_strings, - set_chars_as_strings, - None, - 'get/set squeeze me property') - - def get_order_code(self): - return self._order_code - def set_order_code(self, order_code): - order_code = ByteOrder.to_numpy_code(order_code) - self._order_code = order_code - self.set_dtypes() - order_code = property(get_order_code, - set_order_code, - None, - 'get/set order code') - - def set_dtypes(self): - assert False, 'Not implemented' - - def convert_dtypes(self, dtype_template): - dtypes = dtype_template.copy() - for k in dtypes: - dtypes[k] = N.dtype(dtypes[k]).newbyteorder( - self.order_code) - return dtypes - - def matrix_getter_factory(self): - assert False, 'Not implemented' - - def format_looks_right(self): - "Return True if the format looks right for this object" - assert False, 'Not implemented' - - def file_header(self): - return {} - - def guess_byte_order(self): - assert 0, 'Not implemented' - - def get_processor_func(self): - ''' Processing to apply to read matrices - - Function applies options to matrices. We have to pass this - function into the reader routines because Mat5 matrices - occur as submatrices - in cell arrays, structs and objects - - so we will not see these in the main variable getting routine - here. - - The read array is the first argument. - The getter, passed as second argument to the function, must - define properties, iff mat_dtype option is True: - - mat_dtype - data type when loaded into matlab (tm) - (None for no conversion) - - func returns the processed array - ''' - - def func(arr, getter): - if arr.dtype.kind == 'U' and self.chars_as_strings: - # Convert char array to string or array of strings - dims = arr.shape - if len(dims) >= 2: # return array of strings - dtt = self.order_code + 'U' - n_dims = dims[:-1] - str_arr = arr.reshape( - (small_product(n_dims), - dims[-1])) - arr = N.empty(n_dims, dtype=object) - for i in range(0, n_dims[-1]): - arr[...,i] = self.chars_to_str(str_arr[i]) - else: # return string - arr = self.chars_to_str(arr) - if self.mat_dtype: - # Apply options to replicate matlab's (TM) - # load into workspace - if getter.mat_dtype is not None: - arr = arr.astype(getter.mat_dtype) - if self.squeeze_me: - arr = N.squeeze(arr) - if not arr.size: - arr = N.array([]) - elif not arr.shape: # 0d coverted to scalar - arr = arr.item() - return arr - return func - - def chars_to_str(self, str_arr): - ''' Convert string array to string ''' - dt = N.dtype('U' + str(small_product(str_arr.shape))) - return N.ndarray(shape=(), - dtype = dt, - buffer = str_arr.copy()).item() - - def get_variables(self, variable_names=None): - ''' get variables from stream as dictionary - - variable_names - optional list of variable names to get - - If variable_names is None, then get all variables in file - ''' - if isinstance(variable_names, basestring): - variable_names = [variable_names] - self.mat_stream.seek(0) - mdict = self.file_header() - mdict['__globals__'] = [] - while not self.end_of_stream(): - getter = self.matrix_getter_factory() - name = getter.name - if variable_names and name not in variable_names: - getter.to_next() - continue - res = getter.get_array() - mdict[name] = res - if getter.is_global: - mdict['__globals__'].append(name) - if variable_names: - variable_names.remove(name) - if not variable_names: - break - return mdict - - def end_of_stream(self): - b = self.mat_stream.read(1) - self.mat_stream.seek(-1,1) - return len(b) == 0 - - -class MatMatrixGetter(MatStreamAgent): - """ Base class for matrix getters - - Getters are stateful versions of agents, and record state of - current read on initialization, so need to be created for each - read - one-shot objects. - - MatrixGetters are initialized with the content of the matrix - header - - Accepts - array_reader - array reading object (see below) - header - header dictionary for matrix being read - """ - - def __init__(self, array_reader, header): - super(MatMatrixGetter, self).__init__(array_reader.mat_stream) - self.array_reader = array_reader - self.dtypes = array_reader.dtypes - self.header = header - self.name = header['name'] - - def get_array(self): - ''' Gets an array from matrix, and applies any necessary processing ''' - arr = self.get_raw_array() - return self.array_reader.processor_func(arr, self) - - def get_raw_array(self): - assert False, 'Not implemented' - - def to_next(self): - self.mat_stream.seek(self.next_position) - - -class MatArrayReader(MatStreamAgent): - ''' Base class for array readers - - The array_reader contains information about the current reading - process, such as byte ordered dtypes and the processing function - to apply to matrices as they are read, as well as routines for - reading matrix compenents. - ''' - - def __init__(self, mat_stream, dtypes, processor_func): - self.mat_stream = mat_stream - self.dtypes = dtypes - self.processor_func = processor_func - - def matrix_getter_factory(self): - assert False, 'Not implemented' - - -class MatStreamWriter(object): - ''' Base object for writing to mat files ''' - def __init__(self, file_stream, arr, name): - self.file_stream = file_stream - self.arr = arr - dt = self.arr.dtype - if not dt.isnative: - self.arr = self.arr.astype(dt.newbyteorder('=')) - self.name = name - - def arr_dtype_number(self, num): - ''' Return dtype for given number of items per element''' - return N.dtype(self.arr.dtype.str[:2] + str(num)) - - def arr_to_chars(self): - ''' Convert string array to char array ''' - dims = list(self.arr.shape) - if not dims: - dims = [1] - dims.append(int(self.arr.dtype.str[2:])) - self.arr = N.ndarray(shape=dims, - dtype=self.arr_dtype_number(1), - buffer=self.arr) - - def write_bytes(self, arr): - self.file_stream.write(arr.tostring(order='F')) - - def write_string(self, s): - self.file_stream.write(s) - - -class MatFileWriter(object): - ''' Base class for Mat file writers ''' - def __init__(self, file_stream): - self.file_stream = file_stream Copied: trunk/scipy/io/matlab/miobase.py (from rev 3757, branches/io_new/matlab/miobase.py) Deleted: trunk/scipy/io/matlab/setup.py =================================================================== --- branches/io_new/matlab/setup.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/matlab/setup.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,10 +0,0 @@ -#!/usr/bin/env python - -def configuration(parent_package='',top_path=None): - from numpy.distutils.misc_util import Configuration - config = Configuration('matlab', parent_package, top_path) - return config - -if __name__ == '__main__': - from numpy.distutils.core import setup - setup(**configuration(top_path='').todict()) Copied: trunk/scipy/io/matlab/setup.py (from rev 3757, branches/io_new/matlab/setup.py) Deleted: trunk/scipy/io/mio.py =================================================================== --- trunk/scipy/io/mio.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/mio.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,133 +0,0 @@ -# Authors: Travis Oliphant, Matthew Brett - -""" -Module for reading and writing matlab (TM) .mat files -""" - -import os -import sys - -from scipy.io.mio4 import MatFile4Reader, MatFile4Writer -from scipy.io.mio5 import MatFile5Reader, MatFile5Writer - -__all__ = ['find_mat_file', 'mat_reader_factory', 'loadmat', 'savemat'] - -def find_mat_file(file_name, appendmat=True): - ''' Try to find .mat file on system path - - file_name - file name string - append_mat - If True, and file_name does not end in '.mat', appends it - ''' - if appendmat and file_name[-4:] == ".mat": - file_name = file_name[:-4] - if os.sep in file_name: - full_name = file_name - if appendmat: - full_name = file_name + ".mat" - else: - full_name = None - junk, file_name = os.path.split(file_name) - for path in [os.curdir] + list(sys.path): - test_name = os.path.join(path, file_name) - if appendmat: - test_name += ".mat" - try: - fid = open(test_name,'rb') - fid.close() - full_name = test_name - break - except IOError: - pass - return full_name - -def mat_reader_factory(file_name, appendmat=True, **kwargs): - """Create reader for matlab (TM) .mat format files - - See docstring for loadmat for input options - """ - if isinstance(file_name, basestring): - full_name = find_mat_file(file_name, appendmat) - if full_name is None: - raise IOError, "%s not found on the path." % file_name - byte_stream = open(full_name, 'rb') - else: - try: - file_name.read(0) - except AttributeError: - raise IOError, 'Reader needs file name or open file-like object' - byte_stream = file_name - - MR = MatFile4Reader(byte_stream, **kwargs) - if MR.format_looks_right(): - return MR - return MatFile5Reader(byte_stream, **kwargs) - -def loadmat(file_name, mdict=None, appendmat=True, basename='raw', **kwargs): - ''' Load Matlab(tm) file - - file_name - Name of the mat file - (do not need .mat extension if appendmat==True) - If name not a full path name, search for the file on - the sys.path list and use the first one found (the - current directory is searched first). - Can also pass open file-like object - m_dict - optional dictionary in which to insert matfile variables - appendmat - True to append the .mat extension to the end of the - given filename, if not already present - base_name - base name for unnamed variables (unused in code) - byte_order - byte order ('native', 'little', 'BIG') - in ('native', '=') - or in ('little', '<') - or in ('BIG', '>') - mat_dtype - return arrays in same dtype as loaded into matlab - (instead of the dtype with which they are saved) - squeeze_me - whether to squeeze matrix dimensions or not - chars_as_strings - whether to convert char arrays to string arrays - mat_dtype - return matrices with datatype that matlab would load as - (rather than in the datatype matlab saves as) - matlab_compatible - returns matrices as would be loaded by matlab - (implies squeeze_me=False, chars_as_strings=False, - mat_dtype=True) - - v4 (Level 1.0), v6 and v7.1 matfiles are supported. - - ''' - MR = mat_reader_factory(file_name, appendmat, **kwargs) - matfile_dict = MR.get_variables() - if mdict is not None: - mdict.update(matfile_dict) - else: - mdict = matfile_dict - return mdict - -def savemat(file_name, mdict, appendmat=True, format='4'): - """Save a dictionary of names and arrays into the MATLAB-style .mat file. - - This saves the arrayobjects in the given dictionary to a matlab - style .mat file. - - appendmat - if true, appends '.mat' extension to filename, if not present - format - '4' for matlab 4 mat files, '5' for matlab 5 onwards - """ - file_is_string = isinstance(file_name, basestring) - if file_is_string: - if appendmat and file_name[-4:] != ".mat": - file_name = file_name + ".mat" - file_stream = open(file_name, 'wb') - else: - try: - file_name.write('') - except AttributeError: - raise IOError, 'Writer needs file name or writeable '\ - 'file-like object' - file_stream = file_name - - if format == '4': - MW = MatFile4Writer(file_stream) - elif format == '5': - MW = MatFile5Writer(file_stream) - else: - raise ValueError, 'Format should be 4 or 5' - MW.put_variables(mdict) - if file_is_string: - file_stream.close() Deleted: trunk/scipy/io/mio4.py =================================================================== --- trunk/scipy/io/mio4.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/mio4.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,345 +0,0 @@ -''' Classes for read / write of matlab (TM) 4 files -''' - -import numpy as N - -from scipy.io.miobase import * - -miDOUBLE = 0 -miSINGLE = 1 -miINT32 = 2 -miINT16 = 3 -miUINT16 = 4 -miUINT8 = 5 - -mdtypes_template = { - miDOUBLE: 'f8', - miSINGLE: 'f4', - miINT32: 'i4', - miINT16: 'i2', - miUINT16: 'u2', - miUINT8: 'u1', - 'header': [('mopt', 'i4'), - ('mrows', 'i4'), - ('ncols', 'i4'), - ('imagf', 'i4'), - ('namlen', 'i4')], - 'U1': 'U1', - } - -np_to_mtypes = { - 'f8': miDOUBLE, - 'c32': miDOUBLE, - 'c24': miDOUBLE, - 'c16': miDOUBLE, - 'f4': miSINGLE, - 'c8': miSINGLE, - 'i4': miINT32, - 'i2': miINT16, - 'u2': miUINT16, - 'u1': miUINT8, - 'S1': miUINT8, - } - -# matrix classes -mxFULL_CLASS = 0 -mxCHAR_CLASS = 1 -mxSPARSE_CLASS = 2 - -order_codes = { - 0: '<', - 1: '>', - 2: 'VAX D-float', #! - 3: 'VAX G-float', - 4: 'Cray', #!! - } - - -class Mat4ArrayReader(MatArrayReader): - ''' Class for reading Mat4 arrays - ''' - - def matrix_getter_factory(self): - ''' Read header, return matrix getter ''' - data = self.read_dtype(self.dtypes['header']) - header = {} - header['name'] = self.read_ztstring(data['namlen']) - if data['mopt'] < 0 or data['mopt'] > 5000: - ValueError, 'Mat 4 mopt wrong format, byteswapping problem?' - M,rest = divmod(data['mopt'], 1000) - O,rest = divmod(rest,100) - P,rest = divmod(rest,10) - T = rest - if O != 0: - raise ValueError, 'O in MOPT integer should be 0, wrong format?' - header['dtype'] = self.dtypes[P] - header['mclass'] = T - header['dims'] = (data['mrows'], data['ncols']) - header['is_complex'] = data['imagf'] == 1 - remaining_bytes = header['dtype'].itemsize * N.product(header['dims']) - if header['is_complex'] and not header['mclass'] == mxSPARSE_CLASS: - remaining_bytes *= 2 - next_pos = self.mat_stream.tell() + remaining_bytes - if T == mxFULL_CLASS: - getter = Mat4FullGetter(self, header) - elif T == mxCHAR_CLASS: - getter = Mat4CharGetter(self, header) - elif T == mxSPARSE_CLASS: - getter = Mat4SparseGetter(self, header) - else: - raise TypeError, 'No reader for class code %s' % T - getter.next_position = next_pos - return getter - - -class Mat4MatrixGetter(MatMatrixGetter): - - # Mat4 variables never global or logical - is_global = False - is_logical = False - - def read_array(self, copy=True): - ''' Mat4 read array always uses header dtype and dims - copy - copies array if True - (buffer is usually read only) - a_dtype is assumed to be correct endianness - ''' - dt = self.header['dtype'] - dims = self.header['dims'] - num_bytes = dt.itemsize - for d in dims: - num_bytes *= d - arr = N.ndarray(shape=dims, - dtype=dt, - buffer=self.mat_stream.read(num_bytes), - order='F') - if copy: - arr = arr.copy() - return arr - - -class Mat4FullGetter(Mat4MatrixGetter): - def __init__(self, array_reader, header): - super(Mat4FullGetter, self).__init__(array_reader, header) - if header['is_complex']: - self.mat_dtype = N.dtype(N.complex128) - else: - self.mat_dtype = N.dtype(N.float64) - - def get_raw_array(self): - if self.header['is_complex']: - # avoid array copy to save memory - res = self.read_array(copy=False) - res_j = self.read_array(copy=False) - return res + (res_j * 1j) - return self.read_array() - - -class Mat4CharGetter(Mat4MatrixGetter): - def get_raw_array(self): - arr = self.read_array().astype(N.uint8) - # ascii to unicode - S = arr.tostring().decode('ascii') - return N.ndarray(shape=self.header['dims'], - dtype=N.dtype('U1'), - buffer = N.array(S)).copy() - - -class Mat4SparseGetter(Mat4MatrixGetter): - ''' Read sparse matrix type - - Matlab (TM) 4 real sparse arrays are saved in a N+1 by 3 array - format, where N is the number of non-zero values. Column 1 values - [0:N] are the (1-based) row indices of the each non-zero value, - column 2 [0:N] are the column indices, column 3 [0:N] are the - (real) values. The last values [-1,0:2] of the rows, column - indices are shape[0] and shape[1] respectively of the output - matrix. The last value for the values column is a padding 0. mrows - and ncols values from the header give the shape of the stored - matrix, here [N+1, 3]. Complex data is saved as a 4 column - matrix, where the fourth column contains the imaginary component; - the last value is again 0. Complex sparse data do _not_ have the - header imagf field set to True; the fact that the data are complex - is only detectable because there are 4 storage columns - ''' - def get_raw_array(self): - res = self.read_array() - tmp = res[:-1,:] - dims = res[-1,0:2] - I = N.ascontiguousarray(tmp[:,0],dtype='intc') #fixes byte order also - J = N.ascontiguousarray(tmp[:,1],dtype='intc') - I -= 1 # for 1-based indexing - J -= 1 - if res.shape[1] == 3: - V = N.ascontiguousarray(tmp[:,2],dtype='float') - else: - V = N.ascontiguousarray(tmp[:,2],dtype='complex') - V.imag = tmp[:,3] - if have_sparse: - return scipy.sparse.coo_matrix((V,(I,J)), dims) - return (dims, I, J, V) - - -class MatFile4Reader(MatFileReader): - ''' Reader for Mat4 files ''' - def __init__(self, mat_stream, *args, **kwargs): - self._array_reader = Mat4ArrayReader( - mat_stream, - None, - None, - ) - super(MatFile4Reader, self).__init__(mat_stream, *args, **kwargs) - self._array_reader.processor_func = self.processor_func - - def set_dtypes(self): - self.dtypes = self.convert_dtypes(mdtypes_template) - self._array_reader.dtypes = self.dtypes - - def matrix_getter_factory(self): - return self._array_reader.matrix_getter_factory() - - def format_looks_right(self): - # Mat4 files have a zero somewhere in first 4 bytes - self.mat_stream.seek(0) - mopt_bytes = N.ndarray(shape=(4,), - dtype=N.uint8, - buffer = self.mat_stream.read(4)) - self.mat_stream.seek(0) - return 0 in mopt_bytes - - def guess_byte_order(self): - self.mat_stream.seek(0) - mopt = self.read_dtype(N.dtype('i4')) - self.mat_stream.seek(0) - if mopt < 0 or mopt > 5000: - return ByteOrder.swapped_code - return ByteOrder.native_code - - -class Mat4MatrixWriter(MatStreamWriter): - - def write_header(self, P=0, T=0, imagf=0, dims=None): - ''' Write header for given data options - P - mat4 data type - T - mat4 matrix class - imagf - complex flag - dims - matrix dimensions - ''' - if dims is None: - dims = self.arr.shape - header = N.empty((), mdtypes_template['header']) - M = not ByteOrder.little_endian - O = 0 - header['mopt'] = (M * 1000 + - O * 100 + - P * 10 + - T) - header['mrows'] = dims[0] - header['ncols'] = dims[1] - header['imagf'] = imagf - header['namlen'] = len(self.name) + 1 - self.write_bytes(header) - self.write_string(self.name + '\0') - - def arr_to_2d(self): - self.arr = N.atleast_2d(self.arr) - dims = self.arr.shape - if len(dims) > 2: - self.arr = self.arr.reshape(-1,dims[-1]) - - def write(self): - assert False, 'Not implemented' - - -class Mat4NumericWriter(Mat4MatrixWriter): - - def write(self): - self.arr_to_2d() - imagf = self.arr.dtype.kind == 'c' - try: - P = np_to_mtypes[self.arr.dtype.str[1:]] - except KeyError: - if imagf: - self.arr = self.arr.astype('c128') - else: - self.arr = self.arr.astype('f8') - P = miDOUBLE - self.write_header(P=P, - T=mxFULL_CLASS, - imagf=imagf) - if imagf: - self.write_bytes(self.arr.real) - self.write_bytes(self.arr.imag) - else: - self.write_bytes(self.arr) - - -class Mat4CharWriter(Mat4MatrixWriter): - - def write(self): - self.arr_to_chars() - self.arr_to_2d() - dims = self.arr.shape - self.write_header(P=miUINT8, - T=mxCHAR_CLASS) - if self.arr.dtype.kind == 'U': - # Recode unicode to ascii - n_chars = N.product(dims) - st_arr = N.ndarray(shape=(), - dtype=self.arr_dtype_number(n_chars), - buffer=self.arr) - st = st_arr.item().encode('ascii') - self.arr = N.ndarray(shape=dims, dtype='S1', buffer=st) - self.write_bytes(self.arr) - - -class Mat4SparseWriter(Mat4MatrixWriter): - - def write(self): - ''' Sparse matrices are 2D - See docstring for Mat4SparseGetter - ''' - imagf = self.arr.dtype.kind == 'c' - nnz = self.arr.nnz - ijd = N.zeros((nnz+1, 3+imagf), dtype='f8') - for i in range(nnz): - ijd[i,0], ijd[i,1] = self.arr.rowcol(i) - ijd[:-1,0:2] += 1 # 1 based indexing - if imagf: - ijd[:-1,2] = self.arr.data.real - ijd[:-1,3] = self.arr.data.imag - else: - ijd[:-1,2] = self.arr.data - ijd[-1,0:2] = self.arr.shape - self.write_header(P=miDOUBLE, - T=mxSPARSE_CLASS, - dims=ijd.shape) - self.write_bytes(ijd) - - -def matrix_writer_factory(stream, arr, name): - ''' Factory function to return matrix writer given variable to write - stream - file or file-like stream to write to - arr - array to write - name - name in matlab (TM) workspace - ''' - if have_sparse: - if scipy.sparse.issparse(arr): - return Mat4SparseWriter(stream, arr, name) - arr = N.array(arr) - dtt = arr.dtype.type - if dtt is N.object_: - raise TypeError, 'Cannot save object arrays in Mat4' - elif dtt is N.void: - raise TypeError, 'Cannot save void type arrays' - elif dtt in (N.unicode_, N.string_): - return Mat4CharWriter(stream, arr, name) - else: - return Mat4NumericWriter(stream, arr, name) - - -class MatFile4Writer(MatFileWriter): - - def put_variables(self, mdict): - for name, var in mdict.items(): - matrix_writer_factory(self.file_stream, var, name).write() Deleted: trunk/scipy/io/mio5.py =================================================================== --- trunk/scipy/io/mio5.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/mio5.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,807 +0,0 @@ -''' Classes for read / write of matlab (TM) 5 files -''' - -# Small fragments of current code adapted from matfile.py by Heiko -# Henkelmann - -## Notice in matfile.py file - -# Copyright (c) 2003 Heiko Henkelmann - -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: - -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. - -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -# DEALINGS IN THE SOFTWARE. - -import zlib -from copy import copy as pycopy -from cStringIO import StringIO -import numpy as N - -from scipy.io.miobase import * - -try: # Python 2.3 support - from sets import Set as set -except: - pass - -miINT8 = 1 -miUINT8 = 2 -miINT16 = 3 -miUINT16 = 4 -miINT32 = 5 -miUINT32 = 6 -miSINGLE = 7 -miDOUBLE = 9 -miINT64 = 12 -miUINT64 = 13 -miMATRIX = 14 -miCOMPRESSED = 15 -miUTF8 = 16 -miUTF16 = 17 -miUTF32 = 18 - -mxCELL_CLASS = 1 -mxSTRUCT_CLASS = 2 -mxOBJECT_CLASS = 3 -mxCHAR_CLASS = 4 -mxSPARSE_CLASS = 5 -mxDOUBLE_CLASS = 6 -mxSINGLE_CLASS = 7 -mxINT8_CLASS = 8 -mxUINT8_CLASS = 9 -mxINT16_CLASS = 10 -mxUINT16_CLASS = 11 -mxINT32_CLASS = 12 -mxUINT32_CLASS = 13 - -mdtypes_template = { - miINT8: 'i1', - miUINT8: 'u1', - miINT16: 'i2', - miUINT16: 'u2', - miINT32: 'i4', - miUINT32: 'u4', - miSINGLE: 'f4', - miDOUBLE: 'f8', - miINT64: 'i8', - miUINT64: 'u8', - miUTF8: 'u1', - miUTF16: 'u2', - miUTF32: 'u4', - 'file_header': [('description', 'S116'), - ('subsystem_offset', 'i8'), - ('version', 'u2'), - ('endian_test', 'S2')], - 'tag_full': [('mdtype', 'u4'), ('byte_count', 'u4')], - 'array_flags': [('data_type', 'u4'), - ('byte_count', 'u4'), - ('flags_class','u4'), - ('nzmax', 'u4')], - 'U1': 'U1', - } - -mclass_dtypes_template = { - mxINT8_CLASS: 'i1', - mxUINT8_CLASS: 'u1', - mxINT16_CLASS: 'i2', - mxUINT16_CLASS: 'u2', - mxINT32_CLASS: 'i4', - mxUINT32_CLASS: 'u4', - mxSINGLE_CLASS: 'f4', - mxDOUBLE_CLASS: 'f8', - } - - -np_to_mtypes = { - 'f8': miDOUBLE, - 'c32': miDOUBLE, - 'c24': miDOUBLE, - 'c16': miDOUBLE, - 'f4': miSINGLE, - 'c8': miSINGLE, - 'i1': miINT8, - 'i2': miINT16, - 'i4': miINT32, - 'u1': miUINT8, - 'u4': miUINT32, - 'u2': miUINT16, - 'S1': miUINT8, - 'U1': miUTF16, - } - - -np_to_mxtypes = { - 'f8': mxDOUBLE_CLASS, - 'c32': mxDOUBLE_CLASS, - 'c24': mxDOUBLE_CLASS, - 'c16': mxDOUBLE_CLASS, - 'f4': mxSINGLE_CLASS, - 'c8': mxSINGLE_CLASS, - 'i4': mxINT32_CLASS, - 'i2': mxINT16_CLASS, - 'u2': mxUINT16_CLASS, - 'u1': mxUINT8_CLASS, - 'S1': mxUINT8_CLASS, - } - - - -''' Before release v7.1 (release 14) matlab (TM) used the system -default character encoding scheme padded out to 16-bits. Release 14 -and later use Unicode. When saving character data, R14 checks if it -can be encoded in 7-bit ascii, and saves in that format if so.''' - -codecs_template = { - miUTF8: {'codec': 'utf_8', 'width': 1}, - miUTF16: {'codec': 'utf_16', 'width': 2}, - miUTF32: {'codec': 'utf_32','width': 4}, - } - -miUINT16_codec = sys.getdefaultencoding() - -mx_numbers = ( - mxDOUBLE_CLASS, - mxSINGLE_CLASS, - mxINT8_CLASS, - mxUINT8_CLASS, - mxINT16_CLASS, - mxUINT16_CLASS, - mxINT32_CLASS, - mxUINT32_CLASS, - ) - -class mat_struct(object): - ''' Placeholder for holding read data from structs ''' - pass - -class mat_obj(object): - ''' Placeholder for holding read data from objects ''' - pass - -class Mat5ArrayReader(MatArrayReader): - ''' Class to get Mat5 arrays - - Provides element reader functions, header reader, matrix reader - factory function - ''' - - def __init__(self, mat_stream, dtypes, processor_func, codecs, class_dtypes): - super(Mat5ArrayReader, self).__init__(mat_stream, - dtypes, - processor_func, - ) - self.codecs = codecs - self.class_dtypes = class_dtypes - - def read_element(self, copy=True): - raw_tag = self.mat_stream.read(8) - tag = N.ndarray(shape=(), - dtype=self.dtypes['tag_full'], - buffer = raw_tag) - mdtype = tag['mdtype'].item() - byte_count = mdtype >> 16 - if byte_count: # small data element format - if byte_count > 4: - raise ValueError, 'Too many bytes for sde format' - mdtype = mdtype & 0xFFFF - dt = self.dtypes[mdtype] - el_count = byte_count / dt.itemsize - return N.ndarray(shape=(el_count,), - dtype=dt, - buffer=raw_tag[4:]) - byte_count = tag['byte_count'].item() - if mdtype == miMATRIX: - return self.current_getter(byte_count).get_array() - if mdtype in self.codecs: # encoded char data - raw_str = self.mat_stream.read(byte_count) - codec = self.codecs[mdtype] - if not codec: - raise TypeError, 'Do not support encoding %d' % mdtype - el = raw_str.decode(codec) - else: # numeric data - dt = self.dtypes[mdtype] - el_count = byte_count / dt.itemsize - el = N.ndarray(shape=(el_count,), - dtype=dt, - buffer=self.mat_stream.read(byte_count)) - if copy: - el = el.copy() - mod8 = byte_count % 8 - if mod8: - self.mat_stream.seek(8 - mod8, 1) - return el - - def matrix_getter_factory(self): - ''' Returns reader for next matrix at top level ''' - tag = self.read_dtype(self.dtypes['tag_full']) - mdtype = tag['mdtype'].item() - byte_count = tag['byte_count'].item() - next_pos = self.mat_stream.tell() + byte_count - if mdtype == miCOMPRESSED: - getter = Mat5ZArrayReader(self, byte_count).matrix_getter_factory() - elif not mdtype == miMATRIX: - raise TypeError, \ - 'Expecting miMATRIX type here, got %d' % mdtype - else: - getter = self.current_getter(byte_count) - getter.next_position = next_pos - return getter - - def current_getter(self, byte_count): - ''' Return matrix getter for current stream position - - Returns matrix getters at top level and sub levels - ''' - if not byte_count: # an empty miMATRIX can contain no bytes - return Mat5EmptyMatrixGetter(self) - af = self.read_dtype(self.dtypes['array_flags']) - header = {} - flags_class = af['flags_class'] - mc = flags_class & 0xFF - header['mclass'] = mc - header['is_logical'] = flags_class >> 9 & 1 - header['is_global'] = flags_class >> 10 & 1 - header['is_complex'] = flags_class >> 11 & 1 - header['nzmax'] = af['nzmax'] - header['dims'] = self.read_element() - header['name'] = self.read_element().tostring() - if mc in mx_numbers: - return Mat5NumericMatrixGetter(self, header) - if mc == mxSPARSE_CLASS: - return Mat5SparseMatrixGetter(self, header) - if mc == mxCHAR_CLASS: - return Mat5CharMatrixGetter(self, header) - if mc == mxCELL_CLASS: - return Mat5CellMatrixGetter(self, header) - if mc == mxSTRUCT_CLASS: - return Mat5StructMatrixGetter(self, header) - if mc == mxOBJECT_CLASS: - return Mat5ObjectMatrixGetter(self, header) - raise TypeError, 'No reader for class code %s' % mc - - -class Mat5ZArrayReader(Mat5ArrayReader): - ''' Getter for compressed arrays - - Reads and uncompresses gzipped stream on init, providing wrapper - for this new sub-stream. - ''' - def __init__(self, array_reader, byte_count): - '''Reads and uncompresses gzipped stream''' - data = array_reader.mat_stream.read(byte_count) - super(Mat5ZArrayReader, self).__init__( - StringIO(zlib.decompress(data)), - array_reader.dtypes, - array_reader.processor_func, - array_reader.codecs, - array_reader.class_dtypes) - - -class Mat5MatrixGetter(MatMatrixGetter): - ''' Base class for getting Mat5 matrices - - Gets current read information from passed array_reader - ''' - - def __init__(self, array_reader, header): - super(Mat5MatrixGetter, self).__init__(array_reader, header) - self.class_dtypes = array_reader.class_dtypes - self.codecs = array_reader.codecs - self.is_global = header['is_global'] - self.mat_dtype = None - - def read_element(self, *args, **kwargs): - return self.array_reader.read_element(*args, **kwargs) - - -class Mat5EmptyMatrixGetter(Mat5MatrixGetter): - ''' Dummy class to return empty array for empty matrix - ''' - def __init__(self, array_reader): - self.array_reader = array_reader - self.mat_stream = array_reader.mat_stream - self.data_position = self.mat_stream.tell() - self.header = {} - self.is_global = False - self.mat_dtype = 'f8' - - def get_raw_array(self): - return N.array([[]]) - - -class Mat5NumericMatrixGetter(Mat5MatrixGetter): - - def __init__(self, array_reader, header): - super(Mat5NumericMatrixGetter, self).__init__(array_reader, header) - if header['is_logical']: - self.mat_dtype = N.dtype('bool') - else: - self.mat_dtype = self.class_dtypes[header['mclass']] - - def get_raw_array(self): - if self.header['is_complex']: - # avoid array copy to save memory - res = self.read_element(copy=False) - res_j = self.read_element(copy=False) - res = res + (res_j * 1j) - else: - res = self.read_element() - return N.ndarray(shape=self.header['dims'], - dtype=res.dtype, - buffer=res, - order='F') - - -class Mat5SparseMatrixGetter(Mat5MatrixGetter): - def get_raw_array(self): - rowind = self.read_element() - indptr = self.read_element() - if self.header['is_complex']: - # avoid array copy to save memory - data = self.read_element(copy=False) - data_j = self.read_element(copy=False) - data = data + (data_j * 1j) - else: - data = self.read_element() - ''' From the matlab (TM) API documentation, last found here: - http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/ - rowind are simply the row indices for all the (res) non-zero - entries in the sparse array. rowind has nzmax entries, so - may well have more entries than len(res), the actual number - of non-zero entries, but rowind[len(res):] can be discarded - and should be 0. indptr has length (number of columns + 1), - and is such that, if D = diff(colind), D[j] gives the number - of non-zero entries in column j. Because rowind values are - stored in column order, this gives the column corresponding to - each rowind - ''' - if have_sparse: - dims = self.header['dims'] - return scipy.sparse.csc_matrix((data,rowind,indptr), dims) - else: - return (dims, data, rowind, indptr) - - -class Mat5CharMatrixGetter(Mat5MatrixGetter): - def get_raw_array(self): - res = self.read_element() - # Convert non-string types to unicode - if isinstance(res, N.ndarray): - if res.dtype.type == N.uint16: - codec = miUINT16_codec - if self.codecs['uint16_len'] == 1: - res = res.astype(N.uint8) - elif res.dtype.type in (N.uint8, N.int8): - codec = 'ascii' - else: - raise TypeError, 'Did not expect type %s' % res.dtype - res = res.tostring().decode(codec) - return N.ndarray(shape=self.header['dims'], - dtype=N.dtype('U1'), - buffer=N.array(res), - order='F').copy() - - -class Mat5CellMatrixGetter(Mat5MatrixGetter): - def get_raw_array(self): - # Account for fortran indexing of cells - tupdims = tuple(self.header['dims'][::-1]) - length = N.product(tupdims) - result = N.empty(length, dtype=object) - for i in range(length): - result[i] = self.get_item() - return result.reshape(tupdims).T - - def get_item(self): - return self.read_element() - - -class Mat5StructMatrixGetter(Mat5CellMatrixGetter): - def __init__(self, *args, **kwargs): - super(Mat5StructMatrixGetter, self).__init__(*args, **kwargs) - self.obj_template = mat_struct() - - def get_raw_array(self): - namelength = self.read_element()[0] - # get field names - names = self.read_element() - splitnames = [names[i:i+namelength] for i in \ - xrange(0,len(names),namelength)] - self.obj_template._fieldnames = [x.tostring().strip('\x00') - for x in splitnames] - return super(Mat5StructMatrixGetter, self).get_raw_array() - - def get_item(self): - item = pycopy(self.obj_template) - for element in item._fieldnames: - item.__dict__[element] = self.read_element() - return item - - -class Mat5ObjectMatrixGetter(Mat5StructMatrixGetter): - def __init__(self, *args, **kwargs): - super(Mat5StructMatrixGetter, self).__init__(*args, **kwargs) - self.obj_template = mat_obj() - - def get_raw_array(self): - self.obj_template._classname = self.read_element().tostring() - return super(Mat5ObjectMatrixGetter, self).get_raw_array() - - -class MatFile5Reader(MatFileReader): - ''' Reader for Mat 5 mat files - - Adds the following attribute to base class - - uint16_codec - char codec to use for uint16 char arrays - (defaults to system default codec) - ''' - - def __init__(self, - mat_stream, - byte_order=None, - mat_dtype=False, - squeeze_me=True, - chars_as_strings=True, - matlab_compatible=False, - uint16_codec=None - ): - self.codecs = {} - self._array_reader = Mat5ArrayReader( - mat_stream, - None, - None, - None, - None, - ) - super(MatFile5Reader, self).__init__( - mat_stream, - byte_order, - mat_dtype, - squeeze_me, - chars_as_strings, - matlab_compatible, - ) - self._array_reader.processor_func = self.processor_func - self.uint16_codec = uint16_codec - - def get_uint16_codec(self): - return self._uint16_codec - def set_uint16_codec(self, uint16_codec): - if not uint16_codec: - uint16_codec = sys.getdefaultencoding() - # Set length of miUINT16 char encoding - self.codecs['uint16_len'] = len(" ".encode(uint16_codec)) \ - - len(" ".encode(uint16_codec)) - self.codecs['uint16_codec'] = uint16_codec - self._array_reader.codecs = self.codecs - self._uint16_codec = uint16_codec - uint16_codec = property(get_uint16_codec, - set_uint16_codec, - None, - 'get/set uint16_codec') - - def set_dtypes(self): - ''' Set dtypes and codecs ''' - self.dtypes = self.convert_dtypes(mdtypes_template) - self.class_dtypes = self.convert_dtypes(mclass_dtypes_template) - codecs = {} - postfix = self.order_code == '<' and '_le' or '_be' - for k, v in codecs_template.items(): - codec = v['codec'] - try: - " ".encode(codec) - except LookupError: - codecs[k] = None - continue - if v['width'] > 1: - codec += postfix - codecs[k] = codec - self.codecs.update(codecs) - self.update_array_reader() - - def update_array_reader(self): - self._array_reader.codecs = self.codecs - self._array_reader.dtypes = self.dtypes - self._array_reader.class_dtypes = self.class_dtypes - - def matrix_getter_factory(self): - return self._array_reader.matrix_getter_factory() - - def guess_byte_order(self): - self.mat_stream.seek(126) - mi = self.mat_stream.read(2) - self.mat_stream.seek(0) - return mi == 'IM' and '<' or '>' - - def file_header(self): - ''' Read in mat 5 file header ''' - hdict = {} - hdr = self.read_dtype(self.dtypes['file_header']) - hdict['__header__'] = hdr['description'].item().strip(' \t\n\000') - v_major = hdr['version'] >> 8 - v_minor = hdr['version'] & 0xFF - hdict['__version__'] = '%d.%d' % (v_major, v_minor) - return hdict - - def format_looks_right(self): - # Mat4 files have a zero somewhere in first 4 bytes - self.mat_stream.seek(0) - mopt_bytes = N.ndarray(shape=(4,), - dtype=N.uint8, - buffer = self.mat_stream.read(4)) - self.mat_stream.seek(0) - return 0 not in mopt_bytes - - -class Mat5MatrixWriter(MatStreamWriter): - - mat_tag = N.zeros((), mdtypes_template['tag_full']) - mat_tag['mdtype'] = miMATRIX - - def __init__(self, file_stream, arr, name, is_global=False): - super(Mat5MatrixWriter, self).__init__(file_stream, arr, name) - self.is_global = is_global - - def write_dtype(self, arr): - self.file_stream.write(arr.tostring()) - - def write_element(self, arr, mdtype=None): - # write tag, data - tag = N.zeros((), mdtypes_template['tag_full']) - if mdtype is None: - tag['mdtype'] = np_to_mtypes[arr.dtype.str[1:]] - else: - tag['mdtype'] = mdtype - tag['byte_count'] = arr.size*arr.itemsize - self.write_dtype(tag) - self.write_bytes(arr) - # do 8 byte padding if needed - if tag['byte_count']%8 != 0: - pad = (1+tag['byte_count']//8)*8 - tag['byte_count'] - self.write_bytes(N.zeros((pad,),dtype='u1')) - - def write_header(self, mclass, - is_global=False, - is_complex=False, - is_logical=False, - nzmax=0): - ''' Write header for given data options - mclass - mat5 matrix class - is_global - True if matrix is global - is_complex - True is matrix is complex - is_logical - True if matrix is logical - nzmax - max non zero elements for sparse arrays - ''' - self._mat_tag_pos = self.file_stream.tell() - self.write_dtype(self.mat_tag) - # write array flags (complex, global, logical, class, nzmax) - af = N.zeros((), mdtypes_template['array_flags']) - af['data_type'] = miUINT32 - af['byte_count'] = 8 - flags = is_complex << 3 | is_global << 2 | is_logical << 1 - af['flags_class'] = mclass | flags << 8 - af['nzmax'] = nzmax - self.write_dtype(af) - # write array shape - self.arr=N.atleast_2d(self.arr) - self.write_element(N.array(self.arr.shape, dtype='i4')) - # write name - self.write_element(N.ndarray(shape=len(self.name), dtype='S1', buffer=self.name)) - - def update_matrix_tag(self): - curr_pos = self.file_stream.tell() - self.file_stream.seek(self._mat_tag_pos) - self.mat_tag['byte_count'] = curr_pos - self._mat_tag_pos - 8 - self.write_dtype(self.mat_tag) - self.file_stream.seek(curr_pos) - - def write(self): - assert False, 'Not implemented' - - -class Mat5NumericWriter(Mat5MatrixWriter): - - def write(self): - imagf = self.arr.dtype.kind == 'c' - try: - mclass = np_to_mxtypes[self.arr.dtype.str[1:]] - except KeyError: - if imagf: - self.arr = self.arr.astype('c128') - else: - self.arr = self.arr.astype('f8') - mclass = mxDOUBLE_CLASS - self.write_header(mclass=mclass,is_complex=imagf) - if imagf: - self.write_element(self.arr.real) - self.write_element(self.arr.imag) - else: - self.write_element(self.arr) - self.update_matrix_tag() - -class Mat5CharWriter(Mat5MatrixWriter): - codec='ascii' - def write(self): - self.arr_to_chars() - self.write_header(mclass=mxCHAR_CLASS) - if self.arr.dtype.kind == 'U': - # Recode unicode using self.codec - n_chars = N.product(self.arr.shape) - st_arr = N.ndarray(shape=(), - dtype=self.arr_dtype_number(n_chars), - buffer=self.arr) - st = st_arr.item().encode(self.codec) - self.arr = N.ndarray(shape=(len(st)), dtype='u1', buffer=st) - self.write_element(self.arr,mdtype=miUTF8) - self.update_matrix_tag() - -class Mat5UniCharWriter(Mat5CharWriter): - codec='UTF8' - - -class Mat5SparseWriter(Mat5MatrixWriter): - - def write(self): - ''' Sparse matrices are 2D - See docstring for Mat5SparseGetter - ''' - imagf = self.arr.dtype.kind == 'c' - N = self.arr.nnz - ijd = N.zeros((N+1, 3+imagf), dtype='f8') - for i in range(N): - ijd[i,0], ijd[i,1] = self.arr.rowcol(i) - ijd[:-1,0:2] += 1 # 1 based indexing - if imagf: - ijd[:-1,2] = self.arr.data.real - ijd[:-1,3] = self.arr.data.imag - else: - ijd[:-1,2] = self.arr.data - ijd[-1,0:2] = self.arr.shape - self.write_header(P=miDOUBLE, - T=mxSPARSE_CLASS, - dims=ijd.shape) - self.write_bytes(ijd) - - -class Mat5WriterGetter(object): - ''' Wraps stream and options, provides methods for getting Writer objects ''' - def __init__(self, stream, unicode_strings): - self.stream = stream - self.unicode_strings = unicode_strings - - def rewind(self): - self.stream.seek(0) - - def matrix_writer_factory(self, arr, name, is_global=False): - ''' Factory function to return matrix writer given variable to write - stream - file or file-like stream to write to - arr - array to write - name - name in matlab (TM) workspace - ''' - if have_sparse: - if scipy.sparse.issparse(arr): - return Mat5SparseWriter(self.stream, arr, name, is_global) - arr = N.array(arr) - if arr.dtype.hasobject: - types, arr_type = self.classify_mobjects(arr) - if arr_type == 'c': - return Mat5CellWriter(self.stream, arr, name, is_global, types) - elif arr_type == 's': - return Mat5StructWriter(self.stream, arr, name, is_global) - elif arr_type == 'o': - return Mat5ObjectWriter(self.stream, arr, name, is_global) - if arr.dtype.kind in ('U', 'S'): - if self.unicode_strings: - return Mat5UniCharWriter(self.stream, arr, name, is_global) - else: - return Mat5CharWriter(self.stream, arr, name, is_global) - else: - return Mat5NumericWriter(self.stream, arr, name, is_global) - - def classify_mobjects(self, objarr): - ''' Function to classify objects passed for writing - returns - types - S1 array of same shape as objarr with codes for each object - i - invalid object - a - ndarray - s - matlab struct - o - matlab object - arr_type - one of - c - cell array - s - struct array - o - object array - ''' - n = objarr.size - types = N.empty((n,), dtype='S1') - types[:] = 'i' - type_set = set() - flato = objarr.flat - for i in range(n): - obj = flato[i] - if isinstance(obj, N.ndarray): - types[i] = 'a' - continue - try: - fns = tuple(obj._fieldnames) - except AttributeError: - continue - try: - cn = obj._classname - except AttributeError: - types[i] = 's' - type_set.add(fns) - continue - types[i] = 'o' - type_set.add((cn, fns)) - arr_type = 'c' - if len(set(types))==1 and len(type_set) == 1: - arr_type = types[0] - return types.reshape(objarr.shape), arr_type - - -class MatFile5Writer(MatFileWriter): - ''' Class for writing mat5 files ''' - def __init__(self, file_stream, - do_compression=False, - unicode_strings=False, - global_vars=None): - super(MatFile5Writer, self).__init__(file_stream) - self.do_compression = do_compression - if global_vars: - self.global_vars = global_vars - else: - self.global_vars = [] - self.writer_getter = Mat5WriterGetter( - StringIO(), - unicode_strings) - # write header - import os, time - hdr = N.zeros((), mdtypes_template['file_header']) - hdr['description']='MATLAB 5.0 MAT-file Platform: %s, Created on: %s' % ( - os.name,time.asctime()) - hdr['version']= 0x0100 - hdr['endian_test']=N.ndarray(shape=(),dtype='S2',buffer=N.uint16(0x4d49)) - file_stream.write(hdr.tostring()) - - def get_unicode_strings(self): - return self.write_getter.unicode_strings - def set_unicode_strings(self, unicode_strings): - self.writer_getter.unicode_strings = unicode_strings - unicode_strings = property(get_unicode_strings, - set_unicode_strings, - None, - 'get/set unicode strings property') - - def put_variables(self, mdict): - for name, var in mdict.items(): - is_global = name in self.global_vars - self.writer_getter.rewind() - self.writer_getter.matrix_writer_factory( - var, - name, - is_global, - ).write() - stream = self.writer_getter.stream - if self.do_compression: - str = zlib.compress(stream.getvalue(stream.tell())) - tag = N.empty((), mdtypes_template['tag_full']) - tag['mdtype'] = miCOMPRESSED - tag['byte_count'] = len(str) - self.file_stream.write(tag.tostring() + str) - else: - self.file_stream.write(stream.getvalue(stream.tell())) Deleted: trunk/scipy/io/miobase.py =================================================================== --- trunk/scipy/io/miobase.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/miobase.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,379 +0,0 @@ -# Authors: Travis Oliphant, Matthew Brett - -""" -Base classes for matlab (TM) file stream reading -""" - -import sys - -import numpy as N - -try: - import scipy.sparse - have_sparse = 1 -except ImportError: - have_sparse = 0 - - -def small_product(arr): - ''' Faster than product for small arrays ''' - res = 1 - for e in arr: - res *= e - return res - -class ByteOrder(object): - ''' Namespace for byte ordering ''' - little_endian = sys.byteorder == 'little' - native_code = little_endian and '<' or '>' - swapped_code = little_endian and '>' or '<' - - def to_numpy_code(code): - if code is None: - return ByteOrder.native_code - if code in ('little', '<', 'l', 'L'): - return '<' - elif code in ('BIG', '>', 'B', 'b'): - return '>' - elif code in ('native', '='): - return ByteOrder.native_code - elif code in ('swapped'): - return ByteOrder.swapped_code - else: - raise ValueError, 'We cannot handle byte order %s' % byte_order - to_numpy_code = staticmethod(to_numpy_code) - - -class MatStreamAgent(object): - ''' Base object for readers / getters from mat file streams - - Attaches to initialized stream - - Base class for "getters" - which do store state of what they are - reading on itialization, and therefore need to be initialized - before each read, and "readers" which do not store state, and only - need to be initialized once on object creation - - Implements common array reading functions - - Inputs mat_steam - MatFileReader object - ''' - - def __init__(self, mat_stream): - self.mat_stream = mat_stream - - def read_dtype(self, a_dtype): - ''' Generic get of byte stream data of known type - - Inputs - a_dtype - dtype of array - - a_dtype is assumed to be correct endianness - ''' - num_bytes = a_dtype.itemsize - arr = N.ndarray(shape=(), - dtype=a_dtype, - buffer=self.mat_stream.read(num_bytes), - order='F') - return arr - - def read_ztstring(self, num_bytes): - return self.mat_stream.read(num_bytes).strip('\x00') - - -class MatFileReader(MatStreamAgent): - """ Base object for reading mat files - - mat_stream - initialized byte stream object - file io interface object - byte_order - byte order ('native', 'little', 'BIG') - in ('native', '=') - or in ('little', '<') - or in ('BIG', '>') - mat_dtype - return arrays in same dtype as loaded into matlab - (instead of the dtype with which they are saved) - squeeze_me - whether to squeeze unit dimensions or not - chars_as_strings - whether to convert char arrays to string arrays - mat_dtype - return matrices with datatype that matlab would load as - (rather than in the datatype matlab saves as) - matlab_compatible - returns matrices as would be loaded by matlab - (implies squeeze_me=False, chars_as_strings=False - mat_dtype=True) - - To make this class functional, you will need to override the - following methods: - - set_dtypes - sets data types defs from byte order - matrix_getter_factory - gives object to fetch next matrix from stream - format_looks_right - returns True if format looks correct for - this file type (Mat4, Mat5) - guess_byte_order - guesses file byte order from file - """ - - def __init__(self, mat_stream, - byte_order=None, - mat_dtype=False, - squeeze_me=True, - chars_as_strings=True, - matlab_compatible=False, - ): - # Initialize stream - self.mat_stream = mat_stream - self.dtypes = {} - if not byte_order: - byte_order = self.guess_byte_order() - self.order_code = byte_order # sets dtypes and other things too - if matlab_compatible: - self.set_matlab_compatible() - else: - self._squeeze_me = squeeze_me - self._chars_as_strings = chars_as_strings - self._mat_dtype = mat_dtype - self.processor_func = self.get_processor_func() - - def set_matlab_compatible(self): - ''' Sets options to return arrays as matlab (tm) loads them ''' - self._mat_dtype = True - self._squeeze_me = False - self._chars_as_strings = False - self.processor_func = self.get_processor_func() - - def get_mat_dtype(self): - return self._mat_dtype - def set_mat_dtype(self, mat_dtype): - self._mat_dtype = mat_dtype - self.processor_func = self.get_processor_func() - mat_dtype = property(get_mat_dtype, - set_mat_dtype, - None, - 'get/set mat_dtype property') - - def get_squeeze_me(self): - return self._squeeze_me - def set_squeeze_me(self, squeeze_me): - self._squeeze_me = squeeze_me - self.processor_func = self.get_processor_func() - squeeze_me = property(get_squeeze_me, - set_squeeze_me, - None, - 'get/set squeeze me property') - - def get_chars_as_strings(self): - return self._chars_as_strings - def set_chars_as_strings(self, chars_as_strings): - self._chars_as_strings = chars_as_strings - self.processor_func = self.get_processor_func() - chars_as_strings = property(get_chars_as_strings, - set_chars_as_strings, - None, - 'get/set squeeze me property') - - def get_order_code(self): - return self._order_code - def set_order_code(self, order_code): - order_code = ByteOrder.to_numpy_code(order_code) - self._order_code = order_code - self.set_dtypes() - order_code = property(get_order_code, - set_order_code, - None, - 'get/set order code') - - def set_dtypes(self): - assert False, 'Not implemented' - - def convert_dtypes(self, dtype_template): - dtypes = dtype_template.copy() - for k in dtypes: - dtypes[k] = N.dtype(dtypes[k]).newbyteorder( - self.order_code) - return dtypes - - def matrix_getter_factory(self): - assert False, 'Not implemented' - - def format_looks_right(self): - "Return True if the format looks right for this object" - assert False, 'Not implemented' - - def file_header(self): - return {} - - def guess_byte_order(self): - assert 0, 'Not implemented' - - def get_processor_func(self): - ''' Processing to apply to read matrices - - Function applies options to matrices. We have to pass this - function into the reader routines because Mat5 matrices - occur as submatrices - in cell arrays, structs and objects - - so we will not see these in the main variable getting routine - here. - - The read array is the first argument. - The getter, passed as second argument to the function, must - define properties, iff mat_dtype option is True: - - mat_dtype - data type when loaded into matlab (tm) - (None for no conversion) - - func returns the processed array - ''' - - def func(arr, getter): - if arr.dtype.kind == 'U' and self.chars_as_strings: - # Convert char array to string or array of strings - dims = arr.shape - if len(dims) >= 2: # return array of strings - dtt = self.order_code + 'U' - n_dims = dims[:-1] - str_arr = arr.reshape( - (small_product(n_dims), - dims[-1])) - arr = N.empty(n_dims, dtype=object) - for i in range(0, n_dims[-1]): - arr[...,i] = self.chars_to_str(str_arr[i]) - else: # return string - arr = self.chars_to_str(arr) - if self.mat_dtype: - # Apply options to replicate matlab's (TM) - # load into workspace - if getter.mat_dtype is not None: - arr = arr.astype(getter.mat_dtype) - if self.squeeze_me: - arr = N.squeeze(arr) - if not arr.size: - arr = N.array([]) - elif not arr.shape: # 0d coverted to scalar - arr = arr.item() - return arr - return func - - def chars_to_str(self, str_arr): - ''' Convert string array to string ''' - dt = N.dtype('U' + str(small_product(str_arr.shape))) - return N.ndarray(shape=(), - dtype = dt, - buffer = str_arr.copy()).item() - - def get_variables(self, variable_names=None): - ''' get variables from stream as dictionary - - variable_names - optional list of variable names to get - - If variable_names is None, then get all variables in file - ''' - if isinstance(variable_names, basestring): - variable_names = [variable_names] - self.mat_stream.seek(0) - mdict = self.file_header() - mdict['__globals__'] = [] - while not self.end_of_stream(): - getter = self.matrix_getter_factory() - name = getter.name - if variable_names and name not in variable_names: - getter.to_next() - continue - res = getter.get_array() - mdict[name] = res - if getter.is_global: - mdict['__globals__'].append(name) - if variable_names: - variable_names.remove(name) - if not variable_names: - break - return mdict - - def end_of_stream(self): - b = self.mat_stream.read(1) - self.mat_stream.seek(-1,1) - return len(b) == 0 - - -class MatMatrixGetter(MatStreamAgent): - """ Base class for matrix getters - - Getters are stateful versions of agents, and record state of - current read on initialization, so need to be created for each - read - one-shot objects. - - MatrixGetters are initialized with the content of the matrix - header - - Accepts - array_reader - array reading object (see below) - header - header dictionary for matrix being read - """ - - def __init__(self, array_reader, header): - super(MatMatrixGetter, self).__init__(array_reader.mat_stream) - self.array_reader = array_reader - self.dtypes = array_reader.dtypes - self.header = header - self.name = header['name'] - - def get_array(self): - ''' Gets an array from matrix, and applies any necessary processing ''' - arr = self.get_raw_array() - return self.array_reader.processor_func(arr, self) - - def get_raw_array(self): - assert False, 'Not implemented' - - def to_next(self): - self.mat_stream.seek(self.next_position) - - -class MatArrayReader(MatStreamAgent): - ''' Base class for array readers - - The array_reader contains information about the current reading - process, such as byte ordered dtypes and the processing function - to apply to matrices as they are read, as well as routines for - reading matrix compenents. - ''' - - def __init__(self, mat_stream, dtypes, processor_func): - self.mat_stream = mat_stream - self.dtypes = dtypes - self.processor_func = processor_func - - def matrix_getter_factory(self): - assert False, 'Not implemented' - - -class MatStreamWriter(object): - ''' Base object for writing to mat files ''' - def __init__(self, file_stream, arr, name): - self.file_stream = file_stream - self.arr = arr - dt = self.arr.dtype - if not dt.isnative: - self.arr = self.arr.astype(dt.newbyteorder('=')) - self.name = name - - def arr_dtype_number(self, num): - ''' Return dtype for given number of items per element''' - return N.dtype(self.arr.dtype.str[:2] + str(num)) - - def arr_to_chars(self): - ''' Convert string array to char array ''' - dims = list(self.arr.shape) - if not dims: - dims = [1] - dims.append(int(self.arr.dtype.str[2:])) - self.arr = N.ndarray(shape=dims, - dtype=self.arr_dtype_number(1), - buffer=self.arr) - - def write_bytes(self, arr): - self.file_stream.write(arr.tostring(order='F')) - - def write_string(self, s): - self.file_stream.write(s) - - -class MatFileWriter(object): - ''' Base class for Mat file writers ''' - def __init__(self, file_stream): - self.file_stream = file_stream Modified: trunk/scipy/io/mmio.py =================================================================== --- trunk/scipy/io/mmio.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/mmio.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -14,8 +14,10 @@ empty, concatenate, ones, ascontiguousarray from itertools import izip -__all__ = ['mminfo','mmread','mmwrite'] +__all__ = ['mminfo','mmread','mmwrite', 'MMFile'] + +#------------------------------------------------------------------------------- def mminfo(source): """ Queries the contents of the Matrix Market file 'filename' to extract size and storage information. @@ -29,51 +31,13 @@ rows,cols - number of matrix rows and columns entries - number of non-zero entries of a sparse matrix or rows*cols for a dense matrix - rep - 'coordinate' | 'array' + format - 'coordinate' | 'array' field - 'real' | 'complex' | 'pattern' | 'integer' symm - 'general' | 'symmetric' | 'skew-symmetric' | 'hermitian' """ - close_it = 0 - if type(source) is type(''): - if not os.path.isfile(source): - if source[-4:] != '.mtx': - source = source + '.mtx' - source = open(source,'r') - close_it = 1 - line = source.readline().split() - if not line[0].startswith('%%MatrixMarket'): - raise ValueError,'source is not in Matrix Market format' + return MMFile.info(source) - assert len(line)==5,`line` - - assert line[1].strip().lower()=='matrix',`line` - - rep = line[2].strip().lower() - if rep=='dense': rep='array' - elif rep=='sparse': rep='coordinate' - - field = line[3].strip().lower() - - symm = line[4].strip().lower() - - while line: - line = source.readline() - if line.startswith('%'): - continue - line = line.split() - if rep=='array': - assert len(line)==2,`line` - rows,cols = map(eval,line) - entries = rows*cols - else: - assert len(line)==3,`line` - rows,cols,entries = map(eval,line) - break - - if close_it: - source.close() - return (rows,cols,entries,rep,field,symm) - +#------------------------------------------------------------------------------- def mmread(source): """ Reads the contents of a Matrix Market file 'filename' into a matrix. @@ -86,313 +50,528 @@ a - sparse or full matrix """ - close_it = 0 - if type(source) is type(''): - if not os.path.isfile(source): - if os.path.isfile(source+'.mtx'): - source = source + '.mtx' - elif os.path.isfile(source+'.mtx.gz'): - source = source + '.mtx.gz' - if source[-3:] == '.gz': - import gzip - source = gzip.open(source) - else: - source = open(source,'r') - close_it = 1 + return MMFile().read(source) - rows,cols,entries,rep,field,symm = mminfo(source) +#------------------------------------------------------------------------------- +def mmwrite(target, a, comment='', field=None, precision=None): + """ Writes the sparse or dense matrix A to a Matrix Market formatted file. - try: - from scipy.sparse import coo_matrix - except ImportError: - coo_matrix = None + Inputs: - if field=='integer': - dtype='i' - elif field=='real': - dtype='d' - elif field=='complex': - dtype='D' - elif field=='pattern': - dtype='d' - else: - raise ValueError,`field` + target - Matrix Market filename (extension .mtx) or open file object + a - sparse or full matrix + comment - comments to be prepended to the Matrix Market file + field - 'real' | 'complex' | 'pattern' | 'integer' + precision - Number of digits to display for real or complex values. + """ + MMFile().write(target, a, comment, field, precision) - has_symmetry = symm in ['symmetric','skew-symmetric','hermitian'] - is_complex = field=='complex' - is_skew = symm=='skew-symmetric' - is_herm = symm=='hermitian' - is_pattern = field=='pattern' - if rep == 'array': - a = zeros((rows,cols),dtype=dtype) - line = 1 - i,j = 0,0 - while line: +################################################################################ +class MMFile (object): + __slots__ = ( + '_rows', + '_cols', + '_entries', + '_format', + '_field', + '_symmetry') + + @property + def rows(self): return self._rows + @property + def cols(self): return self._cols + @property + def entries(self): return self._entries + @property + def format(self): return self._format + @property + def field(self): return self._field + @property + def symmetry(self): return self._symmetry + + @property + def has_symmetry(self): + return self._symmetry in (self.SYMMETRY_SYMMETRIC, + self.SYMMETRY_SKEW_SYMMETRIC, self.SYMMETRY_HERMITIAN) + + # format values + FORMAT_COORDINATE = 'coordinate' + FORMAT_ARRAY = 'array' + FORMAT_VALUES = (FORMAT_COORDINATE, FORMAT_ARRAY) + + @classmethod + def _validate_format(self, format): + if format not in self.FORMAT_VALUES: + raise ValueError,'unknown format type %s, must be one of %s'% \ + (`format`, `self.FORMAT_VALUES`) + + # field values + FIELD_INTEGER = 'integer' + FIELD_REAL = 'real' + FIELD_COMPLEX = 'complex' + FIELD_PATTERN = 'pattern' + FIELD_VALUES = (FIELD_INTEGER, FIELD_REAL, FIELD_COMPLEX, FIELD_PATTERN) + + @classmethod + def _validate_field(self, field): + if field not in self.FIELD_VALUES: + raise ValueError,'unknown field type %s, must be one of %s'% \ + (`field`, `self.FIELD_VALUES`) + + # symmetry values + SYMMETRY_GENERAL = 'general' + SYMMETRY_SYMMETRIC = 'symmetric' + SYMMETRY_SKEW_SYMMETRIC = 'skew-symmetric' + SYMMETRY_HERMITIAN = 'hermitian' + SYMMETRY_VALUES = ( + SYMMETRY_GENERAL, SYMMETRY_SYMMETRIC, SYMMETRY_SKEW_SYMMETRIC, + SYMMETRY_HERMITIAN) + + @classmethod + def _validate_symmetry(self, symmetry): + if symmetry not in self.SYMMETRY_VALUES: + raise ValueError,'unknown symmetry type %s, must be one of %s'% \ + (`symmetry`, `self.SYMMETRY_VALUES`) + + DTYPES_BY_FIELD = { + FIELD_INTEGER: 'i', + FIELD_REAL: 'd', + FIELD_COMPLEX:'D', + FIELD_PATTERN:'d'} + + #--------------------------------------------------------------------------- + @staticmethod + def reader(): pass + + #--------------------------------------------------------------------------- + @staticmethod + def writer(): pass + + #--------------------------------------------------------------------------- + @classmethod + def info(self, source): + source, close_it = self._open(source) + + try: + + # read and validate header line line = source.readline() - if not line or line.startswith('%'): - continue - if is_complex: - aij = complex(*map(float,line.split())) + mmid, matrix, format, field, symmetry = \ + [part.strip().lower() for part in line.split()] + if not mmid.startswith('%%matrixmarket'): + raise ValueError,'source is not in Matrix Market format' + + assert matrix == 'matrix',`line` + + # ??? Is this necessary? I don't see 'dense' or 'sparse' in the spec + # http://math.nist.gov/MatrixMarket/formats.html + if format == 'dense': format = self.FORMAT_ARRAY + elif format == 'sparse': format = self.FORMAT_COORDINATE + + # skip comments + while line.startswith('%'): line = source.readline() + + line = line.split() + if format == self.FORMAT_ARRAY: + assert len(line)==2,`line` + rows,cols = map(float, line) + entries = rows*cols else: - aij = float(line) - a[i,j] = aij - if has_symmetry and i!=j: - if is_skew: - a[j,i] = -aij - elif is_herm: - a[j,i] = conj(aij) + assert len(line)==3,`line` + rows, cols, entries = map(float, line) + + return (rows, cols, entries, format, field, symmetry) + + finally: + if close_it: source.close() + + #--------------------------------------------------------------------------- + @staticmethod + def _open(filespec, mode='r'): + """ + Return an open file stream for reading based on source. If source is + a file name, open it (after trying to find it with mtx and gzipped mtx + extensions). Otherwise, just return source. + """ + close_it = False + if type(filespec) is type(''): + close_it = True + + # open for reading + if mode[0] == 'r': + + # determine filename plus extension + if not os.path.isfile(filespec): + if os.path.isfile(filespec+'.mtx'): + filespec = filespec + '.mtx' + elif os.path.isfile(filespec+'.mtx.gz'): + filespec = filespec + '.mtx.gz' + # open filename + if filespec[-3:] == '.gz': + import gzip + stream = gzip.open(filespec, mode) else: - a[j,i] = aij - if i base 0) - J -= 1 + finally: + if close_it: stream.close() - if has_symmetry: - mask = (I != J) #off diagonal mask - od_I = I[mask] - od_J = J[mask] - od_V = V[mask] + #--------------------------------------------------------------------------- + def write(self, target, a, comment='', field=None, precision=None): + stream, close_it = self._open(target, 'w') - I = concatenate((I,od_J)) - J = concatenate((J,od_I)) + try: + self._write(stream, a, comment, field, precision) - if is_skew: - od_V *= -1 - elif is_herm: - od_V = od_V.conjugate() + finally: + if close_it: stream.close() + else: stream.flush() - V = concatenate((V,od_V)) - a = coo_matrix((V, (I, J)), shape=(rows, cols), dtype=dtype) else: raise NotImplementedError,`rep` - if close_it: - source.close() - return a + #--------------------------------------------------------------------------- + def _init_attrs(self, **kwargs): + """ + Initialize each attributes with the corresponding keyword arg value + or a default of None + """ + attrs = self.__class__.__slots__ + public_attrs = [attr[1:] for attr in attrs] + invalid_keys = set(kwargs.keys()) - set(public_attrs) + + if invalid_keys: + raise ValueError, \ + 'found %s invalid keyword arguments, please only use %s' % \ + (`tuple(invalid_keys)`, `public_attrs`) -def mmwrite(target,a,comment='',field=None,precision=None): - """ Writes the sparse or dense matrix A to a Matrix Market formatted file. + for attr in attrs: setattr(self, attr, kwargs.get(attr[1:], None)) - Inputs: + #--------------------------------------------------------------------------- + def _parse_header(self, stream): + rows, cols, entries, format, field, symmetry = \ + self.__class__.info(stream) + self._init_attrs(rows=rows, cols=cols, entries=entries, format=format, + field=field, symmetry=symmetry) - target - Matrix Market filename (extension .mtx) or open file object - a - sparse or full matrix - comment - comments to be prepended to the Matrix Market file - field - 'real' | 'complex' | 'pattern' | 'integer' - precision - Number of digits to display for real or complex values. - """ - close_it = 0 - if type(target) is type(''): - if target[-4:] != '.mtx': - target = target + '.mtx' - target = open(target,'w') - close_it = 1 + #--------------------------------------------------------------------------- + def _parse_body(self, stream): + rows, cols, entries, format, field, symm = \ + (self.rows, self.cols, self.entries, self.format, self.field, self.symmetry) - if isinstance(a, list) or isinstance(a, ndarray) or isinstance(a, tuple) or hasattr(a,'__array__'): - rep = 'array' - a = asarray(a) - if len(a.shape) != 2: - raise ValueError, 'expected matrix' - rows,cols = a.shape - entries = rows*cols - typecode = a.dtype.char - if field is not None: - if field=='integer': - a = a.astype('i') - elif field=='real': - if typecode not in 'fd': - a = a.astype('d') - elif field=='complex': - if typecode not in 'FD': - a = a.astype('D') - elif field=='pattern': - pass + try: + from scipy.sparse import coo_matrix + except ImportError: + coo_matrix = None + + dtype = self.DTYPES_BY_FIELD.get(field, None) + + has_symmetry = self.has_symmetry + is_complex = field == self.FIELD_COMPLEX + is_skew = symm == self.SYMMETRY_SKEW_SYMMETRIC + is_herm = symm == self.SYMMETRY_HERMITIAN + is_pattern = field == self.FIELD_PATTERN + + if format == self.FORMAT_ARRAY: + a = zeros((rows,cols),dtype=dtype) + line = 1 + i,j = 0,0 + while line: + line = stream.readline() + if not line or line.startswith('%'): + continue + if is_complex: + aij = complex(*map(float,line.split())) + else: + aij = float(line) + a[i,j] = aij + if has_symmetry and i!=j: + if is_skew: + a[j,i] = -aij + elif is_herm: + a[j,i] = conj(aij) + else: + a[j,i] = aij + if i base 0) + J -= 1 + + if has_symmetry: + mask = (I != J) #off diagonal mask + od_I = I[mask] + od_J = J[mask] + od_V = V[mask] + + I = concatenate((I,od_J)) + J = concatenate((J,od_I)) + + if is_skew: + od_V *= -1 + elif is_herm: + od_V = od_V.conjugate() + + V = concatenate((V,od_V)) + + a = coo_matrix((V, (I, J)), dims=(rows, cols), dtype=dtype) else: - precision = 16 - if field is None: - if typecode in 'li': - field = 'integer' - elif typecode in 'df': - field = 'real' - elif typecode in 'DF': - field = 'complex' - else: - raise TypeError,'unexpected typecode '+typecode + raise NotImplementedError,`format` - if rep == 'array': - symm = _get_symmetry(a) - else: - symm = 'general' + return a - target.write('%%%%MatrixMarket matrix %s %s %s\n' % (rep,field,symm)) + #--------------------------------------------------------------------------- + def _write(self, stream, a, comment='', field=None, precision=None): - for line in comment.split('\n'): - target.write('%%%s\n' % (line)) + if isinstance(a, list) or isinstance(a, ndarray) or isinstance(a, tuple) or hasattr(a,'__array__'): + rep = self.FORMAT_ARRAY + a = asarray(a) + if len(a.shape) != 2: + raise ValueError, 'expected matrix' + rows,cols = a.shape + entries = rows*cols - if field in ['real','integer']: - if field=='real': - format = '%%.%ie\n' % precision + if field is not None: + + if field == self.FIELD_INTEGER: + a = a.astype('i') + elif field == self.FIELD_REAL: + if a.dtype.char not in 'fd': + a = a.astype('d') + elif field == self.FIELD_COMPLEX: + if a.dtype.char not in 'FD': + a = a.astype('D') + else: - format = '%i\n' - elif field=='complex': - format = '%%.%ie %%.%ie\n' % (precision,precision) + from scipy.sparse import spmatrix + if not isinstance(a,spmatrix): + raise ValueError,'unknown matrix type ' + `type(a)` + rep = 'coordinate' + rows, cols = a.shape + entries = a.getnnz() - if rep == 'array': - target.write('%i %i\n' % (rows,cols)) - if field in ['real','integer']: - if symm=='general': - for j in range(cols): - for i in range(rows): - target.write(format % a[i,j]) + typecode = a.dtype.char + + if precision is None: + if typecode in 'fF': + precision = 8 else: - for j in range(cols): - for i in range(j,rows): - target.write(format % a[i,j]) - elif field=='complex': - if symm=='general': - for j in range(cols): - for i in range(rows): - aij = a[i,j] - target.write(format % (real(aij),imag(aij))) + precision = 16 + + if field is None: + if typecode in 'li': + field = 'integer' + elif typecode in 'df': + field = 'real' + elif typecode in 'DF': + field = 'complex' else: - for j in range(cols): - for i in range(j,rows): - aij = a[i,j] - target.write(format % (real(aij),imag(aij))) - elif field=='pattern': - raise ValueError,'Pattern type inconsisted with dense matrix' + raise TypeError,'unexpected typecode '+typecode + + if rep == self.FORMAT_ARRAY: + symm = self._get_symmetry(a) else: - raise TypeError,'Unknown matrix type '+`field` - else: - format = '%i %i ' + format - target.write('%i %i %i\n' % (rows,cols,entries)) - assert symm=='general',`symm` + symm = self.SYMMETRY_GENERAL - coo = a.tocoo() # convert to COOrdinate format - I,J,V = coo.row + 1, coo.col + 1, coo.data # change base 0 -> base 1 + # validate rep, field, and symmetry + self.__class__._validate_format(rep) + self.__class__._validate_field(field) + self.__class__._validate_symmetry(symm) - if field in ['real','integer']: - for ijv_tuple in izip(I,J,V): - target.writelines(format % ijv_tuple) - elif field=='complex': - for ijv_tuple in izip(I,J,V.real,V.imag): - target.writelines(format % ijv_tuple) - elif field=='pattern': - raise NotImplementedError,`field` + # write initial header line + stream.write('%%%%MatrixMarket matrix %s %s %s\n' % (rep,field,symm)) + + # write comments + for line in comment.split('\n'): + stream.write('%%%s\n' % (line)) + + + template = self._field_template(field, precision) + + # write dense format + if rep == self.FORMAT_ARRAY: + + # write shape spec + stream.write('%i %i\n' % (rows,cols)) + + if field in (self.FIELD_INTEGER, self.FIELD_REAL): + + if symm == self.SYMMETRY_GENERAL: + for j in range(cols): + for i in range(rows): + stream.write(template % a[i,j]) + else: + for j in range(cols): + for i in range(j,rows): + stream.write(template % a[i,j]) + + elif field == self.FIELD_COMPLEX: + + if symm == self.SYMMETRY_GENERAL: + for j in range(cols): + for i in range(rows): + aij = a[i,j] + stream.write(template % (real(aij),imag(aij))) + else: + for j in range(cols): + for i in range(j,rows): + aij = a[i,j] + stream.write(template % (real(aij),imag(aij))) + + elif field == self.FIELD_PATTERN: + raise ValueError,'pattern type inconsisted with dense format' + + else: + raise TypeError,'Unknown field type %s'% `field` + + # write sparse format else: - raise TypeError,'Unknown matrix type '+`field` - if close_it: - target.close() - else: - target.flush() - return + if symm != self.SYMMETRY_GENERAL: + raise ValueError, 'symmetric matrices incompatible with sparse format' -def _get_symmetry(a): - m,n = a.shape - if m!=n: - return 'general' - issymm = 1 - isskew = 1 - isherm = a.dtype.char in 'FD' - for j in range(n): - for i in range(j+1,n): - aij,aji = a[i][j],a[j][i] - if issymm and aij != aji: - issymm = 0 - if isskew and aij != -aji: - isskew = 0 - if isherm and aij != conj(aji): - isherm = 0 - if not (issymm or isskew or isherm): - break - if issymm: return 'symmetric' - if isskew: return 'skew-symmetric' - if isherm: return 'hermitian' - return 'general' + # write shape spec + stream.write('%i %i %i\n' % (rows,cols,entries)) + # line template + template = '%i %i ' + template + + coo = a.tocoo() # convert to COOrdinate format + I,J,V = coo.row + 1, coo.col + 1, coo.data # change base 0 -> base 1 + + if field in (self.FIELD_REAL, self.FIELD_INTEGER): + for ijv_tuple in izip(I,J,V): + stream.writelines(template % ijv_tuple) + elif field == self.FIELD_COMPLEX: + for ijv_tuple in izip(I,J,V.real,V.imag): + stream.writelines(template % ijv_tuple) + elif field == self.FIELD_PATTERN: + raise NotImplementedError,`field` + else: + raise TypeError,'Unknown field type %s'% `field` + + +#------------------------------------------------------------------------------- if __name__ == '__main__': import sys import time Modified: trunk/scipy/io/npfile.py =================================================================== --- trunk/scipy/io/npfile.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/npfile.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -222,3 +222,11 @@ if (not endian == 'dtype') and (dt_endian != endian): return arr.byteswap() return arr.copy() + +npfile = N.deprecate_with_doc(""" +You can achieve the same effect as using npfile, using ndarray.tofile +and numpy.fromfile. + +Even better you can use memory-mapped arrays and data-types to map out a +file format for direct manipulation in NumPy. +""")(npfile) Modified: trunk/scipy/io/pickler.py =================================================================== --- trunk/scipy/io/pickler.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/pickler.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -1,5 +1,10 @@ import cPickle +from numpy import deprecate_with_doc + + at deprecate_with_doc(""" +Just use cPickle.dump directly or numpy.savez +""") def objsave(file, allglobals, *args): """Pickle the part of a dictionary containing the argument list into file string. @@ -19,6 +24,9 @@ cPickle.dump(savedict,fid,1) fid.close() + at deprecate_with_doc(""" +Just use cPickle.load or numpy.load. +""") def objload(file, allglobals): """Load a previously pickled dictionary and insert into given dictionary. Modified: trunk/scipy/io/setup.py =================================================================== --- trunk/scipy/io/setup.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/setup.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -10,6 +10,7 @@ config.add_data_dir('tests') config.add_data_dir('examples') config.add_data_dir('docs') + config.add_subpackage('matlab') return config if __name__ == '__main__': Modified: trunk/scipy/io/tests/test_mio.py =================================================================== --- trunk/scipy/io/tests/test_mio.py 2008-01-01 02:55:20 UTC (rev 3757) +++ trunk/scipy/io/tests/test_mio.py 2008-01-01 09:33:02 UTC (rev 3758) @@ -11,8 +11,8 @@ import scipy.sparse as SP set_package_path() -from scipy.io.mio import loadmat, savemat -from scipy.io.mio5 import mat_obj, mat_struct +from matlab.mio import loadmat, savemat +from matlab.mio5 import mat_obj, mat_struct restore_path() try: # Python 2.3 support From scipy-svn at scipy.org Tue Jan 1 04:35:58 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 1 Jan 2008 03:35:58 -0600 (CST) Subject: [Scipy-svn] r3759 - branches Message-ID: <20080101093558.755F039C048@new.scipy.org> Author: oliphant Date: 2008-01-01 03:35:56 -0600 (Tue, 01 Jan 2008) New Revision: 3759 Removed: branches/io_new/ Log: Merged changes in io_new branch to trunk. Can now delete the branch. From scipy-svn at scipy.org Tue Jan 1 17:00:08 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 1 Jan 2008 16:00:08 -0600 (CST) Subject: [Scipy-svn] r3760 - trunk/scipy/io Message-ID: <20080101220008.24FBE39C0B1@new.scipy.org> Author: oliphant Date: 2008-01-01 16:00:03 -0600 (Tue, 01 Jan 2008) New Revision: 3760 Modified: trunk/scipy/io/mmio.py Log: Fix-up merge issues when bringing in io_new over. Modified: trunk/scipy/io/mmio.py =================================================================== --- trunk/scipy/io/mmio.py 2008-01-01 09:35:56 UTC (rev 3759) +++ trunk/scipy/io/mmio.py 2008-01-01 22:00:03 UTC (rev 3760) @@ -283,10 +283,6 @@ if close_it: stream.close() else: stream.flush() - a = coo_matrix((V, (I, J)), shape=(rows, cols), dtype=dtype) - else: - raise NotImplementedError,`rep` - #--------------------------------------------------------------------------- def _init_attrs(self, **kwargs): """ From scipy-svn at scipy.org Tue Jan 1 23:07:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 1 Jan 2008 22:07:46 -0600 (CST) Subject: [Scipy-svn] r3761 - in branches/testing_cleanup/scipy: . lib/lapack/tests linalg/tests sandbox/exmplpackage/tests sandbox/timeseries sparse sparse/tests Message-ID: <20080102040746.2C7B439C019@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-01 22:07:30 -0600 (Tue, 01 Jan 2008) New Revision: 3761 Modified: branches/testing_cleanup/scipy/__init__.py branches/testing_cleanup/scipy/lib/lapack/tests/esv_tests.py branches/testing_cleanup/scipy/lib/lapack/tests/gesv_tests.py branches/testing_cleanup/scipy/lib/lapack/tests/test_lapack.py branches/testing_cleanup/scipy/linalg/tests/test_atlas_version.py branches/testing_cleanup/scipy/linalg/tests/test_basic.py branches/testing_cleanup/scipy/linalg/tests/test_blas.py branches/testing_cleanup/scipy/linalg/tests/test_decomp.py branches/testing_cleanup/scipy/linalg/tests/test_fblas.py branches/testing_cleanup/scipy/linalg/tests/test_iterative.py branches/testing_cleanup/scipy/linalg/tests/test_lapack.py branches/testing_cleanup/scipy/linalg/tests/test_matfuncs.py branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py branches/testing_cleanup/scipy/sandbox/timeseries/dates.py branches/testing_cleanup/scipy/sparse/construct.py branches/testing_cleanup/scipy/sparse/tests/test_sparse.py Log: Slow progress, delayed by a nasty hack in lib.lapack Modified: branches/testing_cleanup/scipy/__init__.py =================================================================== --- branches/testing_cleanup/scipy/__init__.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/__init__.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -14,12 +14,6 @@ """ -try: - import pkg_resources as _pr # activate namespace packages (manipulates __path__) - del _pr -except ImportError: - pass - __all__ = ['pkgload','test'] from numpy import show_config as show_numpy_config Modified: branches/testing_cleanup/scipy/lib/lapack/tests/esv_tests.py =================================================================== --- branches/testing_cleanup/scipy/lib/lapack/tests/esv_tests.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/lib/lapack/tests/esv_tests.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -1,8 +1,8 @@ -from numpy.testing import * -from numpy import * +from scipy.testing import * +from numpy import dot -class _test_ev: +class _test_ev(object): def check_syev(self,level=1,sym='sy',suffix=''): a = [[1,2,3],[2,2,3],[3,3,6]] Modified: branches/testing_cleanup/scipy/lib/lapack/tests/gesv_tests.py =================================================================== --- branches/testing_cleanup/scipy/lib/lapack/tests/gesv_tests.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/lib/lapack/tests/gesv_tests.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -1,8 +1,8 @@ -from numpy.testing import * -from numpy import * +from scipy.testing import * +from numpy import dot -class _test_gev: +class _test_gev(object): def check_sygv(self,level=1,sym='sy',suffix='',itype=1): a = [[1,2,3],[2,2,3],[3,3,6]] Modified: branches/testing_cleanup/scipy/lib/lapack/tests/test_lapack.py =================================================================== --- branches/testing_cleanup/scipy/lib/lapack/tests/test_lapack.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/lib/lapack/tests/test_lapack.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -2,33 +2,36 @@ # # Created by: Pearu Peterson, September 2002 # +''' +This file adapted for nose tests 1/1/08 -__usage__ = """ -Build lapack: - python setup_lapack.py build -Run tests if scipy is installed: - python -c 'import scipy;scipy.lib.lapack.test()' -Run tests if lapack is not installed: - python tests/test_lapack.py [] -""" +Note that the conversion is not very complete. +This and the included files deliberately use "check_" as the test +method names. There are no subclasses of TestCase. Thus nose will +pick up nothing but the final test_all_lapack generator function. +This does the work of collecting the test methods and checking if they +can be run (see the isrunnable method). +''' + import os import sys from scipy.testing import * -from numpy import array, ones +from numpy import dot, ones, zeros -from scipy.lib.lapack import flapack,clapack +from scipy.lib.lapack import flapack, clapack sys.path.insert(0, os.path.split(__file__)) from gesv_tests import _test_gev from esv_tests import _test_ev +del sys.path[0] #class _test_ev: pass -class _TestLapack(_test_ev, - _test_gev): - # Mixin class for lapack tests - def test_gebal(self): +class _TestLapack( _test_ev, + _test_gev): + + def check_gebal(self): a = [[1,2,3],[4,5,6],[7,8,9]] a1 = [[1,0,0,3e-4], [4,0,0,2e-3], @@ -45,7 +48,7 @@ ba,lo,hi,pivscale,info = f(a1,permute=1,scale=1) assert not info,`info` - def test_gehrd(self): + def check_gehrd(self): a = [[-149, -50,-154], [ 537, 180, 546], [ -27, -9, -25]] @@ -54,12 +57,13 @@ assert not info,`info` def isrunnable(self,mthname): + ''' Return True if required routines for check method present in module ''' l = mthname.split('_') if len(l)>1 and l[0]=='check': return hasattr(self.lapack,l[1]) return 2 -class PrefixWrapper: +class PrefixWrapper(object): def __init__(self,module,prefix): self.module = module self.prefix = prefix @@ -81,16 +85,16 @@ **************************************************************** """ else: - class TestFlapackDouble(TestCase, _TestLapack): + class TestFlapackDouble(_TestLapack): lapack = PrefixWrapper(flapack,'d') decimal = 12 - class TestFlapackFloat(TestCase, _TestLapack): + class TestFlapackFloat(_TestLapack): lapack = PrefixWrapper(flapack,'s') decimal = 5 - class TestFlapackComplex(TestCase, _TestLapack): + class TestFlapackComplex(_TestLapack): lapack = PrefixWrapper(flapack,'c') decimal = 5 - class TestFlapackDoubleComplex(TestCase, _TestLapack): + class TestFlapackDoubleComplex(_TestLapack): lapack = PrefixWrapper(flapack,'z') decimal = 12 @@ -106,18 +110,31 @@ **************************************************************** """ else: - class TestClapackDouble(TestCase, _TestLapack): + class TestClapackDouble(_TestLapack): lapack = PrefixWrapper(clapack,'d') decimal = 12 - class TestClapackFloat(TestCase, _TestLapack): + class TestClapackFloat(_TestLapack): lapack = PrefixWrapper(clapack,'s') decimal = 5 - class TestClapackComplex(TestCase, _TestLapack): + class TestClapackComplex(_TestLapack): lapack = PrefixWrapper(clapack,'c') decimal = 5 - class TestClapackDoubleComplex(TestCase, _TestLapack): + class TestClapackDoubleComplex(_TestLapack): lapack = PrefixWrapper(clapack,'z') decimal = 12 -if __name__ == "__main__": - unittest.main() +# Collect test classes and methods with generator +# This is a moderate hack replicating some obscure numpy testing +# functionality for use with nose + +def test_all_lapack(): + methods = [] + for name, value in globals().items(): + if not (name.startswith('Test') + and issubclass(value, _TestLapack)): + continue + o = value() + methods += [getattr(o, n) for n in dir(o) if o.isrunnable(n) is True] + for method in methods: + yield (method, ) + Modified: branches/testing_cleanup/scipy/linalg/tests/test_atlas_version.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_atlas_version.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/linalg/tests/test_atlas_version.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -4,10 +4,10 @@ # import sys -from numpy.testing import * -set_package_path() -import linalg.atlas_version -restore_path() +from scipy.testing import * +import scipy.linalg.atlas_version + + # No futher tests possible. # Importing atlas_version will print out atlas version. Modified: branches/testing_cleanup/scipy/linalg/tests/test_basic.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_basic.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/linalg/tests/test_basic.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -23,12 +23,12 @@ from numpy import arange, add, array, dot, zeros, identity, conjugate, transpose import sys -from numpy.testing import * -set_package_path() -from linalg import solve,inv,det,lstsq, toeplitz, hankel, tri, triu, tril -from linalg import pinv, pinv2, solve_banded -restore_path() +from scipy.testing import * +from scipy.linalg import solve,inv,det,lstsq, toeplitz, hankel, tri, triu, \ + tril, pinv, pinv2, solve_banded + + def random(size): return rand(*size) @@ -37,9 +37,9 @@ data = add.outer(data,data) return data -class TestSolveBanded(NumpyTestCase): +class TestSolveBanded(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,20,0,0],[-30,4,6,0],[2,1,20,2],[0,-1,7,14]] ab = [[0,20,6,2], @@ -52,9 +52,9 @@ x = solve_banded((l,u),ab,b) assert_array_almost_equal(numpy.dot(a,x),b) -class TestSolve(NumpyTestCase): +class TestSolve(TestCase): - def check_20Feb04_bug(self): + def test_20Feb04_bug(self): a = [[1,1],[1.0,0]] # ok x0 = solve(a,[1,0j]) assert_array_almost_equal(numpy.dot(a,x0),[1,0]) @@ -64,21 +64,21 @@ x0 = solve(a,b) assert_array_almost_equal(numpy.dot(a,x0),[1,0]) - def check_simple(self): + def test_simple(self): a = [[1,20],[-30,4]] for b in ([[1,0],[0,1]],[1,0], [[2,1],[-30,4]]): x = solve(a,b) assert_array_almost_equal(numpy.dot(a,x),b) - def check_simple_sym(self): + def test_simple_sym(self): a = [[2,3],[3,5]] for lower in [0,1]: for b in ([[1,0],[0,1]],[1,0]): x = solve(a,b,sym_pos=1,lower=lower) assert_array_almost_equal(numpy.dot(a,x),b) - def check_simple_sym_complex(self): + def test_simple_sym_complex(self): a = [[5,2],[2,4]] for b in [[1j,0], [[1j,1j], @@ -87,7 +87,7 @@ x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.dot(a,x),b) - def check_simple_complex(self): + def test_simple_complex(self): a = array([[5,2],[2j,4]],'D') for b in [[1j,0], [[1j,1j], @@ -98,7 +98,7 @@ x = solve(a,b) assert_array_almost_equal(numpy.dot(a,x),b) - def check_nils_20Feb04(self): + def test_nils_20Feb04(self): n = 2 A = random([n,n])+random([n,n])*1j X = zeros((n,n),'D') @@ -109,7 +109,7 @@ X[:,i] = solve(A,r) assert_array_almost_equal(X,Ainv) - def check_random(self): + def test_random(self): n = 20 a = random([n,n]) @@ -119,7 +119,7 @@ x = solve(a,b) assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_complex(self): + def test_random_complex(self): n = 20 a = random([n,n]) + 1j * random([n,n]) for i in range(n): a[i,i] = 20*(.1+a[i,i]) @@ -128,7 +128,7 @@ x = solve(a,b) assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_sym(self): + def test_random_sym(self): n = 20 a = random([n,n]) for i in range(n): @@ -140,7 +140,7 @@ x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_sym_complex(self): + def test_random_sym_complex(self): n = 20 a = random([n,n]) #a = a + 1j*random([n,n]) # XXX: with this the accuracy will be very low @@ -191,9 +191,9 @@ print ' (secs for %s calls)' % (repeat) -class TestInv(NumpyTestCase): +class TestInv(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2],[3,4]] a_inv = inv(a) assert_array_almost_equal(numpy.dot(a,a_inv), @@ -203,7 +203,7 @@ assert_array_almost_equal(numpy.dot(a,a_inv), [[1,0,0],[0,1,0],[0,0,1]]) - def check_random(self): + def test_random(self): n = 20 for i in range(4): a = random([n,n]) @@ -211,13 +211,13 @@ a_inv = inv(a) assert_array_almost_equal(numpy.dot(a,a_inv), numpy.identity(n)) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2],[3,4j]] a_inv = inv(a) assert_array_almost_equal(numpy.dot(a,a_inv), [[1,0],[0,1]]) - def check_random_complex(self): + def test_random_complex(self): n = 20 for i in range(4): a = random([n,n])+2j*random([n,n]) @@ -263,19 +263,19 @@ print ' (secs for %s calls)' % (repeat) -class TestDet(NumpyTestCase): +class TestDet(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2],[3,4]] a_det = det(a) assert_almost_equal(a_det,-2.0) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2],[3,4j]] a_det = det(a) assert_almost_equal(a_det,-6+4j) - def check_random(self): + def test_random(self): import numpy.linalg as linalg basic_det = linalg.det n = 20 @@ -285,7 +285,7 @@ d2 = basic_det(a) assert_almost_equal(d1,d2) - def check_random_complex(self): + def test_random_complex(self): import numpy.linalg as linalg basic_det = linalg.det n = 20 @@ -338,8 +338,8 @@ b1 = dot(at, b) return solve(a1, b1) -class TestLstsq(NumpyTestCase): - def check_random_overdet_large(self): +class TestLstsq(TestCase): + def test_random_overdet_large(self): #bug report: Nils Wagner n = 200 a = random([n,2]) @@ -348,21 +348,21 @@ x = lstsq(a,b)[0] assert_array_almost_equal(x,direct_lstsq(a,b)) - def check_simple_exact(self): + def test_simple_exact(self): a = [[1,20],[-30,4]] for b in ([[1,0],[0,1]],[1,0], [[2,1],[-30,4]]): x = lstsq(a,b)[0] assert_array_almost_equal(numpy.dot(a,x),b) - def check_simple_overdet(self): + def test_simple_overdet(self): a = [[1,2],[4,5],[3,4]] b = [1,2,3] x,res,r,s = lstsq(a,b) #XXX: check defintion of res assert_array_almost_equal(x,direct_lstsq(a,b)) - def check_simple_underdet(self): + def test_simple_underdet(self): a = [[1,2,3],[4,5,6]] b = [1,2] x,res,r,s = lstsq(a,b) @@ -370,7 +370,7 @@ assert_array_almost_equal(x,[[-0.05555556], [0.11111111],[0.27777778]]) - def check_random_exact(self): + def test_random_exact(self): n = 20 a = random([n,n]) @@ -380,7 +380,7 @@ x = lstsq(a,b)[0] assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_complex_exact(self): + def test_random_complex_exact(self): n = 20 a = random([n,n]) + 1j * random([n,n]) for i in range(n): a[i,i] = 20*(.1+a[i,i]) @@ -389,7 +389,7 @@ x = lstsq(a,b)[0] assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_overdet(self): + def test_random_overdet(self): n = 20 m = 15 a = random([n,m]) @@ -401,7 +401,7 @@ #XXX: check definition of res assert_array_almost_equal(x,direct_lstsq(a,b)) - def check_random_complex_overdet(self): + def test_random_complex_overdet(self): n = 20 m = 15 a = random([n,m]) + 1j * random([n,m]) @@ -414,8 +414,8 @@ #XXX: check definition of res assert_array_almost_equal(x,direct_lstsq(a,b,1)) -class TestTri(NumpyTestCase): - def check_basic(self): +class TestTri(TestCase): + def test_basic(self): assert_equal(tri(4),array([[1,0,0,0], [1,1,0,0], [1,1,1,0], @@ -424,7 +424,7 @@ [1,1,0,0], [1,1,1,0], [1,1,1,1]],'f')) - def check_diag(self): + def test_diag(self): assert_equal(tri(4,k=1),array([[1,1,0,0], [1,1,1,0], [1,1,1,1], @@ -433,7 +433,7 @@ [1,0,0,0], [1,1,0,0], [1,1,1,0]])) - def check_2d(self): + def test_2d(self): assert_equal(tri(4,3),array([[1,0,0], [1,1,0], [1,1,1], @@ -441,7 +441,7 @@ assert_equal(tri(3,4),array([[1,0,0,0], [1,1,0,0], [1,1,1,0]])) - def check_diag2d(self): + def test_diag2d(self): assert_equal(tri(3,4,k=2),array([[1,1,1,0], [1,1,1,1], [1,1,1,1]])) @@ -450,8 +450,8 @@ [1,0,0], [1,1,0]])) -class TestTril(NumpyTestCase): - def check_basic(self): +class TestTril(TestCase): + def test_basic(self): a = (100*get_mat(5)).astype('l') b = a.copy() for k in range(5): @@ -459,7 +459,7 @@ b[k,l] = 0 assert_equal(tril(a),b) - def check_diag(self): + def test_diag(self): a = (100*get_mat(5)).astype('f') b = a.copy() for k in range(5): @@ -472,8 +472,8 @@ b[k,l] = 0 assert_equal(tril(a,k=-2),b) -class TestTriu(NumpyTestCase): - def check_basic(self): +class TestTriu(TestCase): + def test_basic(self): a = (100*get_mat(5)).astype('l') b = a.copy() for k in range(5): @@ -481,7 +481,7 @@ b[l,k] = 0 assert_equal(triu(a),b) - def check_diag(self): + def test_diag(self): a = (100*get_mat(5)).astype('f') b = a.copy() for k in range(5): @@ -494,46 +494,46 @@ b[l,k] = 0 assert_equal(triu(a,k=-2),b) -class TestToeplitz(NumpyTestCase): - def check_basic(self): +class TestToeplitz(TestCase): + def test_basic(self): y = toeplitz([1,2,3]) assert_array_equal(y,[[1,2,3],[2,1,2],[3,2,1]]) y = toeplitz([1,2,3],[1,4,5]) assert_array_equal(y,[[1,4,5],[2,1,4],[3,2,1]]) -class TestHankel(NumpyTestCase): - def check_basic(self): +class TestHankel(TestCase): + def test_basic(self): y = hankel([1,2,3]) assert_array_equal(y,[[1,2,3],[2,3,0],[3,0,0]]) y = hankel([1,2,3],[3,4,5]) assert_array_equal(y,[[1,2,3],[2,3,4],[3,4,5]]) -class TestPinv(NumpyTestCase): +class TestPinv(TestCase): - def check_simple(self): + def test_simple(self): a=array([[1,2,3],[4,5,6.],[7,8,10]]) a_pinv = pinv(a) assert_array_almost_equal(dot(a,a_pinv),[[1,0,0],[0,1,0],[0,0,1]]) a_pinv = pinv2(a) assert_array_almost_equal(dot(a,a_pinv),[[1,0,0],[0,1,0],[0,0,1]]) - def check_simple_0det(self): + def test_simple_0det(self): a=array([[1,2,3],[4,5,6.],[7,8,9]]) a_pinv = pinv(a) a_pinv2 = pinv2(a) assert_array_almost_equal(a_pinv,a_pinv2) - def check_simple_cols(self): + def test_simple_cols(self): a=array([[1,2,3],[4,5,6.]]) a_pinv = pinv(a) a_pinv2 = pinv2(a) assert_array_almost_equal(a_pinv,a_pinv2) - def check_simple_rows(self): + def test_simple_rows(self): a=array([[1,2],[3,4],[5,6]]) a_pinv = pinv(a) a_pinv2 = pinv2(a) assert_array_almost_equal(a_pinv,a_pinv2) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/linalg/tests/test_blas.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_blas.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/linalg/tests/test_blas.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -12,21 +12,19 @@ python tests/test_blas.py [] """ +import sys +import math from numpy import arange, add, array -import math -import sys -from numpy.testing import * -set_package_path() -from linalg import fblas -print fblas -from linalg import cblas -restore_path() +from scipy.testing import * -class TestCBLAS1Simple(NumpyTestCase): +from scipy.linalg import fblas, cblas - def check_axpy(self): + +class TestCBLAS1Simple(TestCase): + + def test_axpy(self): for p in 'sd': f = getattr(cblas,p+'axpy',None) if f is None: continue @@ -36,9 +34,9 @@ if f is None: continue assert_array_almost_equal(f(5,[1,2j,3],[2,-1,3]),[7,10j-1,18]) -class TestFBLAS1Simple(NumpyTestCase): +class TestFBLAS1Simple(TestCase): - def check_axpy(self): + def test_axpy(self): for p in 'sd': f = getattr(fblas,p+'axpy',None) if f is None: continue @@ -47,7 +45,7 @@ f = getattr(fblas,p+'axpy',None) if f is None: continue assert_array_almost_equal(f([1,2j,3],[2,-1,3],a=5),[7,10j-1,18]) - def check_copy(self): + def test_copy(self): for p in 'sd': f = getattr(fblas,p+'copy',None) if f is None: continue @@ -56,7 +54,7 @@ f = getattr(fblas,p+'copy',None) if f is None: continue assert_array_almost_equal(f([3,4j,5+3j],[8]*3),[3,4j,5+3j]) - def check_asum(self): + def test_asum(self): for p in 'sd': f = getattr(fblas,p+'asum',None) if f is None: continue @@ -65,24 +63,24 @@ f = getattr(fblas,p+'asum',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j]),14) - def check_dot(self): + def test_dot(self): for p in 'sd': f = getattr(fblas,p+'dot',None) if f is None: continue assert_almost_equal(f([3,-4,5],[2,5,1]),-9) - def check_complex_dotu(self): + def test_complex_dotu(self): for p in 'cz': f = getattr(fblas,p+'dotu',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j],[2,3,1]),-9+2j) - def check_complex_dotc(self): + def test_complex_dotc(self): for p in 'cz': f = getattr(fblas,p+'dotc',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j],[2,3j,1]),3-14j) - def check_nrm2(self): + def test_nrm2(self): for p in 'sd': f = getattr(fblas,p+'nrm2',None) if f is None: continue @@ -91,7 +89,7 @@ f = getattr(fblas,p+'nrm2',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j]),math.sqrt(50)) - def check_scal(self): + def test_scal(self): for p in 'sd': f = getattr(fblas,p+'scal',None) if f is None: continue @@ -104,7 +102,7 @@ f = getattr(fblas,p+'scal',None) if f is None: continue assert_array_almost_equal(f(3,[3j,-4,3-4j]),[9j,-12,9-12j]) - def check_swap(self): + def test_swap(self): for p in 'sd': f = getattr(fblas,p+'swap',None) if f is None: continue @@ -119,7 +117,7 @@ x1,y1 = f(x,y) assert_array_almost_equal(x1,y) assert_array_almost_equal(y1,x) - def check_amax(self): + def test_amax(self): for p in 'sd': f = getattr(fblas,'i'+p+'amax') assert_equal(f([-2,4,3]),1) @@ -128,9 +126,9 @@ assert_equal(f([-5,4+3j,6]),1) #XXX: need tests for rot,rotm,rotg,rotmg -class TestFBLAS2Simple(NumpyTestCase): +class TestFBLAS2Simple(TestCase): - def check_gemv(self): + def test_gemv(self): for p in 'sd': f = getattr(fblas,p+'gemv',None) if f is None: continue @@ -142,7 +140,7 @@ assert_array_almost_equal(f(3j,[[3-4j]],[-4]),[-48-36j]) assert_array_almost_equal(f(3j,[[3-4j]],[-4],3,[5j]),[-48-21j]) - def check_ger(self): + def test_ger(self): for p in 'sd': f = getattr(fblas,p+'ger',None) @@ -176,9 +174,9 @@ 2j, 3j],[3j,4j]),[[6,8],[12,16],[18,24]]) -class TestFBLAS3Simple(NumpyTestCase): +class TestFBLAS3Simple(TestCase): - def check_gemm(self): + def test_gemm(self): for p in 'sd': f = getattr(fblas,p+'gemm',None) if f is None: continue @@ -190,9 +188,9 @@ assert_array_almost_equal(f(3j,[3-4j],[-4]),[[-48-36j]]) assert_array_almost_equal(f(3j,[3-4j],[-4],3,[5j]),[-48-21j]) -class TestBLAS(NumpyTestCase): +class TestBLAS(TestCase): - def check_fblas(self): + def test_fblas(self): if hasattr(fblas,'empty_module'): print """ **************************************************************** @@ -201,7 +199,7 @@ See scipy/INSTALL.txt for troubleshooting. **************************************************************** """ - def check_cblas(self): + def test_cblas(self): if hasattr(cblas,'empty_module'): print """ **************************************************************** @@ -215,4 +213,4 @@ """ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/linalg/tests/test_decomp.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_decomp.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/linalg/tests/test_decomp.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -15,31 +15,35 @@ """ import sys -from numpy.testing import * +from scipy.testing import * -set_package_path() -from linalg import eig,eigvals,lu,svd,svdvals,cholesky,qr,schur,rsf2csf -from linalg import lu_solve,lu_factor,solve,diagsvd,hessenberg,rq -from linalg import eig_banded,eigvals_banded -from linalg.flapack import dgbtrf, dgbtrs, zgbtrf, zgbtrs -from linalg.flapack import dsbev, dsbevd, dsbevx, zhbevd, zhbevx -restore_path() -from numpy import * +from scipy.linalg import eig,eigvals,lu,svd,svdvals,cholesky,qr, \ + schur,rsf2csf, lu_solve,lu_factor,solve,diagsvd,hessenberg,rq, \ + eig_banded, eigvals_banded +from scipy.linalg.flapack import dgbtrf, dgbtrs, zgbtrf, zgbtrs, \ + dsbev, dsbevd, dsbevx, zhbevd, zhbevx + +from numpy import array, transpose, sometrue, diag, ones, linalg, \ + argsort, zeros, arange, float32, complex64, dot, conj, identity, \ + ravel, sqrt, iscomplex, shape, sort, sign, conjugate, sign, bmat, \ + asarray, matrix, isfinite + + from numpy.random import rand def random(size): return rand(*size) -class TestEigVals(NumpyTestCase): +class TestEigVals(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2,3],[1,2,3],[2,5,6]] w = eigvals(a) exact_w = [(9+sqrt(93))/2,0,(9-sqrt(93))/2] assert_array_almost_equal(w,exact_w) - def check_simple_tr(self): + def test_simple_tr(self): a = array([[1,2,3],[1,2,3],[2,5,6]],'d') a = transpose(a).copy() a = transpose(a) @@ -47,7 +51,7 @@ exact_w = [(9+sqrt(93))/2,0,(9-sqrt(93))/2] assert_array_almost_equal(w,exact_w) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2,3],[1,2,3],[2,5,6+1j]] w = eigvals(a) exact_w = [(9+1j+sqrt(92+6j))/2, @@ -77,9 +81,9 @@ print ' (secs for %s calls)' % (repeat) -class TestEig(NumpyTestCase): +class TestEig(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2,3],[1,2,3],[2,5,6]] w,v = eig(a) exact_w = [(9+sqrt(93))/2,0,(9-sqrt(93))/2] @@ -99,7 +103,7 @@ for i in range(3): assert_array_almost_equal(dot(transpose(a),v[:,i]),w[i]*v[:,i]) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2,3],[1,2,3],[2,5,6+1j]] w,vl,vr = eig(a,left=1,right=1) for i in range(3): @@ -151,10 +155,10 @@ if all(isfinite(res[:, i])): assert_array_almost_equal(res[:, i], 0) -class TestEigBanded(NumpyTestCase): +class TestEigBanded(TestCase): def __init__(self, *args): - NumpyTestCase.__init__(self, *args) + TestCase.__init__(self, *args) self.create_bandmat() @@ -238,7 +242,7 @@ ##################################################################### - def check_dsbev(self): + def test_dsbev(self): """Compare dsbev eigenvalues and eigenvectors with the result of linalg.eig.""" w, evec, info = dsbev(self.bandmat_sym, compute_v=1) @@ -248,7 +252,7 @@ - def check_dsbevd(self): + def test_dsbevd(self): """Compare dsbevd eigenvalues and eigenvectors with the result of linalg.eig.""" w, evec, info = dsbevd(self.bandmat_sym, compute_v=1) @@ -258,7 +262,7 @@ - def check_dsbevx(self): + def test_dsbevx(self): """Compare dsbevx eigenvalues and eigenvectors with the result of linalg.eig.""" N,N = shape(self.sym_mat) @@ -270,7 +274,7 @@ assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin)) - def check_zhbevd(self): + def test_zhbevd(self): """Compare zhbevd eigenvalues and eigenvectors with the result of linalg.eig.""" w, evec, info = zhbevd(self.bandmat_herm, compute_v=1) @@ -280,7 +284,7 @@ - def check_zhbevx(self): + def test_zhbevx(self): """Compare zhbevx eigenvalues and eigenvectors with the result of linalg.eig.""" N,N = shape(self.herm_mat) @@ -293,7 +297,7 @@ - def check_eigvals_banded(self): + def test_eigvals_banded(self): """Compare eigenvalues of eigvals_banded with those of linalg.eig.""" w_sym = eigvals_banded(self.bandmat_sym) w_sym = w_sym.real @@ -332,7 +336,7 @@ - def check_eig_banded(self): + def test_eig_banded(self): """Compare eigenvalues and eigenvectors of eig_banded with those of linalg.eig. """ w_sym, evec_sym = eig_banded(self.bandmat_sym) @@ -382,7 +386,7 @@ abs(self.evec_herm_lin[:,ind1:ind2+1]) ) - def check_dgbtrf(self): + def test_dgbtrf(self): """Compare dgbtrf LU factorisation with the LU factorisation result of linalg.lu.""" M,N = shape(self.real_mat) @@ -397,7 +401,7 @@ assert_array_almost_equal(u, u_lin) - def check_zgbtrf(self): + def test_zgbtrf(self): """Compare zgbtrf LU factorisation with the LU factorisation result of linalg.lu.""" M,N = shape(self.comp_mat) @@ -413,7 +417,7 @@ - def check_dgbtrs(self): + def test_dgbtrs(self): """Compare dgbtrs solutions for linear equation system A*x = b with solutions of linalg.solve.""" @@ -423,7 +427,7 @@ y_lin = linalg.solve(self.real_mat, self.b) assert_array_almost_equal(y, y_lin) - def check_zgbtrs(self): + def test_zgbtrs(self): """Compare zgbtrs solutions for linear equation system A*x = b with solutions of linalg.solve.""" @@ -436,10 +440,10 @@ -class TestLU(NumpyTestCase): +class TestLU(TestCase): def __init__(self, *args, **kw): - NumpyTestCase.__init__(self, *args, **kw) + TestCase.__init__(self, *args, **kw) self.a = array([[1,2,3],[1,2,3],[2,5,6]]) self.ca = array([[1,2,3],[1,2,3],[2,5j,6]]) @@ -466,37 +470,37 @@ assert_array_almost_equal(dot(pl,u),data) # Simple tests - def check_simple(self): + def test_simple(self): self._test_common(self.a) - def check_simple_complex(self): + def test_simple_complex(self): self._test_common(self.ca) - def check_simple2(self): + def test_simple2(self): self._test_common(self.b) - def check_simple2_complex(self): + def test_simple2_complex(self): self._test_common(self.cb) # rectangular matrices tests - def check_hrectangular(self): + def test_hrectangular(self): self._test_common(self.hrect) - def check_vrectangular(self): + def test_vrectangular(self): self._test_common(self.vrect) - def check_hrectangular_complex(self): + def test_hrectangular_complex(self): self._test_common(self.chrect) - def check_vrectangular_complex(self): + def test_vrectangular_complex(self): self._test_common(self.cvrect) # Bigger matrices - def check_medium1(self, level = 2): + def test_medium1(self): """Check lu decomposition on medium size, rectangular matrix.""" self._test_common(self.med) - def check_medium1_complex(self, level = 2): + def test_medium1_complex(self): """Check lu decomposition on medium size, rectangular matrix.""" self._test_common(self.cmed) @@ -519,8 +523,8 @@ self.med = self.vrect.astype(float32) self.cmed = self.vrect.astype(complex64) -class TestLUSolve(NumpyTestCase): - def check_lu(self): +class TestLUSolve(TestCase): + def test_lu(self): a = random((10,10)) b = random((10,)) @@ -531,9 +535,9 @@ assert_array_equal(x1,x2) -class TestSVD(NumpyTestCase): +class TestSVD(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2,3],[1,20,3],[2,5,6]] u,s,vh = svd(a) assert_array_almost_equal(dot(transpose(u),u),identity(3)) @@ -542,7 +546,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_simple_singular(self): + def test_simple_singular(self): a = [[1,2,3],[1,2,3],[2,5,6]] u,s,vh = svd(a) assert_array_almost_equal(dot(transpose(u),u),identity(3)) @@ -551,7 +555,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_simple_underdet(self): + def test_simple_underdet(self): a = [[1,2,3],[4,5,6]] u,s,vh = svd(a) assert_array_almost_equal(dot(transpose(u),u),identity(2)) @@ -560,7 +564,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_simple_overdet(self): + def test_simple_overdet(self): a = [[1,2],[4,5],[3,4]] u,s,vh = svd(a) assert_array_almost_equal(dot(transpose(u),u),identity(3)) @@ -569,7 +573,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_random(self): + def test_random(self): n = 20 m = 15 for i in range(3): @@ -581,7 +585,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2,3],[1,2j,3],[2,5,6]] u,s,vh = svd(a) assert_array_almost_equal(dot(conj(transpose(u)),u),identity(3)) @@ -590,7 +594,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_random_complex(self): + def test_random_complex(self): n = 20 m = 15 for i in range(3): @@ -604,52 +608,52 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) -class TestSVDVals(NumpyTestCase): +class TestSVDVals(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2,3],[1,2,3],[2,5,6]] s = svdvals(a) assert len(s)==3 assert s[0]>=s[1]>=s[2] - def check_simple_underdet(self): + def test_simple_underdet(self): a = [[1,2,3],[4,5,6]] s = svdvals(a) assert len(s)==2 assert s[0]>=s[1] - def check_simple_overdet(self): + def test_simple_overdet(self): a = [[1,2],[4,5],[3,4]] s = svdvals(a) assert len(s)==2 assert s[0]>=s[1] - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2,3],[1,20,3j],[2,5,6]] s = svdvals(a) assert len(s)==3 assert s[0]>=s[1]>=s[2] - def check_simple_underdet_complex(self): + def test_simple_underdet_complex(self): a = [[1,2,3],[4,5j,6]] s = svdvals(a) assert len(s)==2 assert s[0]>=s[1] - def check_simple_overdet_complex(self): + def test_simple_overdet_complex(self): a = [[1,2],[4,5],[3j,4]] s = svdvals(a) assert len(s)==2 assert s[0]>=s[1] -class TestDiagSVD(NumpyTestCase): +class TestDiagSVD(TestCase): - def check_simple(self): + def test_simple(self): assert_array_almost_equal(diagsvd([1,0,0],3,3),[[1,0,0],[0,0,0],[0,0,0]]) -class TestCholesky(NumpyTestCase): +class TestCholesky(TestCase): - def check_simple(self): + def test_simple(self): a = [[8,2,3],[2,9,3],[3,3,6]] c = cholesky(a) assert_array_almost_equal(dot(transpose(c),c),a) @@ -657,7 +661,7 @@ a = dot(c,transpose(c)) assert_array_almost_equal(cholesky(a,lower=1),c) - def check_simple_complex(self): + def test_simple_complex(self): m = array([[3+1j,3+4j,5],[0,2+2j,2+7j],[0,0,7+4j]]) a = dot(transpose(conjugate(m)),m) c = cholesky(a) @@ -667,7 +671,7 @@ a = dot(c,transpose(conjugate(c))) assert_array_almost_equal(cholesky(a,lower=1),c) - def check_random(self): + def test_random(self): n = 20 for k in range(2): m = random([n,n]) @@ -681,7 +685,7 @@ a = dot(c,transpose(c)) assert_array_almost_equal(cholesky(a,lower=1),c) - def check_random_complex(self): + def test_random_complex(self): n = 20 for k in range(2): m = random([n,n])+1j*random([n,n]) @@ -696,28 +700,28 @@ assert_array_almost_equal(cholesky(a,lower=1),c) -class TestQR(NumpyTestCase): +class TestQR(TestCase): - def check_simple(self): + def test_simple(self): a = [[8,2,3],[2,9,3],[5,3,6]] q,r = qr(a) assert_array_almost_equal(dot(transpose(q),q),identity(3)) assert_array_almost_equal(dot(q,r),a) - def check_simple_trap(self): + def test_simple_trap(self): a = [[8,2,3],[2,9,3]] q,r = qr(a) assert_array_almost_equal(dot(transpose(q),q),identity(2)) assert_array_almost_equal(dot(q,r),a) - def check_simple_tall(self): + def test_simple_tall(self): # full version a = [[8,2],[2,9],[5,3]] q,r = qr(a) assert_array_almost_equal(dot(transpose(q),q),identity(3)) assert_array_almost_equal(dot(q,r),a) - def check_simple_tall_e(self): + def test_simple_tall_e(self): # economy version a = [[8,2],[2,9],[5,3]] q,r = qr(a,econ=True) @@ -726,13 +730,13 @@ assert_equal(q.shape, (3,2)) assert_equal(r.shape, (2,2)) - def check_simple_complex(self): + def test_simple_complex(self): a = [[3,3+4j,5],[5,2,2+7j],[3,2,7]] q,r = qr(a) assert_array_almost_equal(dot(conj(transpose(q)),q),identity(3)) assert_array_almost_equal(dot(q,r),a) - def check_random(self): + def test_random(self): n = 20 for k in range(2): a = random([n,n]) @@ -740,7 +744,7 @@ assert_array_almost_equal(dot(transpose(q),q),identity(n)) assert_array_almost_equal(dot(q,r),a) - def check_random_tall(self): + def test_random_tall(self): # full version m = 200 n = 100 @@ -750,7 +754,7 @@ assert_array_almost_equal(dot(transpose(q),q),identity(m)) assert_array_almost_equal(dot(q,r),a) - def check_random_tall_e(self): + def test_random_tall_e(self): # economy version m = 200 n = 100 @@ -762,7 +766,7 @@ assert_equal(q.shape, (m,n)) assert_equal(r.shape, (n,n)) - def check_random_trap(self): + def test_random_trap(self): m = 100 n = 200 for k in range(2): @@ -771,7 +775,7 @@ assert_array_almost_equal(dot(transpose(q),q),identity(m)) assert_array_almost_equal(dot(q,r),a) - def check_random_complex(self): + def test_random_complex(self): n = 20 for k in range(2): a = random([n,n])+1j*random([n,n]) @@ -779,15 +783,15 @@ assert_array_almost_equal(dot(conj(transpose(q)),q),identity(n)) assert_array_almost_equal(dot(q,r),a) -class TestRQ(NumpyTestCase): +class TestRQ(TestCase): - def check_simple(self): + def test_simple(self): a = [[8,2,3],[2,9,3],[5,3,6]] r,q = rq(a) assert_array_almost_equal(dot(transpose(q),q),identity(3)) assert_array_almost_equal(dot(r,q),a) - def check_random(self): + def test_random(self): n = 20 for k in range(2): a = random([n,n]) @@ -797,25 +801,25 @@ # TODO: implement support for non-square and complex arrays -## def check_simple_trap(self): +## def test_simple_trap(self): ## a = [[8,2,3],[2,9,3]] ## r,q = rq(a) ## assert_array_almost_equal(dot(transpose(q),q),identity(2)) ## assert_array_almost_equal(dot(r,q),a) -## def check_simple_tall(self): +## def test_simple_tall(self): ## a = [[8,2],[2,9],[5,3]] ## r,q = rq(a) ## assert_array_almost_equal(dot(transpose(q),q),identity(3)) ## assert_array_almost_equal(dot(r,q),a) -## def check_simple_complex(self): +## def test_simple_complex(self): ## a = [[3,3+4j,5],[5,2,2+7j],[3,2,7]] ## r,q = rq(a) ## assert_array_almost_equal(dot(conj(transpose(q)),q),identity(3)) ## assert_array_almost_equal(dot(r,q),a) -## def check_random_tall(self): +## def test_random_tall(self): ## m = 200 ## n = 100 ## for k in range(2): @@ -824,7 +828,7 @@ ## assert_array_almost_equal(dot(transpose(q),q),identity(m)) ## assert_array_almost_equal(dot(r,q),a) -## def check_random_trap(self): +## def test_random_trap(self): ## m = 100 ## n = 200 ## for k in range(2): @@ -833,7 +837,7 @@ ## assert_array_almost_equal(dot(transpose(q),q),identity(m)) ## assert_array_almost_equal(dot(r,q),a) -## def check_random_complex(self): +## def test_random_complex(self): ## n = 20 ## for k in range(2): ## a = random([n,n])+1j*random([n,n]) @@ -844,9 +848,9 @@ transp = transpose any = sometrue -class TestSchur(NumpyTestCase): +class TestSchur(TestCase): - def check_simple(self): + def test_simple(self): a = [[8,12,3],[2,9,3],[10,3,6]] t,z = schur(a) assert_array_almost_equal(dot(dot(z,t),transp(conj(z))),a) @@ -856,9 +860,9 @@ tc2,zc2 = rsf2csf(tc,zc) assert_array_almost_equal(dot(dot(zc2,tc2),transp(conj(zc2))),a) -class TestHessenberg(NumpyTestCase): +class TestHessenberg(TestCase): - def check_simple(self): + def test_simple(self): a = [[-149, -50,-154], [ 537, 180, 546], [ -27, -9, -25]] @@ -869,7 +873,7 @@ assert_array_almost_equal(dot(transp(q),dot(a,q)),h) assert_array_almost_equal(h,h1,decimal=4) - def check_simple_complex(self): + def test_simple_complex(self): a = [[-149, -50,-154], [ 537, 180j, 546], [ -27j, -9, -25]] @@ -877,7 +881,7 @@ h1 = dot(transp(conj(q)),dot(a,q)) assert_array_almost_equal(h1,h) - def check_simple2(self): + def test_simple2(self): a = [[1,2,3,4,5,6,7], [0,2,3,4,6,7,2], [0,2,2,3,0,3,2], @@ -888,14 +892,14 @@ h,q = hessenberg(a,calc_q=1) assert_array_almost_equal(dot(transp(q),dot(a,q)),h) - def check_random(self): + def test_random(self): n = 20 for k in range(2): a = random([n,n]) h,q = hessenberg(a,calc_q=1) assert_array_almost_equal(dot(transp(q),dot(a,q)),h) - def check_random_complex(self): + def test_random_complex(self): n = 20 for k in range(2): a = random([n,n])+1j*random([n,n]) @@ -905,9 +909,9 @@ -class TestDataNotShared(NumpyTestCase): +class TestDataNotShared(TestCase): - def check_datanotshared(self): + def test_datanotshared(self): from scipy.linalg.decomp import _datanotshared M = matrix([[0,1],[2,3]]) @@ -924,4 +928,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/linalg/tests/test_fblas.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_fblas.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/linalg/tests/test_fblas.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -6,14 +6,16 @@ # !! Complex calculations really aren't checked that carefully. # !! Only real valued complex numbers are used in tests. -from numpy import * - import sys -from numpy.testing import * -set_package_path() -from linalg import fblas -restore_path() +from numpy import dot, float32, float64, complex64, complex128, \ + arange, array, zeros, shape, transpose, newaxis, \ + common_type, conjugate +from scipy.linalg import fblas + +from scipy.testing import * + + #decimal accuracy to require between Python and LAPACK/BLAS calculations accuracy = 5 @@ -40,39 +42,40 @@ ################################################## ### Test blas ?axpy -class BaseAxpy(NumpyTestCase): - def check_default_a(self): +class BaseAxpy(object): + ''' Mixin class for axpy tests ''' + def test_default_a(self): x = arange(3.,dtype=self.dtype) y = arange(3.,dtype=x.dtype) real_y = x*1.+y self.blas_func(x,y) assert_array_equal(real_y,y) - def check_simple(self): + def test_simple(self): x = arange(3.,dtype=self.dtype) y = arange(3.,dtype=x.dtype) real_y = x*3.+y self.blas_func(x,y,a=3.) assert_array_equal(real_y,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) y = arange(3.,dtype=x.dtype) real_y = x[::2]*3.+y self.blas_func(x,y,a=3.,n=3,incx=2) assert_array_equal(real_y,y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) real_y = x*3.+y[::2] self.blas_func(x,y,a=3.,n=3,incy=2) assert_array_equal(real_y,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) real_y = x[::4]*3.+y[::2] self.blas_func(x,y,a=3.,n=3,incx=4,incy=2) assert_array_equal(real_y,y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -81,7 +84,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -92,21 +95,21 @@ assert(0) try: - class TestSaxpy(BaseAxpy): + class TestSaxpy(TestCase, BaseAxpy): blas_func = fblas.saxpy dtype = float32 except AttributeError: class TestSaxpy: pass -class TestDaxpy(BaseAxpy): +class TestDaxpy(TestCase, BaseAxpy): blas_func = fblas.daxpy dtype = float64 try: - class TestCaxpy(BaseAxpy): + class TestCaxpy(TestCase, BaseAxpy): blas_func = fblas.caxpy dtype = complex64 except AttributeError: class TestCaxpy: pass -class TestZaxpy(BaseAxpy): +class TestZaxpy(TestCase, BaseAxpy): blas_func = fblas.zaxpy dtype = complex128 @@ -114,19 +117,20 @@ ################################################## ### Test blas ?scal -class BaseScal(NumpyTestCase): - def check_simple(self): +class BaseScal(object): + ''' Mixin class for scal testing ''' + def test_simple(self): x = arange(3.,dtype=self.dtype) real_x = x*3. self.blas_func(3.,x) assert_array_equal(real_x,x) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) real_x = x.copy() real_x[::2] = x[::2]*array(3.,self.dtype) self.blas_func(3.,x,n=3,incx=2) assert_array_equal(real_x,x) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) try: self.blas_func(2.,x,n=4,incx=5) @@ -135,21 +139,21 @@ # should catch error and never get here assert(0) try: - class TestSscal(BaseScal): + class TestSscal(TestCase, BaseScal): blas_func = fblas.sscal dtype = float32 except AttributeError: class TestSscal: pass -class TestDscal(BaseScal): +class TestDscal(TestCase, BaseScal): blas_func = fblas.dscal dtype = float64 try: - class TestCscal(BaseScal): + class TestCscal(TestCase, BaseScal): blas_func = fblas.cscal dtype = complex64 except AttributeError: class TestCscal: pass -class TestZscal(BaseScal): +class TestZscal(TestCase, BaseScal): blas_func = fblas.zscal dtype = complex128 @@ -159,28 +163,29 @@ ################################################## ### Test blas ?copy -class BaseCopy(NumpyTestCase): - def check_simple(self): +class BaseCopy(object): + ''' Mixin class for copy testing ''' + def test_simple(self): x = arange(3.,dtype=self.dtype) y = zeros(shape(x),x.dtype) self.blas_func(x,y) assert_array_equal(x,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) self.blas_func(x,y,n=3,incx=2) assert_array_equal(x[::2],y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) self.blas_func(x,y,n=3,incy=2) assert_array_equal(x,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) self.blas_func(x,y,n=3,incx=4,incy=2) assert_array_equal(x[::4],y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -189,7 +194,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -198,7 +203,7 @@ return # should catch error and never get here assert(0) - #def check_y_bad_type(self): + #def test_y_bad_type(self): ## Hmmm. Should this work? What should be the output. # x = arange(3.,dtype=self.dtype) # y = zeros(shape(x)) @@ -206,21 +211,21 @@ # assert_array_equal(x,y) try: - class TestScopy(BaseCopy): + class TestScopy(TestCase, BaseCopy): blas_func = fblas.scopy dtype = float32 except AttributeError: class TestScopy: pass -class TestDcopy(BaseCopy): +class TestDcopy(TestCase, BaseCopy): blas_func = fblas.dcopy dtype = float64 try: - class TestCcopy(BaseCopy): + class TestCcopy(TestCase, BaseCopy): blas_func = fblas.ccopy dtype = complex64 except AttributeError: class TestCcopy: pass -class TestZcopy(BaseCopy): +class TestZcopy(TestCase, BaseCopy): blas_func = fblas.zcopy dtype = complex128 @@ -228,8 +233,9 @@ ################################################## ### Test blas ?swap -class BaseSwap(NumpyTestCase): - def check_simple(self): +class BaseSwap(object): + ''' Mixin class for swap tests ''' + def test_simple(self): x = arange(3.,dtype=self.dtype) y = zeros(shape(x),x.dtype) desired_x = y.copy() @@ -237,7 +243,7 @@ self.blas_func(x,y) assert_array_equal(desired_x,x) assert_array_equal(desired_y,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) desired_x = y.copy() @@ -245,7 +251,7 @@ self.blas_func(x,y,n=3,incx=2) assert_array_equal(desired_x,x[::2]) assert_array_equal(desired_y,y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) desired_x = y.copy()[::2] @@ -254,7 +260,7 @@ assert_array_equal(desired_x,x) assert_array_equal(desired_y,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) desired_x = y.copy()[::2] @@ -262,7 +268,7 @@ self.blas_func(x,y,n=3,incx=4,incy=2) assert_array_equal(desired_x,x[::4]) assert_array_equal(desired_y,y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -271,7 +277,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -282,21 +288,21 @@ assert(0) try: - class TestSswap(BaseSwap): + class TestSswap(TestCase, BaseSwap): blas_func = fblas.sswap dtype = float32 except AttributeError: class TestSswap: pass -class TestDswap(BaseSwap): +class TestDswap(TestCase, BaseSwap): blas_func = fblas.dswap dtype = float64 try: - class TestCswap(BaseSwap): + class TestCswap(TestCase, BaseSwap): blas_func = fblas.cswap dtype = complex64 except AttributeError: class TestCswap: pass -class TestZswap(BaseSwap): +class TestZswap(TestCase, BaseSwap): blas_func = fblas.zswap dtype = complex128 @@ -304,7 +310,8 @@ ### Test blas ?gemv ### This will be a mess to test all cases. -class BaseGemv(NumpyTestCase): +class BaseGemv(object): + ''' Mixin class for gemv tests ''' def get_data(self,x_stride=1,y_stride=1): mult = array(1, dtype = self.dtype) if self.dtype in [complex64, complex128]: @@ -316,37 +323,37 @@ x = arange(shape(a)[0]*x_stride,dtype=self.dtype) * mult y = arange(shape(a)[1]*y_stride,dtype=self.dtype) * mult return alpha,beta,a,x,y - def check_simple(self): + def test_simple(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(a,x)+beta*y y = self.blas_func(alpha,a,x,beta,y) assert_array_almost_equal(desired_y,y) - def check_default_beta_y(self): + def test_default_beta_y(self): alpha,beta,a,x,y = self.get_data() desired_y = matrixmultiply(a,x) y = self.blas_func(1,a,x) assert_array_almost_equal(desired_y,y) - def check_simple_transpose(self): + def test_simple_transpose(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(transpose(a),x)+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=1) assert_array_almost_equal(desired_y,y) - def check_simple_transpose_conj(self): + def test_simple_transpose_conj(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(transpose(conjugate(a)),x)+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=2) assert_array_almost_equal(desired_y,y) - def check_x_stride(self): + def test_x_stride(self): alpha,beta,a,x,y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(a,x[::2])+beta*y y = self.blas_func(alpha,a,x,beta,y,incx=2) assert_array_almost_equal(desired_y,y) - def check_x_stride_transpose(self): + def test_x_stride_transpose(self): alpha,beta,a,x,y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(transpose(a),x[::2])+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=1,incx=2) assert_array_almost_equal(desired_y,y) - def check_x_stride_assert(self): + def test_x_stride_assert(self): # What is the use of this test? alpha,beta,a,x,y = self.get_data(x_stride=2) try: @@ -359,19 +366,19 @@ assert(0) except: pass - def check_y_stride(self): + def test_y_stride(self): alpha,beta,a,x,y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(a,x)+beta*y[::2] y = self.blas_func(alpha,a,x,beta,y,incy=2) assert_array_almost_equal(desired_y,y) - def check_y_stride_transpose(self): + def test_y_stride_transpose(self): alpha,beta,a,x,y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(transpose(a),x)+beta*y[::2] y = self.blas_func(alpha,a,x,beta,y,trans=1,incy=2) assert_array_almost_equal(desired_y,y) - def check_y_stride_assert(self): + def test_y_stride_assert(self): # What is the use of this test? alpha,beta,a,x,y = self.get_data(y_stride=2) try: @@ -386,21 +393,21 @@ pass try: - class TestSgemv(BaseGemv): + class TestSgemv(TestCase, BaseGemv): blas_func = fblas.sgemv dtype = float32 except AttributeError: class TestSgemv: pass -class TestDgemv(BaseGemv): +class TestDgemv(TestCase, BaseGemv): blas_func = fblas.dgemv dtype = float64 try: - class TestCgemv(BaseGemv): + class TestCgemv(TestCase, BaseGemv): blas_func = fblas.cgemv dtype = complex64 except AttributeError: class TestCgemv: pass -class TestZgemv(BaseGemv): +class TestZgemv(TestCase, BaseGemv): blas_func = fblas.zgemv dtype = complex128 @@ -409,7 +416,7 @@ ### Test blas ?ger ### This will be a mess to test all cases. -class BaseGer(NumpyTestCase): +class BaseGer(TestCase): def get_data(self,x_stride=1,y_stride=1): from numpy.random import normal alpha = array(1., dtype = self.dtype) @@ -417,31 +424,31 @@ x = arange(shape(a)[0]*x_stride,dtype=self.dtype) y = arange(shape(a)[1]*y_stride,dtype=self.dtype) return alpha,a,x,y - def check_simple(self): + def test_simple(self): alpha,a,x,y = self.get_data() # tranpose takes care of Fortran vs. C(and Python) memory layout desired_a = alpha*transpose(x[:,newaxis]*y) + a self.blas_func(x,y,a) assert_array_almost_equal(desired_a,a) - def check_x_stride(self): + def test_x_stride(self): alpha,a,x,y = self.get_data(x_stride=2) desired_a = alpha*transpose(x[::2,newaxis]*y) + a self.blas_func(x,y,a,incx=2) assert_array_almost_equal(desired_a,a) - def check_x_stride_assert(self): + def test_x_stride_assert(self): alpha,a,x,y = self.get_data(x_stride=2) try: self.blas_func(x,y,a,incx=3) assert(0) except: pass - def check_y_stride(self): + def test_y_stride(self): alpha,a,x,y = self.get_data(y_stride=2) desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a self.blas_func(x,y,a,incy=2) assert_array_almost_equal(desired_a,a) - def check_y_stride_assert(self): + def test_y_stride_assert(self): alpha,a,x,y = self.get_data(y_stride=2) try: self.blas_func(a,x,y,incy=3) @@ -472,7 +479,7 @@ y = normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype) y = y + y * array(1j, dtype = self.dtype) return alpha,a,x,y - def check_simple(self): + def test_simple(self): alpha,a,x,y = self.get_data() # tranpose takes care of Fortran vs. C(and Python) memory layout a = a * array(0.,dtype = self.dtype) @@ -482,12 +489,12 @@ fblas.cgeru(x,y,a,alpha = alpha) assert_array_almost_equal(desired_a,a) - #def check_x_stride(self): + #def test_x_stride(self): # alpha,a,x,y = self.get_data(x_stride=2) # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a # self.blas_func(x,y,a,incx=2) # assert_array_almost_equal(desired_a,a) - #def check_y_stride(self): + #def test_y_stride(self): # alpha,a,x,y = self.get_data(y_stride=2) # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a # self.blas_func(x,y,a,incy=2) @@ -518,4 +525,4 @@ """ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/linalg/tests/test_iterative.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_iterative.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/linalg/tests/test_iterative.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -13,15 +13,14 @@ python tests/test_iterative.py [] """ +import sys + from numpy import zeros, dot, diag, ones -from numpy.testing import * +from scipy.testing import * from numpy.random import rand #from numpy import arange, add, array, dot, zeros, identity, conjugate, transpose -import sys -set_package_path() -from linalg import iterative, norm, cg, cgs, bicg, bicgstab, gmres, qmr -restore_path() +from scipy.linalg import iterative, norm, cg, cgs, bicg, bicgstab, gmres, qmr def callback(x): @@ -29,9 +28,9 @@ res = b-dot(A,x) #print "||A.x - b|| = " + str(norm(dot(A,x)-b)) -class TestIterativeSolvers(NumpyTestCase): +class TestIterativeSolvers(TestCase): def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.setUp() def setUp (self): global A, b @@ -44,41 +43,41 @@ self.b = rand(n) b = self.b - def check_cg(self): + def test_cg(self): bx0 = self.x0.copy() x, info = cg(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_bicg(self): + def test_bicg(self): bx0 = self.x0.copy() x, info = bicg(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_cgs(self): + def test_cgs(self): bx0 = self.x0.copy() x, info = cgs(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_bicgstab(self): + def test_bicgstab(self): bx0 = self.x0.copy() x, info = bicgstab(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_gmres(self): + def test_gmres(self): bx0 = self.x0.copy() x, info = gmres(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_qmr(self): + def test_qmr(self): bx0 = self.x0.copy() x, info = qmr(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/linalg/tests/test_lapack.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_lapack.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/linalg/tests/test_lapack.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -3,26 +3,17 @@ # Created by: Pearu Peterson, September 2002 # -__usage__ = """ -Build linalg: - python setup_linalg.py build -Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' -Run tests if linalg is not installed: - python tests/test_lapack.py [] -""" import sys -from numpy.testing import * +from scipy.testing import * from numpy import ones -set_package_path() -from linalg import flapack -from linalg import clapack -restore_path() -class TestFlapackSimple(NumpyTestCase): +from scipy.linalg import flapack, clapack - def check_gebal(self): + +class TestFlapackSimple(TestCase): + + def test_gebal(self): a = [[1,2,3],[4,5,6],[7,8,9]] a1 = [[1,0,0,3e-4], [4,0,0,2e-3], @@ -42,7 +33,7 @@ #print a1 #print ba,lo,hi,pivscale - def check_gehrd(self): + def test_gehrd(self): a = [[-149, -50,-154], [ 537, 180, 546], [ -27, -9, -25]] @@ -52,9 +43,9 @@ ht,tau,info = f(a) assert not info,`info` -class TestLapack(NumpyTestCase): +class TestLapack(TestCase): - def check_flapack(self): + def test_flapack(self): if hasattr(flapack,'empty_module'): print """ **************************************************************** @@ -63,7 +54,7 @@ See scipy/INSTALL.txt for troubleshooting. **************************************************************** """ - def check_clapack(self): + def test_clapack(self): if hasattr(clapack,'empty_module'): print """ **************************************************************** @@ -77,4 +68,4 @@ """ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/linalg/tests/test_matfuncs.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_matfuncs.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/linalg/tests/test_matfuncs.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -5,29 +5,21 @@ """ Test functions for linalg.matfuncs module """ -__usage__ = """ -Build linalg: - python setup_linalg.py build -Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' -Run tests if linalg is not installed: - python tests/test_matfuncs.py [] -""" -from numpy import array, identity - import sys -from numpy.testing import * -set_package_path() + import numpy -from numpy import dot,sqrt -import linalg -from linalg import signm,logm,funm, sqrtm, expm, expm2, expm3 -restore_path() +from numpy import array, identity, dot, sqrt -class TestSignM(NumpyTestCase): +from scipy.testing import * - def check_nils(self): +import scipy.linalg +from scipy.linalg import signm,logm,funm, sqrtm, expm, expm2, expm3 + + +class TestSignM(TestCase): + + def test_nils(self): a = array([[ 29.2, -24.2, 69.5, 49.8, 7. ], [ -9.2, 5.2, -18. , -16.8, -2. ], [-10. , 6. , -20. , -18. , -2. ], @@ -41,12 +33,12 @@ r = signm(a) assert_array_almost_equal(r,cr) - def check_defective1(self): + def test_defective1(self): a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]]) r = signm(a) #XXX: what would be the correct result? - def check_defective2(self): + def test_defective2(self): a = array(( [29.2,-24.2,69.5,49.8,7.0], [-9.2,5.2,-18.0,-16.8,-2.0], @@ -56,7 +48,7 @@ r = signm(a) #XXX: what would be the correct result? - def check_defective3(self): + def test_defective3(self): a = array([[ -2., 25., 0., 0., 0., 0., 0.], [ 0., -3., 10., 3., 3., 3., 0.], [ 0., 0., 2., 15., 3., 3., 0.], @@ -67,9 +59,9 @@ r = signm(a) #XXX: what would be the correct result? -class TestLogM(NumpyTestCase): +class TestLogM(TestCase): - def check_nils(self): + def test_nils(self): a = array([[ -2., 25., 0., 0., 0., 0., 0.], [ 0., -3., 10., 3., 3., 3., 0.], [ 0., 0., 2., 15., 3., 3., 0.], @@ -81,8 +73,8 @@ logm(m) -class TestSqrtM(NumpyTestCase): - def check_bad(self): +class TestSqrtM(TestCase): + def test_bad(self): # See http://www.maths.man.ac.uk/~nareports/narep336.ps.gz e = 2**-5 se = sqrt(e) @@ -98,12 +90,12 @@ esa = sqrtm(a) assert_array_almost_equal(dot(esa,esa),a) -class TestExpM(NumpyTestCase): - def check_zero(self): +class TestExpM(TestCase): + def test_zero(self): a = array([[0.,0],[0,0]]) assert_array_almost_equal(expm(a),[[1,0],[0,1]]) assert_array_almost_equal(expm2(a),[[1,0],[0,1]]) assert_array_almost_equal(expm3(a),[[1,0],[0,1]]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -49,6 +49,7 @@ def test_big(self,level=5): print 'Big, slow test' + def test_simplefunction(): """A simple test function.""" assert True Modified: branches/testing_cleanup/scipy/sandbox/timeseries/dates.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/dates.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/sandbox/timeseries/dates.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -617,9 +617,26 @@ def date_array(dlist=None, start_date=None, end_date=None, length=None, freq=None): - """Constructs a DateArray from: - - a starting date and either an ending date or a given length. - - a list of dates. + """Factory function for constructing a DateArray + +*Parameters*: + dlist : {list of dates or DateArray} (optional) + may be a list of dates, integer representations of dates for a given + frequency, datetime objects, or an existing DateArray. If specifying + a list of dates, you must also specify the `freq` parameter. + + start_date : {Date} (optional) + if you want a continuous DateArray, specify a start_date and either an + `end_date` or a `length`. Frequency of the resulting DateArray will be + automatically determined based on the frequency of this parameter. + + end_date : {Date} (optional) + last date in resulting DateArray. Specify this parameter or `length` + in combination with `start_date` for a continuous DateArray. + + length : {int} (optional) + the length of the resulting DateArray. Specify this parameter or + `end_date` in combination with `start_date` for a continuous DateArray. """ freq = check_freq(freq) # Case #1: we have a list ................... Modified: branches/testing_cleanup/scipy/sparse/construct.py =================================================================== --- branches/testing_cleanup/scipy/sparse/construct.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/sparse/construct.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -12,6 +12,7 @@ from csr import csr_matrix, isspmatrix_csr from csc import csc_matrix, isspmatrix_csc +from bsr import bsr_matrix from coo import coo_matrix from dok import dok_matrix from lil import lil_matrix @@ -96,36 +97,56 @@ """ #TODO optimize for small dense B and CSR A - A,B = coo_matrix(A),coo_matrix(B) - output_shape = (A.shape[0]*B.shape[0],A.shape[1]*B.shape[1]) + B = coo_matrix(B) - if A.nnz == 0 or B.nnz == 0: - # kronecker product is the zero matrix - return coo_matrix( output_shape ) + + if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: + #B is fairly dense, use BSR + A = csr_matrix(A,copy=True) + + output_shape = (A.shape[0]*B.shape[0],A.shape[1]*B.shape[1]) - # expand entries of a into blocks - row = A.row.repeat(B.nnz) - col = A.col.repeat(B.nnz) - data = A.data.repeat(B.nnz) + if A.nnz == 0 or B.nnz == 0: + # kronecker product is the zero matrix + return coo_matrix( output_shape ) + + B = B.toarray() + data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1]) + data = data * B + + return bsr_matrix((data,A.indices,A.indptr),shape=output_shape) + else: + #use COO + A = coo_matrix(A) + output_shape = (A.shape[0]*B.shape[0],A.shape[1]*B.shape[1]) - row *= B.shape[0] - col *= B.shape[1] + if A.nnz == 0 or B.nnz == 0: + # kronecker product is the zero matrix + return coo_matrix( output_shape ) - # increment block indices - row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) - row += B.row - col += B.col - row,col = row.reshape(-1),col.reshape(-1) + # expand entries of a into blocks + row = A.row.repeat(B.nnz) + col = A.col.repeat(B.nnz) + data = A.data.repeat(B.nnz) - # compute block entries - data = data.reshape(-1,B.nnz) * B.data - data = data.reshape(-1) + row *= B.shape[0] + col *= B.shape[1] - return coo_matrix((data,(row,col)), shape=output_shape).asformat(format) + # increment block indices + row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) + row += B.row + col += B.col + row,col = row.reshape(-1),col.reshape(-1) + # compute block entries + data = data.reshape(-1,B.nnz) * B.data + data = data.reshape(-1) + return coo_matrix((data,(row,col)), shape=output_shape).asformat(format) + + def lil_eye((r,c), k=0, dtype='d'): """Generate a lil_matrix of dimensions (r,c) with the k-th diagonal set to 1. Modified: branches/testing_cleanup/scipy/sparse/tests/test_sparse.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_sparse.py 2008-01-01 22:00:03 UTC (rev 3760) +++ branches/testing_cleanup/scipy/sparse/tests/test_sparse.py 2008-01-02 04:07:30 UTC (rev 3761) @@ -77,8 +77,7 @@ vars = dict( [(var,mat.asformat(format)) for (var,name,mat) in matrices ] ) for X,Y in [ ('A','A'),('A','B'),('B','A'),('B','B') ]: x,y = vars[X],vars[Y] - #for op in ['__add__','__sub__','multiply','__div__','__mul__']: - for op in ['__mul__']: + for op in ['__add__','__sub__','multiply','__div__','__mul__']: fn = getattr(x,op) fn(y) #warmup From scipy-svn at scipy.org Wed Jan 2 00:37:21 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 1 Jan 2008 23:37:21 -0600 (CST) Subject: [Scipy-svn] r3762 - in trunk/scipy/io: . matlab Message-ID: <20080102053721.6A80839C019@new.scipy.org> Author: wnbell Date: 2008-01-01 23:37:17 -0600 (Tue, 01 Jan 2008) New Revision: 3762 Modified: trunk/scipy/io/matlab/mio5.py trunk/scipy/io/mmio.py Log: fixed small bug in MATLAB 6 sparse reader updated use of sparse dims parameter Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-01-02 04:07:30 UTC (rev 3761) +++ trunk/scipy/io/matlab/mio5.py 2008-01-02 05:37:17 UTC (rev 3762) @@ -359,19 +359,24 @@ data = self.read_element() ''' From the matlab (TM) API documentation, last found here: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/ - rowind are simply the row indices for all the (res) non-zero + rowind are simply the row indices for all the (nnz) non-zero entries in the sparse array. rowind has nzmax entries, so - may well have more entries than len(res), the actual number - of non-zero entries, but rowind[len(res):] can be discarded + may well have more entries than nnz, the actual number + of non-zero entries, but rowind[nnz:] can be discarded and should be 0. indptr has length (number of columns + 1), and is such that, if D = diff(colind), D[j] gives the number of non-zero entries in column j. Because rowind values are stored in column order, this gives the column corresponding to each rowind ''' + M,N = self.header['dims'] + indptr = indptr[:N+1] + nnz = indptr[-1] + rowind = rowind[:nnz] + data = data[:nnz] if have_sparse: - dims = self.header['dims'] - return scipy.sparse.csc_matrix((data,rowind,indptr), dims) + from scipy.sparse import csc_matrix + return csc_matrix((data,rowind,indptr), shape=(M,N)) else: return (dims, data, rowind, indptr) Modified: trunk/scipy/io/mmio.py =================================================================== --- trunk/scipy/io/mmio.py 2008-01-02 04:07:30 UTC (rev 3761) +++ trunk/scipy/io/mmio.py 2008-01-02 05:37:17 UTC (rev 3762) @@ -430,7 +430,7 @@ V = concatenate((V,od_V)) - a = coo_matrix((V, (I, J)), dims=(rows, cols), dtype=dtype) + a = coo_matrix((V, (I, J)), shape=(rows, cols), dtype=dtype) else: raise NotImplementedError,`format` From scipy-svn at scipy.org Wed Jan 2 00:41:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 1 Jan 2008 23:41:06 -0600 (CST) Subject: [Scipy-svn] r3763 - trunk/scipy/io Message-ID: <20080102054106.F184A39C019@new.scipy.org> Author: wnbell Date: 2008-01-01 23:41:05 -0600 (Tue, 01 Jan 2008) New Revision: 3763 Modified: trunk/scipy/io/mmio.py Log: slight change to mmio sparse writing Modified: trunk/scipy/io/mmio.py =================================================================== --- trunk/scipy/io/mmio.py 2008-01-02 05:37:17 UTC (rev 3762) +++ trunk/scipy/io/mmio.py 2008-01-02 05:41:05 UTC (rev 3763) @@ -546,13 +546,14 @@ if symm != self.SYMMETRY_GENERAL: raise ValueError, 'symmetric matrices incompatible with sparse format' + coo = a.tocoo() # convert to COOrdinate format + # write shape spec - stream.write('%i %i %i\n' % (rows,cols,entries)) + stream.write('%i %i %i\n' % (rows,cols,coo.nnz)) # line template template = '%i %i ' + template - coo = a.tocoo() # convert to COOrdinate format I,J,V = coo.row + 1, coo.col + 1, coo.data # change base 0 -> base 1 if field in (self.FIELD_REAL, self.FIELD_INTEGER): From scipy-svn at scipy.org Wed Jan 2 02:57:35 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 2 Jan 2008 01:57:35 -0600 (CST) Subject: [Scipy-svn] r3764 - in branches/testing_cleanup: . scipy/linsolve/umfpack/tests scipy/maxentropy/tests scipy/misc/tests scipy/odr/tests scipy/optimize/tests scipy/signal/tests scipy/sparse/tests scipy/special/tests scipy/stats/models/tests scipy/stats/tests Message-ID: <20080102075735.C230939C053@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-02 01:54:58 -0600 (Wed, 02 Jan 2008) New Revision: 3764 Modified: branches/testing_cleanup/INSTALL.txt branches/testing_cleanup/scipy/linsolve/umfpack/tests/test_umfpack.py branches/testing_cleanup/scipy/maxentropy/tests/test_maxentropy.py branches/testing_cleanup/scipy/misc/tests/test_pilutil.py branches/testing_cleanup/scipy/odr/tests/test_odr.py branches/testing_cleanup/scipy/optimize/tests/test_cobyla.py branches/testing_cleanup/scipy/optimize/tests/test_nonlin.py branches/testing_cleanup/scipy/optimize/tests/test_optimize.py branches/testing_cleanup/scipy/optimize/tests/test_slsqp.py branches/testing_cleanup/scipy/optimize/tests/test_zeros.py branches/testing_cleanup/scipy/signal/tests/test_signaltools.py branches/testing_cleanup/scipy/signal/tests/test_wavelets.py branches/testing_cleanup/scipy/sparse/tests/test_base.py branches/testing_cleanup/scipy/sparse/tests/test_construct.py branches/testing_cleanup/scipy/sparse/tests/test_sparse.py branches/testing_cleanup/scipy/sparse/tests/test_sputils.py branches/testing_cleanup/scipy/special/tests/test_basic.py branches/testing_cleanup/scipy/special/tests/test_spfun_stats.py branches/testing_cleanup/scipy/stats/models/tests/test_bspline.py branches/testing_cleanup/scipy/stats/models/tests/test_formula.py branches/testing_cleanup/scipy/stats/models/tests/test_glm.py branches/testing_cleanup/scipy/stats/models/tests/test_regression.py branches/testing_cleanup/scipy/stats/models/tests/test_rlm.py branches/testing_cleanup/scipy/stats/models/tests/test_scale.py branches/testing_cleanup/scipy/stats/models/tests/test_utils.py branches/testing_cleanup/scipy/stats/tests/test_distributions.py branches/testing_cleanup/scipy/stats/tests/test_morestats.py branches/testing_cleanup/scipy/stats/tests/test_stats.py Log: Slowly working through, sandbox omitted, stats in progress Modified: branches/testing_cleanup/INSTALL.txt =================================================================== --- branches/testing_cleanup/INSTALL.txt 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/INSTALL.txt 2008-01-02 07:54:58 UTC (rev 3764) @@ -20,7 +20,7 @@ SciPy requires the following software installed: -1) Python__ 2.3.x or newer +1) Python__ 2.4.x or newer Debian packages: python python-dev @@ -32,7 +32,7 @@ __ http://www.python.org -2) NumPy__ 1.0b1 or newer +2) NumPy__ 1.0.5 or newer Debian package: python-numpy Modified: branches/testing_cleanup/scipy/linsolve/umfpack/tests/test_umfpack.py =================================================================== --- branches/testing_cleanup/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -8,20 +8,20 @@ from numpy import transpose, array, arange import random -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy import linsolve, rand, matrix, diag, eye from scipy.sparse import csc_matrix, dok_matrix, spdiags import numpy as nm import scipy.linsolve.umfpack as um -restore_path() -class TestSolvers(NumpyTestCase): + +class TestSolvers(TestCase): """Tests inverting a sparse linear system""" - def check_solve_complex_without_umfpack(self): + def test_solve_complex_without_umfpack(self): """Solve: single precision complex""" linsolve.use_solver( useUmfpack = False ) a = self.a.astype('F') @@ -32,7 +32,7 @@ assert_array_almost_equal(a*x, b) - def check_solve_without_umfpack(self): + def test_solve_without_umfpack(self): """Solve: single precision""" linsolve.use_solver( useUmfpack = False ) a = self.a.astype('f') @@ -43,7 +43,7 @@ assert_array_almost_equal(a*x, b) - def check_solve_complex_umfpack(self): + def test_solve_complex_umfpack(self): """Solve with UMFPACK: double precision complex""" linsolve.use_solver( useUmfpack = True ) a = self.a.astype('D') @@ -53,7 +53,7 @@ #print "Error: ", a*x-b assert_array_almost_equal(a*x, b) - def check_solve_umfpack(self): + def test_solve_umfpack(self): """Solve with UMFPACK: double precision""" linsolve.use_solver( useUmfpack = True ) a = self.a.astype('d') @@ -63,7 +63,7 @@ #print "Error: ", a*x-b assert_array_almost_equal(a*x, b) - def check_solve_sparse_rhs(self): + def test_solve_sparse_rhs(self): """Solve with UMFPACK: double precision, sparse rhs""" linsolve.use_solver( useUmfpack = True ) a = self.a.astype('d') @@ -73,7 +73,7 @@ #print "Error: ", a*x-b assert_array_almost_equal(a*x, self.b) - def check_factorized_umfpack(self): + def test_factorized_umfpack(self): """Prefactorize (with UMFPACK) matrix for solving with multiple rhs""" linsolve.use_solver( useUmfpack = True ) a = self.a.astype('d') @@ -84,7 +84,7 @@ x2 = solve( self.b2 ) assert_array_almost_equal(a*x2, self.b2) - def check_factorized_without_umfpack(self): + def test_factorized_without_umfpack(self): """Prefactorize matrix for solving with multiple rhs""" linsolve.use_solver( useUmfpack = False ) a = self.a.astype('d') @@ -104,10 +104,10 @@ -class TestFactorization(NumpyTestCase): +class TestFactorization(TestCase): """Tests factorizing a sparse linear system""" - def check_complex_lu(self): + def test_complex_lu(self): """Getting factors of complex matrix""" umfpack = um.UmfpackContext("zi") @@ -126,7 +126,7 @@ assert_array_almost_equal(P*R*A*Q,L*U) - def check_real_lu(self): + def test_real_lu(self): """Getting factors of real matrix""" umfpack = um.UmfpackContext("di") @@ -166,4 +166,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/maxentropy/tests/test_maxentropy.py =================================================================== --- branches/testing_cleanup/scipy/maxentropy/tests/test_maxentropy.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/maxentropy/tests/test_maxentropy.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -7,20 +7,15 @@ """ import sys -from numpy.testing import * +from scipy.testing import * from numpy import arange, add, array, dot, zeros, identity, log, exp, ones -set_package_path() from scipy.maxentropy.maxentropy import * -restore_path() -import unittest - - -class TestMaxentropy(NumpyTestCase): +class TestMaxentropy(TestCase): """Test whether logsumexp() function correctly handles large inputs. """ - def check_logsumexp(self, level=1): + def test_logsumexp(self): a = arange(200) desired = log(sum(exp(a))) assert_almost_equal(logsumexp(a), desired) @@ -35,10 +30,10 @@ desired = 10000.0 + log(n) assert_almost_equal(logsumexp(b), desired) - def check_simple(self, level=1): + def test_simple(self): # Write me! pass if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/misc/tests/test_pilutil.py =================================================================== --- branches/testing_cleanup/scipy/misc/tests/test_pilutil.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/misc/tests/test_pilutil.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,16 +1,15 @@ -from numpy.testing import * -set_package_path() +import os.path +import glob +import numpy as N + +from scipy.testing import * + import PIL.Image import scipy.misc.pilutil as pilutil -restore_path() -import glob -import os.path -import numpy as N - datapath = os.path.dirname(__file__) -class TestPILUtil(ParametricTestCase): +class TestPILUtil(TestCase): def test_imresize(self): im = N.random.random((10,20)) for T in N.sctypes['float'] + [float]: @@ -23,19 +22,20 @@ assert_equal(pilutil.bytescale(x),x) assert_equal(pilutil.bytescale(y),[0,127,255]) - def tst_fromimage(self,filename,irange): - img = pilutil.fromimage(PIL.Image.open(filename)) - imin,imax = irange - assert img.min() >= imin - assert img.max() <= imax - def testip_fromimage(self): - data = {'icon.png':(0,255), - 'icon_mono.png':(0,2), - 'icon_mono_flat.png':(0,1)} +def tst_fromimage(filename, irange): + img = pilutil.fromimage(PIL.Image.open(filename)) + imin,imax = irange + assert img.min() >= imin + assert img.max() <= imax + +def test_fromimage(): + ''' Test generator for parametric tests ''' + data = {'icon.png':(0,255), + 'icon_mono.png':(0,2), + 'icon_mono_flat.png':(0,1)} + for fn, irange in data.iteritems(): + yield tst_fromimage, os.path.join(datapath,'data',fn), irange - return ((self.tst_fromimage,os.path.join(datapath,'data',fn),irange) - for fn,irange in data.iteritems()) - if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/odr/tests/test_odr.py =================================================================== --- branches/testing_cleanup/scipy/odr/tests/test_odr.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/odr/tests/test_odr.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -4,11 +4,11 @@ # Scipy imports. import numpy as np from numpy import pi -from numpy.testing import NumpyTest, NumpyTestCase, assert_array_almost_equal +from scipy.testing import * from scipy.odr import Data, Model, ODR, RealData, odr_stop -class TestODR(NumpyTestCase): +class TestODR(TestCase): # Explicit Example @@ -311,6 +311,5 @@ if __name__ == "__main__": - NumpyTest().run() - + unittest.main() #### EOF ####################################################################### Modified: branches/testing_cleanup/scipy/optimize/tests/test_cobyla.py =================================================================== --- branches/testing_cleanup/scipy/optimize/tests/test_cobyla.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/optimize/tests/test_cobyla.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,13 +1,11 @@ +import math -from numpy.testing import * +from scipy.testing import * -set_package_path() -from optimize import cobyla as co -restore_path() -import math +from scipy.optimize import cobyla as co -class TestCobyla(NumpyTestCase): - def check_simple(self, level=1): +class TestCobyla(TestCase): + def test_simple(self, level=1): function = lambda x: x[0]**2 + abs(x[1])**3 con1 = lambda x: x[0]**2 + x[1]**2 - 25 @@ -20,4 +18,4 @@ assert_almost_equal(x, [x0, x1], decimal=5) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/optimize/tests/test_nonlin.py =================================================================== --- branches/testing_cleanup/scipy/optimize/tests/test_nonlin.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/optimize/tests/test_nonlin.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -3,13 +3,12 @@ May 2007 """ -from numpy.testing import * +from scipy.testing import * -set_package_path() from scipy.optimize import nonlin from numpy import matrix, diag -restore_path() + def F(x): def p3(y): return float(y.T*y)*y @@ -25,7 +24,7 @@ return tuple(f.flat) -class TestNonlin(NumpyTestCase): +class TestNonlin(TestCase): """ Test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) @@ -92,4 +91,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/optimize/tests/test_optimize.py =================================================================== --- branches/testing_cleanup/scipy/optimize/tests/test_optimize.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/optimize/tests/test_optimize.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -3,17 +3,16 @@ Nov 2005 """ -from numpy.testing import * +from scipy.testing import * -set_package_path() from scipy import optimize from numpy import array, zeros, float64, dot, log, exp, inf from scipy.optimize.tnc import RCSTRINGS, MSG_NONE -restore_path() + from math import sin, cos, pow -class TestOptimize(NumpyTestCase): +class TestOptimize(TestCase): """ Test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) @@ -44,7 +43,7 @@ return dot(self.F.transpose(), p) - self.K - def check_cg(self): + def test_cg(self): """ conjugate gradient optimization routine """ retval = optimize.fmin_cg(self.func, self.startparams, self.grad, (), \ @@ -58,7 +57,7 @@ assert err < 1e-6 - def check_bfgs(self): + def test_bfgs(self): """ Broyden-Fletcher-Goldfarb-Shanno optimization routine """ retval = optimize.fmin_bfgs(self.func, self.startparams, self.grad, \ @@ -72,7 +71,7 @@ assert err < 1e-6 - def check_powell(self): + def test_powell(self): """ Powell (direction set) optimization routine """ retval = optimize.fmin_powell(self.func, self.startparams, \ @@ -85,7 +84,7 @@ #print "Powell: Difference is: " + str(err) assert err < 1e-6 - def check_neldermead(self): + def test_neldermead(self): """ Nelder-Mead simplex algorithm """ retval = optimize.fmin(self.func, self.startparams, \ @@ -98,7 +97,7 @@ #print "Nelder-Mead: Difference is: " + str(err) assert err < 1e-6 - def check_ncg(self): + def test_ncg(self): """ line-search Newton conjugate gradient optimization routine """ retval = optimize.fmin_ncg(self.func, self.startparams, self.grad, @@ -113,7 +112,7 @@ assert err < 1e-6 - def check_l_bfgs_b(self): + def test_l_bfgs_b(self): """ limited-memory bound-constrained BFGS algorithm """ retval = optimize.fmin_l_bfgs_b(self.func, self.startparams, @@ -143,7 +142,7 @@ -class TestTnc(NumpyTestCase): +class TestTnc(TestCase): """TNC non-linear optimization. These tests are taken from Prof. K. Schittkowski's test examples @@ -244,4 +243,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/optimize/tests/test_slsqp.py =================================================================== --- branches/testing_cleanup/scipy/optimize/tests/test_slsqp.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/optimize/tests/test_slsqp.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,12 +1,11 @@ -from numpy.testing import * +from scipy.testing import * import numpy as np -set_package_path() from scipy.optimize import fmin_slsqp from numpy import matrix, diag -restore_path() -class TestSLSQP(NumpyTestCase): + +class TestSLSQP(TestCase): """Test fmin_slsqp using Example 14.4 from Numerical Methods for Engineers by Steven Chapra and Raymond Canale. This example maximizes the function f(x) = 2*x*y + 2*x - x**2 - 2*y**2, which @@ -87,4 +86,4 @@ assert_array_almost_equal(x,[2,1]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/optimize/tests/test_zeros.py =================================================================== --- branches/testing_cleanup/scipy/optimize/tests/test_zeros.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/optimize/tests/test_zeros.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,11 +1,10 @@ #!/usr/bin/env python -from numpy.testing import * -set_package_path() -from optimize import zeros as cc -restore_path() +from scipy.testing import * +from scipy.optimize import zeros as cc + from math import sin,sqrt,log from random import random @@ -51,8 +50,8 @@ functions = [f2,f3,f4,f5,f6] fstrings = ['f2','f3','f4','f5','f6'] -class TestBasic(NumpyTestCase) : - def run_test(self, method, name): +class TestBasic(TestCase) : + def run_check(self, method, name): a = .5 b = sqrt(3) for function, fname in zip(functions, fstrings): @@ -61,14 +60,14 @@ assert_almost_equal(zero, 1.0, decimal=12, err_msg='method %s, function %s' % (name, fname)) - def check_bisect(self): - self.run_test(cc.bisect, 'bisect') - def check_ridder(self): - self.run_test(cc.ridder, 'ridder') - def check_brentq(self): - self.run_test(cc.brentq, 'brentq') - def check_brenth(self): - self.run_test(cc.brenth, 'brenth') + def test_bisect(self): + self.run_check(cc.bisect, 'bisect') + def test_ridder(self): + self.run_check(cc.ridder, 'ridder') + def test_brentq(self): + self.run_check(cc.brentq, 'brentq') + def test_brenth(self): + self.run_check(cc.brenth, 'brenth') def bench_run(self,level=5): a = .5 @@ -93,4 +92,4 @@ print '\n\n' if __name__ == '__main__' : - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/signal/tests/test_signaltools.py =================================================================== --- branches/testing_cleanup/scipy/signal/tests/test_signaltools.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/signal/tests/test_signaltools.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,34 +1,34 @@ #this program corresponds to special.py -from numpy.testing import * -set_package_path() +from scipy.testing import * + import scipy.signal as signal -restore_path() + from numpy import array, arange -class TestConvolve(NumpyTestCase): - def check_basic(self): +class TestConvolve(TestCase): + def test_basic(self): a = [3,4,5,6,5,4] b = [1,2,3] c = signal.convolve(a,b) assert_array_equal(c,array([3,10,22,28,32,32,23,12])) -class TestMedFilt(NumpyTestCase): - def check_basic(self): +class TestMedFilt(TestCase): + def test_basic(self): f = [[3,4,5],[2,3,4],[1,2,5]] d = signal.medfilt(f) assert_array_equal(d, [[0,3,0],[2,3,3],[0,2,0]]) -class TestWiener(NumpyTestCase): - def check_basic(self): +class TestWiener(TestCase): + def test_basic(self): g = array([[5,6,4,3],[3,5,6,2],[2,3,5,6],[1,6,9,7]],'d') correct = array([[2.16374269,3.2222222222, 2.8888888889, 1.6666666667],[2.666666667, 4.33333333333, 4.44444444444, 2.8888888888],[2.222222222, 4.4444444444, 5.4444444444, 4.801066874837],[1.33333333333, 3.92735042735, 6.0712560386, 5.0404040404]]) h = signal.wiener(g) assert_array_almost_equal(h,correct,decimal=6) -class TestCSpline1DEval(NumpyTestCase): - def check_basic(self): +class TestCSpline1DEval(TestCase): + def test_basic(self): y=array([1,2,3,4,3,2,1,2,3.0]) x=arange(len(y)) dx=x[1]-x[0] @@ -40,10 +40,10 @@ # make sure interpolated values are on knot points assert_array_almost_equal(y2[::10], y, decimal=5) -class TestOrderFilt(NumpyTestCase): - def check_basic(self): +class TestOrderFilt(TestCase): + def test_basic(self): assert_array_equal(signal.order_filter([1,2,3],[1,0,1],1), [2,3,2]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/signal/tests/test_wavelets.py =================================================================== --- branches/testing_cleanup/scipy/signal/tests/test_wavelets.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/signal/tests/test_wavelets.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,19 +1,18 @@ import numpy as N -from numpy.testing import * +from scipy.testing import * -set_package_path() from scipy.signal import wavelets -restore_path() -class TestWavelets(NumpyTestCase): - def check_qmf(self): + +class TestWavelets(TestCase): + def test_qmf(self): assert_array_equal(wavelets.qmf([1,1]),[1,-1]) - def check_daub(self): + def test_daub(self): for i in xrange(1,15): assert_equal(len(wavelets.daub(i)),i*2) - def check_cascade(self): + def test_cascade(self): for J in xrange(1,7): for i in xrange(1,5): lpcoef = wavelets.daub(i) @@ -22,7 +21,7 @@ assert len(x) == len(phi) == len(psi) assert_equal(len(x),(k-1)*2**J) - def check_morlet(self): + def test_morlet(self): x = wavelets.morlet(50,4.1,complete=True) y = wavelets.morlet(50,4.1,complete=False) assert_equal(len(x),len(y)) @@ -32,4 +31,4 @@ assert_equal(x,y) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/sparse/tests/test_base.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_base.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/sparse/tests/test_base.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -18,15 +18,15 @@ asarray, vstack, ndarray, kron import random -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ coo_matrix, lil_matrix, dia_matrix, bsr_matrix, \ extract_diagonal, speye, spkron from scipy.linsolve import splu -restore_path() + #TODO test spmatrix( [[1,2],[3,4]] ) format #TODO check that invalid shape in constructor raises exception #TODO check that spmatrix( ... , copy=X ) is respected @@ -38,11 +38,11 @@ self.dat = matrix([[1,0,0,2],[3,0,1,0],[0,2,0,0]],'d') self.datsp = self.spmatrix(self.dat) - def check_repr(self): + def test_repr(self): """make sure __repr__ works""" repr(self.spmatrix) - def check_empty(self): + def test_empty(self): """Test manipulating empty matrices. Fails in SciPy SVN <= r1768 """ shape = (5, 5) @@ -59,15 +59,15 @@ assert_equal(m.dtype,mytype) assert_equal(m.A.dtype,mytype) - def check_abs(self): + def test_abs(self): A = matrix([[-1, 0, 17],[0, -5, 0],[1, -4, 0],[0,0,0]],'d') assert_equal(abs(A),abs(self.spmatrix(A)).todense()) - def check_neg(self): + def test_neg(self): A = matrix([[-1, 0, 17],[0, -5, 0],[1, -4, 0],[0,0,0]],'d') assert_equal(-A,(-self.spmatrix(A)).todense()) - def check_sum(self): + def test_sum(self): """Does the matrix's sum(,axis=0) method work? """ assert_array_equal(self.dat.sum(), self.datsp.sum()) @@ -75,7 +75,7 @@ assert_array_equal(self.dat.sum(axis=0), self.datsp.sum(axis=0)) assert_array_equal(self.dat.sum(axis=1), self.datsp.sum(axis=1)) - def check_mean(self): + def test_mean(self): """Does the matrix's mean(,axis=0) method work? """ assert_array_equal(self.dat.mean(), self.datsp.mean()) @@ -83,13 +83,13 @@ assert_array_equal(self.dat.mean(axis=0), self.datsp.mean(axis=0)) assert_array_equal(self.dat.mean(axis=1), self.datsp.mean(axis=1)) - def check_fromdense(self): + def test_fromdense(self): A = matrix([[1,0,0],[2,3,4],[0,5,0],[0,0,0]]) assert_array_equal(self.spmatrix(A).todense(),A) assert_array_equal(self.spmatrix(A.A).todense(),A) assert_array_equal(self.spmatrix(A.tolist()).todense(),A) - def check_todense(self): + def test_todense(self): chk = self.datsp.todense() assert_array_equal(chk,self.dat) a = matrix([1.,2.,3.]) @@ -101,7 +101,7 @@ check2 = self.datsp.todense() * b assert_array_equal(dense_dot_dense, check2) - def check_toarray(self): + def test_toarray(self): dat = asarray(self.dat) chk = self.datsp.toarray() assert_array_equal(chk, dat) @@ -115,36 +115,36 @@ assert_array_equal(dense_dot_dense, check2) - def check_mul_scalar(self): + def test_mul_scalar(self): assert_array_equal(self.dat*2,(self.datsp*2).todense()) assert_array_equal(self.dat*17.3,(self.datsp*17.3).todense()) - def check_rmul_scalar(self): + def test_rmul_scalar(self): assert_array_equal(2*self.dat,(2*self.datsp).todense()) assert_array_equal(17.3*self.dat,(17.3*self.datsp).todense()) - def check_add(self): + def test_add(self): a = self.dat.copy() a[0,2] = 2.0 b = self.datsp c = b + a assert_array_equal(c,[[2,0,2,4],[6,0,2,0],[0,4,0,0]]) - def check_radd(self): + def test_radd(self): a = self.dat.copy() a[0,2] = 2.0 b = self.datsp c = a + b assert_array_equal(c,[[2,0,2,4],[6,0,2,0],[0,4,0,0]]) - def check_sub(self): + def test_sub(self): assert_array_equal((self.datsp - self.datsp).todense(),[[0,0,0,0],[0,0,0,0],[0,0,0,0]]) A = self.spmatrix(matrix([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],'d')) assert_array_equal((self.datsp - A).todense(),self.dat - A.todense()) assert_array_equal((A - self.datsp).todense(),A.todense() - self.dat) - def check_rsub(self): + def test_rsub(self): assert_array_equal((self.dat - self.datsp),[[0,0,0,0],[0,0,0,0],[0,0,0,0]]) assert_array_equal((self.datsp - self.dat),[[0,0,0,0],[0,0,0,0],[0,0,0,0]]) @@ -154,14 +154,14 @@ assert_array_equal(A.todense() - self.datsp,A.todense() - self.dat) assert_array_equal(self.datsp - A.todense(),self.dat - A.todense()) - def check_elmul(self): + def test_elmul(self): temp = self.dat.copy() temp[0,2] = 2.0 temp = self.spmatrix(temp) c = temp.multiply(self.datsp) assert_array_equal(c.todense(),[[1,0,0,4],[9,0,1,0],[0,4,0,0]]) - def check_eldiv(self): + def test_eldiv(self): expected = [[1,0,0,1],[1,0,1,0],[0,1,0,0]] assert_array_equal((self.datsp / self.datsp).todense(),expected) @@ -169,7 +169,7 @@ res = matrix([[1,0,0,0.5],[-3,0,numpy.inf,0],[0,0.25,0,0]],'d') assert_array_equal((self.datsp / denom).todense(),res) - def check_pow(self): + def test_pow(self): A = matrix([[1,0,2,0],[0,3,4,0],[0,5,0,0],[0,6,7,8]]) B = self.spmatrix( A ) @@ -185,13 +185,13 @@ self.assertRaises( Exception, B.__pow__, 1 ) - def check_rmatvec(self): + def test_rmatvec(self): M = self.spmatrix(matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])) assert_array_almost_equal([1,2,3,4]*M, dot([1,2,3,4], M.toarray())) row = matrix([[1,2,3,4]]) assert_array_almost_equal(row*M, row*M.todense()) - def check_matvec(self): + def test_matvec(self): M = self.spmatrix(matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])) col = matrix([1,2,3]).T assert_array_almost_equal(M * col, M.todense() * col) @@ -237,7 +237,7 @@ # Currently M.matvec(asarray(col)) is rank-1, whereas M.matvec(col) # is rank-2. Is this desirable? - def check_matmat_sparse(self): + def test_matmat_sparse(self): a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) a2 = array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) b = matrix([[0,1],[1,0],[0,2]],'d') @@ -288,7 +288,7 @@ assert_array_almost_equal(B.todense(), A.todense() * A.T.todense()) assert_array_almost_equal(B.todense(), A.todense() * A.todense().T) - def check_matmat_dense(self): + def test_matmat_dense(self): a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) asp = self.spmatrix(a) @@ -301,7 +301,7 @@ assert_equal( result.shape, (4,2) ) assert_equal( result, dot(a,b) ) - def check_conversions(self): + def test_conversions(self): A = spkron([[1,0,1],[0,1,1],[1,0,0]], [[1,1],[0,1]] ) D = A.todense() A = self.spmatrix(A) @@ -321,11 +321,11 @@ - def check_todia(self): + def test_todia(self): #TODO, add and test .todia(maxdiags) pass - def check_tocompressedblock(self): + def test_tocompressedblock(self): x = array([[1,0,2,0],[0,0,0,0],[0,0,4,5]]) y = array([[0,1,2],[3,0,5]]) A = kron(x,y) @@ -338,7 +338,7 @@ assert_equal( fn(blocksize=(X,Y)).todense(), A) - def check_transpose(self): + def test_transpose(self): a = self.datsp.transpose() b = self.dat.transpose() assert_array_equal(a.todense(), b) @@ -347,7 +347,7 @@ assert_array_equal( self.spmatrix((3,4)).T.todense(), zeros((4,3)) ) - def check_add_dense(self): + def test_add_dense(self): """ Check whether adding a dense matrix to a sparse matrix works """ sum1 = self.dat + self.datsp @@ -355,7 +355,7 @@ sum2 = self.datsp + self.dat assert_array_equal(sum2, 2*self.dat) - def check_sub_dense(self): + def test_sub_dense(self): """ Check whether adding a dense matrix to a sparse matrix works """ sum1 = 3*self.dat - self.datsp @@ -364,7 +364,7 @@ assert_array_equal(sum2, 2*self.dat) - def check_copy(self): + def test_copy(self): """ Check whether the copy=True and copy=False keywords work """ A = self.datsp @@ -394,20 +394,20 @@ # Eventually we'd like to allow matrix products between dense # and sparse matrices using the normal dot() function: - #def check_dense_dot_sparse(self): + #def test_dense_dot_sparse(self): # a = array([1.,2.,3.]) # dense_dot_dense = dot(a, self.dat) # dense_dot_sparse = dot(a, self.datsp) # assert_array_equal(dense_dot_dense, dense_dot_sparse) - #def check_sparse_dot_dense(self): + #def test_sparse_dot_dense(self): # b = array([1.,2.,3.,4.]) # dense_dot_dense = dot(self.dat, b) # dense_dot_sparse = dot(self.datsp, b) # assert_array_equal(dense_dot_dense, dense_dot_sparse) - def check_extract_diagonal(self): + def test_extract_diagonal(self): """ Test extraction of main diagonal from sparse matrices """ @@ -422,7 +422,7 @@ class _TestInplaceArithmetic: - def check_imul_scalar(self): + def test_imul_scalar(self): a = self.datsp.copy() a *= 2 assert_array_equal(self.dat*2,a.todense()) @@ -431,7 +431,7 @@ a *= 17.3 assert_array_equal(self.dat*17.3,a.todense()) - def check_idiv_scalar(self): + def test_idiv_scalar(self): a = self.datsp.copy() a /= 2 assert_array_equal(self.dat/2,a.todense()) @@ -443,7 +443,7 @@ class _TestMatvecOutput: """test using the matvec() output parameter""" - def check_matvec_output(self): + def test_matvec_output(self): #flat array x = array([1.25, -6.5, 0.125, -3.75],dtype='d') y = zeros(3,dtype='d') @@ -481,7 +481,7 @@ assert_equal((self.datsp*x).dtype,y.dtype) class _TestGetSet: - def check_setelement(self): + def test_setelement(self): a = self.spmatrix((3,4)) a[1,2] = 4.0 a[0,1] = 3 @@ -490,14 +490,14 @@ a[-1,-2] = 7 assert_array_equal(a.todense(),[[0,3,0,8],[0,0,4,0],[2,0,7,0]]) - def check_getelement(self): + def test_getelement(self): assert_equal(self.datsp[0,0],1) assert_equal(self.datsp[0,1],0) assert_equal(self.datsp[1,0],3) assert_equal(self.datsp[2,1],2) class _TestSolve: - def check_solve(self): + def test_solve(self): """ Test whether the lu_solve command segfaults, as reported by Nils Wagner for a 64-bit machine, 02 March 2005 (EJS) """ @@ -521,7 +521,7 @@ """Tests horizontal slicing (e.g. [0, :]). Tests for individual sparse matrix types that implement this should derive from this class. """ - def check_get_horiz_slice(self): + def test_get_horiz_slice(self): """Test for new slice functionality (EJS)""" B = asmatrix(arange(50.).reshape(5,10)) A = self.spmatrix(B) @@ -555,7 +555,7 @@ """Tests vertical slicing (e.g. [:, 0]). Tests for individual sparse matrix types that implement this should derive from this class. """ - def check_get_vert_slice(self): + def test_get_vert_slice(self): """Test for new slice functionality (EJS)""" B = asmatrix(arange(50.).reshape(5,10)) A = self.spmatrix(B) @@ -592,7 +592,7 @@ individual sparse matrix types that implement this should derive from this class. """ - def check_get_slices(self): + def test_get_slices(self): B = asmatrix(arange(50.).reshape(5,10)) A = self.spmatrix(B) assert_array_equal(B[2:5,0:3], A[2:5,0:3].todense()) @@ -610,13 +610,13 @@ that implement these features should derive from this class. """ # This isn't supported by any matrix objects yet: - def check_sequence_indexing(self): + def test_sequence_indexing(self): B = asmatrix(arange(50.).reshape(5,10)) A = self.spmatrix(B) assert_array_equal(B[(1,2),(3,4)], A[(1,2),(3,4)].todense()) assert_array_equal(B[(1,2,3),(3,4,5)], A[(1,2,3),(3,4,5)].todense()) - def check_fancy_indexing(self): + def test_fancy_indexing(self): """Test for new indexing functionality""" B = ones((5,10), float) A = dok_matrix(B) @@ -658,7 +658,7 @@ self.dtypes = ['int8','uint8','int16','int32','int64', 'float32','float64','complex64','complex128'] - def check_conversion(self): + def test_conversion(self): self.arith_init() #check whether dtype and value is preserved in conversion @@ -673,7 +673,7 @@ assert_array_equal(A,Asp.todense()) assert_array_equal(B,Bsp.todense()) - def check_add_sub(self): + def test_add_sub(self): self.arith_init() #basic tests @@ -707,7 +707,7 @@ assert_array_equal(D1,A - Bsp) #check dense - sparse - def check_mu(self): + def test_mu(self): self.arith_init() #basic tests @@ -732,10 +732,10 @@ class TestCSR(_TestCommon, _TestGetSet, _TestSolve, _TestInplaceArithmetic, _TestArithmetic, _TestMatvecOutput, _TestHorizSlicing, _TestVertSlicing, _TestBothSlicing, - NumpyTestCase): + TestCase): spmatrix = csr_matrix - def check_constructor1(self): + def test_constructor1(self): b = matrix([[0,4,0], [3,0,0], [0,2,0]],'d') @@ -747,7 +747,7 @@ assert_equal(bsp.getformat(),'csr') assert_array_equal(bsp.todense(),b) - def check_constructor2(self): + def test_constructor2(self): b = zeros((6,6),'d') b[3,4] = 5 bsp = csr_matrix(b) @@ -756,7 +756,7 @@ assert_array_equal(bsp.indptr,[0,0,0,0,1,1,1]) assert_array_almost_equal(bsp.todense(),b) - def check_constructor3(self): + def test_constructor3(self): b = matrix([[1,0], [0,2], [3,0]],'d') @@ -767,7 +767,7 @@ assert_array_almost_equal(bsp.todense(),b) ### currently disabled -## def check_constructor4(self): +## def test_constructor4(self): ## """try using int64 indices""" ## data = arange( 6 ) + 1 ## col = array( [1, 2, 1, 0, 0, 2], dtype='int64' ) @@ -783,7 +783,7 @@ ## assert_equal(a.indices.dtype,numpy.dtype('int64')) ## assert_array_equal(a.todense(),b) - def check_constructor4(self): + def test_constructor4(self): """using (data, ij) format""" row = numpy.array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) col = numpy.array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) @@ -794,7 +794,7 @@ csr = csr_matrix((data,ij),(4,3)) assert_array_equal(arange(12).reshape(4,3),csr.todense()) - def check_constructor5(self): + def test_constructor5(self): """infer dimensions from arrays""" indptr = array([0,1,3,3]) indices = array([0,5,1,2]) @@ -803,7 +803,7 @@ assert_array_equal(csr.shape,(3,6)) - def check_sort_indices(self): + def test_sort_indices(self): data = arange( 5 ) indices = array( [7, 2, 1, 5, 4] ) indptr = array( [0, 3, 5] ) @@ -813,7 +813,7 @@ assert_array_equal(asp.indices,[1, 2, 7, 4, 5]) assert_array_equal(asp.todense(),bsp.todense()) - def check_get_submatrix(self): + def test_get_submatrix(self): a = csr_matrix( array([[1,2,3,4],[1,2,3,5],[0,2,0,1]]) ) i0 = slice( 0, 2 ) i1 = ( 1, 3 ) @@ -829,10 +829,10 @@ class TestCSC(_TestCommon, _TestGetSet, _TestSolve, _TestInplaceArithmetic, _TestArithmetic, _TestMatvecOutput, _TestHorizSlicing, _TestVertSlicing, _TestBothSlicing, - NumpyTestCase): + TestCase): spmatrix = csc_matrix - def check_constructor1(self): + def test_constructor1(self): b = matrix([[1,0,0,0],[0,0,1,0],[0,2,0,3]],'d') bsp = csc_matrix(b) assert_array_almost_equal(bsp.data,[1,2,1,3]) @@ -842,7 +842,7 @@ assert_equal(bsp.shape,b.shape) assert_equal(bsp.getformat(),'csc') - def check_constructor2(self): + def test_constructor2(self): b = zeros((6,6),'d') b[2,4] = 5 bsp = csc_matrix(b) @@ -850,14 +850,14 @@ assert_array_equal(bsp.indices,[2]) assert_array_equal(bsp.indptr,[0,0,0,0,0,1,1]) - def check_constructor3(self): + def test_constructor3(self): b = matrix([[1,0],[0,0],[0,2]],'d') bsp = csc_matrix(b) assert_array_almost_equal(bsp.data,[1,2]) assert_array_equal(bsp.indices,[0,2]) assert_array_equal(bsp.indptr,[0,1,2]) - def check_constructor4(self): + def test_constructor4(self): """using (data, ij) format""" row = numpy.array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) col = numpy.array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) @@ -868,7 +868,7 @@ csc = csc_matrix((data,ij),(4,3)) assert_array_equal(arange(12).reshape(4,3),csc.todense()) - def check_constructor5(self): + def test_constructor5(self): """infer dimensions from arrays""" indptr = array([0,1,3,3]) indices = array([0,5,1,2]) @@ -876,7 +876,7 @@ csc = csc_matrix((data, indices, indptr)) assert_array_equal(csc.shape,(6,3)) - def check_sort_indices(self): + def test_sort_indices(self): data = arange( 5 ) row = array( [7, 2, 1, 5, 4] ) ptr = [0, 3, 5] @@ -886,7 +886,7 @@ assert_array_equal(asp.indices,[1, 2, 7, 4, 5]) assert_array_equal(asp.todense(),bsp.todense()) - def check_get_submatrix(self): + def test_get_submatrix(self): a = csc_matrix( array([[1,2,3,4],[1,2,3,5],[0,2,0,1]]) ) i0 = slice( 0, 2 ) i1 = ( 1, 3 ) @@ -899,10 +899,10 @@ assert_equal(b.shape, (2,2)) assert_equal( ab, aa[i0,i1[0]:i1[1]] ) -class TestDOK(_TestCommon, _TestGetSet, _TestSolve, NumpyTestCase): +class TestDOK(_TestCommon, _TestGetSet, _TestSolve, TestCase): spmatrix = dok_matrix - def check_mult(self): + def test_mult(self): A = dok_matrix((10,10)) A[0,3] = 10 A[5,6] = 20 @@ -910,7 +910,7 @@ E = A*A.H assert_array_equal(D.A, E.A) - def check_add(self): + def test_add(self): A = dok_matrix((3,2)) A[0,1] = -10 A[2,0] = 20 @@ -918,7 +918,7 @@ B = matrix([[10, 0], [10, 10], [30, 10]]) assert_array_equal(A.todense(), B) - def check_convert(self): + def test_convert(self): """Test provided by Andrew Straw. Fails in SciPy <= r1477. """ (m, n) = (6, 7) @@ -950,7 +950,7 @@ csr=b.tocsr() assert_array_equal( csr.toarray()[m-1,:], zeros(n,)) - def check_set_slice(self): + def test_set_slice(self): """Test for slice functionality (EJS)""" A = dok_matrix((5,10)) B = zeros((5,10), float) @@ -1009,7 +1009,7 @@ class TestLIL( _TestCommon, _TestHorizSlicing, _TestVertSlicing, _TestBothSlicing, _TestGetSet, _TestSolve, _TestArithmetic, _TestInplaceArithmetic, - NumpyTestCase): + TestCase): spmatrix = lil_matrix B = lil_matrix((4,3)) @@ -1018,7 +1018,7 @@ B[2,1] = 3 B[3,0] = 10 - def check_dot(self): + def test_dot(self): A = matrix(zeros((10,10))) A[0,3] = 10 A[5,6] = 20 @@ -1029,7 +1029,7 @@ assert_array_equal(A * A.T, (B * B.T).todense()) assert_array_equal(A * A.H, (B * B.H).todense()) - def check_scalar_mul(self): + def test_scalar_mul(self): x = lil_matrix((3,3)) x[0,0] = 2 @@ -1039,7 +1039,7 @@ x = x*0 assert_equal(x[0,0],0) - def check_reshape(self): + def test_reshape(self): x = lil_matrix((4,3)) x[0,0] = 1 x[2,1] = 3 @@ -1050,7 +1050,7 @@ assert_array_equal(x.reshape(s).todense(), x.todense().reshape(s)) - def check_lil_lil_assignment(self): + def test_lil_lil_assignment(self): """ Tests whether a row of one lil_matrix can be assigned to another. """ @@ -1078,7 +1078,7 @@ return [(self.tst_inplace_op,op,B,other,result) for op,(other,result) in data.iteritems()] - def check_lil_slice_assignment(self): + def test_lil_slice_assignment(self): B = lil_matrix((4,3)) B[0,0] = 5 B[1,2] = 3 @@ -1096,7 +1096,7 @@ B[:2,:2] = csc_matrix(array(block)) assert_array_equal(B.todense()[:2,:2],block) - def check_lil_sequence_assignement(self): + def test_lil_sequence_assignement(self): A = lil_matrix((4,3)) B = speye(3,4,format='lil') @@ -1109,13 +1109,13 @@ A[2,i2] = B[i2,2] assert_array_equal(A.todense(),B.T.todense()) - def check_lil_iteration(self): + def test_lil_iteration(self): row_data = [[1,2,3],[4,5,6]] B = lil_matrix(array(row_data)) for r,row in enumerate(B): assert_array_equal(row.todense(),array(row_data[r],ndmin=2)) - def check_lil_from_csr(self): + def test_lil_from_csr(self): """ Tests whether a lil_matrix can be constructed from a csr_matrix. """ @@ -1129,7 +1129,7 @@ D = lil_matrix(C) assert_array_equal(C.A, D.A) - def check_point_wise_multiply(self): + def test_point_wise_multiply(self): l = lil_matrix((4,3)) l[0,0] = 1 l[1,1] = 2 @@ -1154,9 +1154,9 @@ -class TestCOO(_TestCommon, NumpyTestCase): +class TestCOO(_TestCommon, TestCase): spmatrix = coo_matrix - def check_constructor1(self): + def test_constructor1(self): """unsorted triplet format""" row = numpy.array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) col = numpy.array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) @@ -1167,7 +1167,7 @@ assert_array_equal(arange(12).reshape(4,3),coo.todense()) - def check_constructor2(self): + def test_constructor2(self): """unsorted triplet format with duplicates (which are summed)""" row = numpy.array([0,1,2,2,2,2,0,0,2,2]) col = numpy.array([0,2,0,2,1,1,1,0,0,2]) @@ -1178,7 +1178,7 @@ assert_array_equal(mat,coo.todense()) - def check_constructor3(self): + def test_constructor3(self): """empty matrix""" coo = coo_matrix( (4,3) ) @@ -1188,7 +1188,7 @@ assert_array_equal(coo.data,[]) assert_array_equal(coo.todense(),zeros((4,3))) - def check_constructor4(self): + def test_constructor4(self): """from dense matrix""" mat = numpy.array([[0,1,0,0], [7,0,3,0], @@ -1202,19 +1202,19 @@ assert_array_equal(coo.todense(),mat.reshape(1,-1)) -class TestDIA(_TestCommon, _TestArithmetic, NumpyTestCase): +class TestDIA(_TestCommon, _TestArithmetic, TestCase): spmatrix = dia_matrix - def check_constructor1(self): + def test_constructor1(self): pass #TODO add test class TestBSR(_TestCommon, _TestArithmetic, _TestInplaceArithmetic, - _TestMatvecOutput, NumpyTestCase): + _TestMatvecOutput, TestCase): spmatrix = bsr_matrix - def check_constructor1(self): + def test_constructor1(self): """check native BSR format constructor""" indptr = array([0,2,2,4]) indices = array([0,2,2,3]) @@ -1237,7 +1237,7 @@ Asp = bsr_matrix((data,indices,indptr)) assert_equal(Asp.todense(),A) - def check_constructor2(self): + def test_constructor2(self): """construct from dense""" #test zero mats @@ -1264,4 +1264,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/sparse/tests/test_construct.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_construct.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/sparse/tests/test_construct.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,16 +1,16 @@ """test sparse matrix construction functions""" from numpy import array, kron -from numpy.testing import * +from scipy.testing import * -set_package_path() + from scipy.sparse import csr_matrix, \ spidentity, speye, spkron, spdiags, \ lil_eye, lil_diags -restore_path() -class TestConstructUtils(NumpyTestCase): - def check_spdiags(self): + +class TestConstructUtils(TestCase): + def test_spdiags(self): diags1 = array( [[ 1, 2, 3, 4, 5]] ) diags2 = array( [[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9,10]] ) @@ -58,12 +58,12 @@ assert_equal( spdiags(d,o,m,n).todense(), result ) - def check_identity(self): + def test_identity(self): a = spidentity(3) b = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype='d') assert_array_equal(a.toarray(), b) - def check_eye(self): + def test_eye(self): a = speye(2, 3 ) b = array([[1, 0, 0], [0, 1, 0]], dtype='d') assert_array_equal(a.toarray(), b) @@ -76,7 +76,7 @@ b = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype='d') assert_array_equal(a.toarray(), b) - def check_spkron(self): + def test_spkron(self): cases = [] cases.append(array([[ 0]])) @@ -100,7 +100,7 @@ assert_array_equal(result,expected) - def check_lil_diags(self): + def test_lil_diags(self): assert_array_equal(lil_diags([[1,2,3],[4,5],[6]], [0,1,2],(3,3)).todense(), [[1,4,6], @@ -132,5 +132,5 @@ [6,5,0]]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/sparse/tests/test_sparse.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_sparse.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/sparse/tests/test_sparse.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -4,14 +4,14 @@ from numpy import ones, array, asarray, empty import random -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ coo_matrix, lil_matrix, dia_matrix, spidentity, spdiags, \ spkron from scipy.linsolve import splu -restore_path() + def random_sparse(m,n,nnz_per_row): rows = numpy.arange(m).repeat(nnz_per_row) cols = numpy.random.random_integers(low=0,high=n-1,size=nnz_per_row*m) @@ -43,10 +43,10 @@ return dia_matrix((diags,offsets),shape=(N**2,N**2)).asformat(format) import time -class TestSparseTools(NumpyTestCase): +class TestSparseTools(TestCase): """Simple benchmarks for sparse matrix module""" - def test_arithmetic(self,level=4): + def bench_arithmetic(self): matrices = [] #matrices.append( ('A','Identity', spidentity(500**2,format='csr')) ) matrices.append( ('A','Poisson5pt', poisson2d(500,format='csr')) ) @@ -94,7 +94,7 @@ - def bench_sort(self,level=5): + def bench_sort(self): """sort CSR column indices""" matrices = [] matrices.append( ('Rand10', 1e4, 10) ) @@ -127,7 +127,7 @@ print fmt % (A.format,name,shape,A.nnz,1e3*(end-start)/float(iter) ) - def bench_matvec(self,level=5): + def bench_matvec(self): matrices = [] matrices.append(('Identity', spidentity(10**4,format='dia'))) matrices.append(('Identity', spidentity(10**4,format='csr'))) @@ -174,7 +174,7 @@ print fmt % (A.format,name,shape,A.nnz,MFLOPs) - def bench_construction(self,level=5): + def bench_construction(self): """build matrices by inserting single values""" matrices = [] matrices.append( ('Empty',csr_matrix((10000,10000))) ) @@ -210,7 +210,7 @@ print fmt % (format,name,shape,A.nnz,(end-start)/float(iter)) - def bench_conversion(self,level=5): + def bench_conversion(self): A = poisson2d(100) formats = ['csr','csc','coo','lil','dok'] @@ -251,8 +251,8 @@ print output -class TestLarge(NumpyTestCase): - def check_large(self): +class TestLarge(TestCase): + def test_large(self): # Create a 100x100 matrix with 100 non-zero elements # and play around with it #TODO move this out of Common since it doesn't use spmatrix @@ -279,5 +279,5 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/sparse/tests/test_sputils.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_sputils.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/sparse/tests/test_sputils.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -2,28 +2,28 @@ import numpy -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy.sparse.sputils import * -restore_path() -class TestSparseUtils(NumpyTestCase): - def check_upcast(self): +class TestSparseUtils(TestCase): + + def test_upcast(self): assert_equal(upcast('int32'),numpy.int32) assert_equal(upcast('int32','float32'),numpy.float64) assert_equal(upcast('bool',complex,float),numpy.complex128) assert_equal(upcast('i','d'),numpy.float64) - def check_getdtype(self): + def test_getdtype(self): A = numpy.array([1],dtype='int8') assert_equal(getdtype(None,default=float),numpy.float) assert_equal(getdtype(None,a=A),numpy.int8) - def check_isscalarlike(self): + def test_isscalarlike(self): assert_equal(isscalarlike(3.0),True) assert_equal(isscalarlike(-4),True) assert_equal(isscalarlike(2.5),True) @@ -36,7 +36,7 @@ assert_equal(isscalarlike( (1,) ), False) assert_equal(isscalarlike( (1,2) ), False) - def check_isintlike(self): + def test_isintlike(self): assert_equal(isintlike(3.0),True) assert_equal(isintlike(-4),True) assert_equal(isintlike(numpy.array(3)),True) @@ -47,7 +47,7 @@ assert_equal(isintlike( (1,) ), False) assert_equal(isintlike( (1,2) ), False) - def check_isshape(self): + def test_isshape(self): assert_equal(isshape( (1,2) ),True) assert_equal(isshape( (5,2) ),True) @@ -56,7 +56,7 @@ assert_equal(isshape( (0,4) ),False) assert_equal(isshape( (2,2,2) ),False) - def check_issequence(self): + def test_issequence(self): assert_equal(issequence( (1,) ),True) assert_equal(issequence( (1,2,3) ),True) assert_equal(issequence( [1] ),True) @@ -66,11 +66,11 @@ assert_equal(issequence( numpy.array([[1],[2],[3]]) ),False) assert_equal(issequence( 3 ),False) - def check_isdense(self): + def test_isdense(self): assert_equal(isdense( numpy.array([1]) ),True) assert_equal(isdense( numpy.matrix([1]) ),True) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/special/tests/test_basic.py =================================================================== --- branches/testing_cleanup/scipy/special/tests/test_basic.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/special/tests/test_basic.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -32,377 +32,377 @@ #8 test_sh_jacobi #8 test_sh_legendre -from numpy import * +from numpy import dot -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy.special import * import scipy.special._cephes as cephes -restore_path() -class TestCephes(NumpyTestCase): - def check_airy(self): + +class TestCephes(TestCase): + def test_airy(self): cephes.airy(0) - def check_airye(self): + def test_airye(self): cephes.airye(0) - def check_bdtr(self): + def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) - def check_bdtri(self): + def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) - def check_bdtrc(self): + def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) - def check_bdtrin(self): + def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) - def check_bdtrik(self): + def test_bdtrik(self): cephes.bdtrik(1,3,0.5) - def check_bei(self): + def test_bei(self): assert_equal(cephes.bei(0),0.0) - def check_beip(self): + def test_beip(self): assert_equal(cephes.beip(0),0.0) - def check_ber(self): + def test_ber(self): assert_equal(cephes.ber(0),1.0) - def check_berp(self): + def test_berp(self): assert_equal(cephes.berp(0),0.0) - def check_besselpoly(self): + def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) - def check_beta(self): + def test_beta(self): assert_equal(cephes.beta(1,1),1.0) - def check_betainc(self): + def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) - def check_betaln(self): + def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) - def check_betaincinv(self): + def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) - def check_btdtr(self): + def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) - def check_btdtri(self): + def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) - def check_btdtria(self): + def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) - def check_btdtrib(self): + def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) - def check_cbrt(self): + def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) - def check_chdtr(self): + def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) - def check_chdtrc(self): + def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) - def check_chdtri(self): + def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) - def check_chdtriv(self): + def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) - def check_chndtr(self): + def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) - def check_chndtridf(self): + def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) - def check_chndtrinc(self): + def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) - def check_chndtrix(self): + def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) - def check_cosdg(self): + def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) - def check_cosm1(self): + def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) - def check_cotdg(self): + def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) - def check_dawsn(self): + def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) - def check_ellipe(self): + def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) - def check_ellipeinc(self): + def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) - def check_ellipj(self): + def test_ellipj(self): cephes.ellipj(0,1) - def check_ellipk(self): + def test_ellipk(self): cephes.ellipk(0)#==pi/2 - def check_ellipkinc(self): + def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) - def check_erf(self): + def test_erf(self): assert_equal(cephes.erf(0),0.0) - def check_erfc(self): + def test_erfc(self): assert_equal(cephes.erfc(0),1.0) - def check_exp1(self): + def test_exp1(self): cephes.exp1(1) - def check_expi(self): + def test_expi(self): cephes.expi(1) - def check_expn(self): + def test_expn(self): cephes.expn(1,1) - def check_exp10(self): + def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) - def check_exp2(self): + def test_exp2(self): assert_equal(cephes.exp2(2),4.0) - def check_expm1(self): + def test_expm1(self): assert_equal(cephes.expm1(0),0.0) - def check_fdtr(self): + def test_fdtr(self): assert_equal(cephes.fdtr(1,1,0),0.0) - def check_fdtrc(self): + def test_fdtrc(self): assert_equal(cephes.fdtrc(1,1,0),1.0) - def check_fdtri(self): + def test_fdtri(self): cephes.fdtri(1,1,0.5) - def check_fdtridfd(self): + def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) - def check_fresnel(self): + def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) - def check_gamma(self): + def test_gamma(self): assert_equal(cephes.gamma(5),24.0) - def check_gammainc(self): + def test_gammainc(self): assert_equal(cephes.gammainc(5,0),0.0) - def check_gammaincc(self): + def test_gammaincc(self): assert_equal(cephes.gammaincc(5,0),1.0) - def check_gammainccinv(self): + def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) - def check_gammaln(self): + def test_gammaln(self): cephes.gammaln(10) - def check_gdtr(self): + def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) - def check_gdtrc(self): + def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) - def check_gdtria(self): + def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) - def check_gdtrib(self): + def test_gdtrib(self): cephes.gdtrib(1,0,1) #assert_equal(cephes.gdtrib(1,0,1),5.0) - def check_gdtrix(self): + def test_gdtrix(self): cephes.gdtrix(1,1,.1) - def check_hankel1(self): + def test_hankel1(self): cephes.hankel1(1,1) - def check_hankel1e(self): + def test_hankel1e(self): cephes.hankel1e(1,1) - def check_hankel2(self): + def test_hankel2(self): cephes.hankel2(1,1) - def check_hankel2e(self): + def test_hankel2e(self): cephes.hankel2e(1,1) - def check_hyp1f1(self): + def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) - def check_hyp1f2(self): + def test_hyp1f2(self): cephes.hyp1f2(1,1,1,1) - def check_hyp2f0(self): + def test_hyp2f0(self): cephes.hyp2f0(1,1,1,1) - def check_hyp2f1(self): + def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) - def check_hyp3f0(self): + def test_hyp3f0(self): assert_equal(cephes.hyp3f0(1,1,1,0),(1.0,0.0)) - def check_hyperu(self): + def test_hyperu(self): assert_equal(cephes.hyperu(0,1,1),1.0) - def check_i0(self): + def test_i0(self): assert_equal(cephes.i0(0),1.0) - def check_i0e(self): + def test_i0e(self): assert_equal(cephes.i0e(0),1.0) - def check_i1(self): + def test_i1(self): assert_equal(cephes.i1(0),0.0) - def check_i1e(self): + def test_i1e(self): assert_equal(cephes.i1e(0),0.0) - def check_it2i0k0(self): + def test_it2i0k0(self): cephes.it2i0k0(1) - def check_it2j0y0(self): + def test_it2j0y0(self): cephes.it2j0y0(1) - def check_it2struve0(self): + def test_it2struve0(self): cephes.it2struve0(1) - def check_itairy(self): + def test_itairy(self): cephes.itairy(1) - def check_iti0k0(self): + def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) - def check_itj0y0(self): + def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) - def check_itmodstruve0(self): + def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) - def check_itstruve0(self): + def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) - def check_iv(self): + def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) - def check_j0(self): + def test_j0(self): assert_equal(cephes.j0(0),1.0) - def check_j1(self): + def test_j1(self): assert_equal(cephes.j1(0),0.0) - def check_jn(self): + def test_jn(self): assert_equal(cephes.jn(0,0),1.0) - def check_jv(self): + def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) - def check_k0(self): + def test_k0(self): cephes.k0(2) - def check_k0e(self): + def test_k0e(self): cephes.k0e(2) - def check_k1(self): + def test_k1(self): cephes.k1(2) - def check_k1e(self): + def test_k1e(self): cephes.k1e(2) - def check_kei(self): + def test_kei(self): cephes.kei(2) - def check_keip(self): + def test_keip(self): assert_equal(cephes.keip(0),0.0) - def check_ker(self): + def test_ker(self): cephes.ker(2) - def check_kerp(self): + def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) - def check_kn(self): + def test_kn(self): cephes.kn(1,1) - def check_kolmogi(self): + def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) - def check_kolmogorov(self): + def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0),1.0) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) - def check_log1p(self): + def test_log1p(self): assert_equal(cephes.log1p(0),0.0) - def check_lpmv(self): + def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) - def check_mathieu_a(self): + def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) - def check_mathieu_b(self): + def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) - def check_mathieu_cem(self): + def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) - def check_mathieu_modcem1(self): + def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) - def check_mathieu_modcem2(self): + def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) - def check_mathieu_sem(self): + def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) - def check_mathieu_modsem1(self): + def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) - def check_mathieu_modsem2(self): + def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) - def check_modfresnelm(self): + def test_modfresnelm(self): cephes.modfresnelm(0) - def check_modfresnelp(self): + def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) - def check_nbdtr(self): + def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) - def check_nbdtrc(self): + def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) - def check_nbdtri(self): + def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) - def check_nbdtrin(self): + def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) - def check_ncfdtr(self): + def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) - def check_ncfdtri(self): + def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1,1,1,0),0.0) - def check_ncfdtridfd(self): + def test_ncfdtridfd(self): cephes.ncfdtridfd(1,0.5,0,1) def __check_ncfdtridfn(self): cephes.ncfdtridfn(1,0.5,0,1) def __check_ncfdtrinc(self): cephes.ncfdtrinc(1,0.5,0,1) - def check_nctdtr(self): + def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) - def check_nctdtrinc(self): + def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) - def check_nctdtrit(self): + def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) - def check_ndtr(self): + def test_ndtr(self): assert_equal(cephes.ndtr(0),0.5) - def check_ndtri(self): + def test_ndtri(self): assert_equal(cephes.ndtri(0.5),0.0) - def check_nrdtrimn(self): + def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) - def check_nrdtrisd(self): + def test_nrdtrisd(self): assert_equal(cephes.nrdtrisd(0.5,0.5,0.5),0.0) - def check_obl_ang1(self): + def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) - def check_obl_ang1_cv(self): + def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) - def check_obl_rad1(self): + def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) - def check_obl_rad1_cv(self): + def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) - def check_obl_rad2(self): + def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) - def check_obl_rad2_cv(self): + def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) - def check_pbdv(self): + def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,0.0)) - def check_pbvv(self): + def test_pbvv(self): cephes.pbvv(1,0) - def check_pbwa(self): + def test_pbwa(self): cephes.pbwa(1,0) - def check_pdtr(self): + def test_pdtr(self): cephes.pdtr(0,1) - def check_pdtrc(self): + def test_pdtrc(self): cephes.pdtrc(0,1) - def check_pdtri(self): + def test_pdtri(self): cephes.pdtri(0.5,0.5) - def check_pdtrik(self): + def test_pdtrik(self): cephes.pdtrik(0.5,1) - def check_pro_ang1(self): + def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) - def check_pro_ang1_cv(self): + def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) - def check_pro_rad1(self): + def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) - def check_pro_rad1_cv(self): + def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) - def check_pro_rad2(self): + def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) - def check_pro_rad2_cv(self): + def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) - def check_psi(self): + def test_psi(self): cephes.psi(1) - def check_radian(self): + def test_radian(self): assert_equal(cephes.radian(0,0,0),0) - def check_rgamma(self): + def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) - def check_round(self): + def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) @@ -410,54 +410,54 @@ assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) - def check_shichi(self): + def test_shichi(self): cephes.shichi(1) - def check_sici(self): + def test_sici(self): cephes.sici(1) - def check_sindg(self): + def test_sindg(self): assert_equal(cephes.sindg(90),1.0) - def check_smirnov(self): + def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) - def check_smirnovi(self): + def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) - def check_spence(self): + def test_spence(self): assert_equal(cephes.spence(1),0.0) - def check_stdtr(self): + def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) - def check_stdtridf(self): + def test_stdtridf(self): cephes.stdtridf(0.7,1) - def check_stdtrit(self): + def test_stdtrit(self): cephes.stdtrit(1,0.7) - def check_struve(self): + def test_struve(self): assert_equal(cephes.struve(0,0),0.0) - def check_tandg(self): + def test_tandg(self): assert_equal(cephes.tandg(45),1.0) - def check_tklmbda(self): + def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) - def check_y0(self): + def test_y0(self): cephes.y0(1) - def check_y1(self): + def test_y1(self): cephes.y1(1) - def check_yn(self): + def test_yn(self): cephes.yn(1,1) - def check_yv(self): + def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) - def check_zeta(self): + def test_zeta(self): cephes.zeta(2,2) - def check_zetac(self): + def test_zetac(self): assert_equal(cephes.zetac(0),-1.5) - def check_wofz(self): + def test_wofz(self): cephes.wofz(0) -class TestAiry(NumpyTestCase): - def check_airy(self): +class TestAiry(TestCase): + def test_airy(self): #This tests the airy function to ensure 8 place accuracy in computation x = airy(.99) @@ -467,7 +467,7 @@ x = airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) - def check_airye(self): + def test_airye(self): a = airye(0.01) b = airy(0.01) b1 = [None]*4 @@ -477,7 +477,7 @@ b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) - def check_bi_zeros(self): + def test_bi_zeros(self): bi = bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), @@ -485,43 +485,43 @@ array([ 0.60195789 , -0.76031014])) assert_array_almost_equal(bi,bia,4) - def check_ai_zeros(self): + def test_ai_zeros(self): ai = ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([ 0.5357]), array([ 0.7012])),4) -class TestAssocLaguerre(NumpyTestCase): - def check_assoc_laguerre(self): +class TestAssocLaguerre(TestCase): + def test_assoc_laguerre(self): a1 = genlaguerre(11,1) a2 = assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) -class TestBesselpoly(NumpyTestCase): - def check_besselpoly(self): +class TestBesselpoly(TestCase): + def test_besselpoly(self): pass -class TestKelvin(NumpyTestCase): - def check_bei(self): +class TestKelvin(TestCase): + def test_bei(self): mbei = bei(2) assert_almost_equal(mbei, 0.9722916273066613,5)#this may not be exact - def check_beip(self): + def test_beip(self): mbeip = beip(2) assert_almost_equal(mbeip,0.91701361338403631,5)#this may not be exact - def check_ber(self): + def test_ber(self): mber = ber(2) assert_almost_equal(mber,0.75173418271380821,5)#this may not be exact - def check_berp(self): + def test_berp(self): mberp = berp(2) assert_almost_equal(mberp,-0.49306712470943909,5)#this may not be exact - def check_bei_zeros(self): + def test_bei_zeros(self): bi = bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, @@ -548,7 +548,7 @@ 0.929983638568022]),11) - def check_beip_zeros(self): + def test_beip_zeros(self): bip = beip_zeros(5) assert_array_almost_equal(bip,array([ 3.772673304934953, 8.280987849760042, @@ -556,7 +556,7 @@ 17.193431752512542, 21.641143941167325]),4) - def check_ber_zeros(self): + def test_ber_zeros(self): ber = ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, @@ -564,7 +564,7 @@ 16.11356, 20.55463]),4) - def check_berp_zeros(self): + def test_berp_zeros(self): brp = berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, @@ -572,30 +572,30 @@ 19.41758, 23.86430]),4) - def check_kelvin(self): + def test_kelvin(self): mkelv = kelvin(2) assert_array_almost_equal(mkelv,(ber(2)+bei(2)*1j, ker(2)+kei(2)*1j, berp(2)+beip(2)*1j, kerp(2)+keip(2)*1j),8) - def check_kei(self): + def test_kei(self): mkei = kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) - def check_keip(self): + def test_keip(self): mkeip = keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) - def check_ker(self): + def test_ker(self): mker = ker(2) assert_almost_equal(mker,-0.041664513991509472,5) - def check_kerp(self): + def test_kerp(self): mkerp = kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) - def check_kei_zeros(self): + def test_kei_zeros(self): kei = kei_zeros(5) assert_array_almost_equal(kei,array([ 3.91467, 8.34422, @@ -603,7 +603,7 @@ 17.22314, 21.66464]),4) - def check_keip_zeros(self): + def test_keip_zeros(self): keip = keip_zeros(5) assert_array_almost_equal(keip,array([ 4.93181, 9.40405, @@ -614,7 +614,7 @@ # numbers come from 9.9 of A&S pg. 381 - def check_kelvin_zeros(self): + def test_kelvin_zeros(self): tmp = kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([ 2.84892, @@ -660,7 +660,7 @@ 18.30717, 22.75379]),4) - def check_ker_zeros(self): + def test_ker_zeros(self): ker = ker_zeros(5) assert_array_almost_equal(ker,array([ 1.71854, 6.12728, @@ -668,7 +668,7 @@ 15.00269, 19.44381]),4) - def check_kerp_zeros(self): + def test_kerp_zeros(self): kerp = kerp_zeros(5) assert_array_almost_equal(kerp,array([ 2.66584, 7.17212, @@ -676,8 +676,8 @@ 16.08312, 20.53068]),4) -class TestBernoulli(NumpyTestCase): - def check_bernoulli(self): +class TestBernoulli(TestCase): + def test_bernoulli(self): brn = bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, @@ -686,28 +686,28 @@ -0.0333, 0.0000]),4) -class TestBeta(NumpyTestCase): - def check_beta(self): +class TestBeta(TestCase): + def test_beta(self): bet = beta(2,4) betg = (gamma(2)*gamma(4))/gamma(6) assert_almost_equal(bet,betg,8) - def check_betaln(self): + def test_betaln(self): betln = betaln(2,4) bet = log(abs(beta(2,4))) assert_almost_equal(betln,bet,8) - def check_betainc(self): + def test_betainc(self): btinc = betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) - def check_betaincinv(self): + def test_betaincinv(self): y = betaincinv(2,4,.5) comp = betainc(2,4,y) assert_almost_equal(comp,.5,5) -class TestCheby(NumpyTestCase): - def check_chebyc(self): +class TestCheby(TestCase): + def test_chebyc(self): C0 = chebyc(0) C1 = chebyc(1) C2 = chebyc(2) @@ -722,7 +722,7 @@ assert_array_almost_equal(C4.c,[1,0,-4,0,2],13) assert_array_almost_equal(C5.c,[1,0,-5,0,5,0],13) - def check_chebys(self): + def test_chebys(self): S0 = chebys(0) S1 = chebys(1) S2 = chebys(2) @@ -736,7 +736,7 @@ assert_array_almost_equal(S4.c,[1,0,-3,0,1],13) assert_array_almost_equal(S5.c,[1,0,-4,0,3,0],13) - def check_chebyt(self): + def test_chebyt(self): T0 = chebyt(0) T1 = chebyt(1) T2 = chebyt(2) @@ -750,7 +750,7 @@ assert_array_almost_equal(T4.c,[8,0,-8,0,1],13) assert_array_almost_equal(T5.c,[16,0,-20,0,5,0],13) - def check_chebyu(self): + def test_chebyu(self): U0 = chebyu(0) U1 = chebyu(1) U2 = chebyu(2) @@ -764,43 +764,43 @@ assert_array_almost_equal(U4.c,[16,0,-12,0,1],13) assert_array_almost_equal(U5.c,[32,0,-32,0,6,0],13) -class TestTrigonometric(NumpyTestCase): - def check_cbrt(self): +class TestTrigonometric(TestCase): + def test_cbrt(self): cb = cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) - def check_cbrtmore(self): + def test_cbrtmore(self): cb1 = cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) - def check_cosdg(self): + def test_cosdg(self): cdg = cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) - def check_cosdgmore(self): + def test_cosdgmore(self): cdgm = cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) - def check_cosm1(self): + def test_cosm1(self): cs = (cosm1(0),cosm1(.3),cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) - def check_cotdg(self): + def test_cotdg(self): ct = cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) - def check_cotdgmore(self): + def test_cotdgmore(self): ct1 = cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) - def check_specialpoints(self): + def test_specialpoints(self): assert_almost_equal(cotdg(45), 1.0, 14) assert_almost_equal(cotdg(-45), -1.0, 14) assert_almost_equal(cotdg(90), 0.0, 14) @@ -815,21 +815,21 @@ assert_almost_equal(cotdg(-315), 1.0, 14) assert_almost_equal(cotdg(765), 1.0, 14) - def check_sinc(self): + def test_sinc(self): c = arange(-2,2,.1) y = sinc(c) yre = sin(pi*c)/(pi*c) yre[20] = 1.0 assert_array_almost_equal(y, yre, 4) - def check_0(self): + def test_0(self): x = 0.0 assert_equal(sinc(x),1.0) - def check_sindg(self): + def test_sindg(self): sn = sindg(90) assert_equal(sn,1.0) - def check_sindgmore(self): + def test_sindgmore(self): snm = sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) @@ -837,14 +837,14 @@ snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) -class TestTandg(NumpyTestCase): +class TestTandg(TestCase): - def check_tandg(self): + def test_tandg(self): tn = tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) - def check_tandgmore(self): + def test_tandgmore(self): tnm = tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) @@ -852,7 +852,7 @@ tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) - def check_specialpoints(self): + def test_specialpoints(self): assert_almost_equal(tandg(0), 0.0, 14) assert_almost_equal(tandg(45), 1.0, 14) assert_almost_equal(tandg(-45), -1.0, 14) @@ -865,17 +865,17 @@ assert_almost_equal(tandg(315), -1.0, 14) assert_almost_equal(tandg(-315), 1.0, 14) -class TestEllip(NumpyTestCase): - def check_ellipj(self): +class TestEllip(TestCase): + def test_ellipj(self): el = ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) - def check_ellipk(self): + def test_ellipk(self): elk = ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) - def check_ellipkinc(self): + def test_ellipkinc(self): elkinc = ellipkinc(pi/2,.2) elk = ellipk(0.2) assert_almost_equal(elkinc,elk,15) @@ -886,11 +886,11 @@ assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S - def check_ellipe(self): + def test_ellipe(self): ele = ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) - def check_ellipeinc(self): + def test_ellipeinc(self): eleinc = ellipeinc(pi/2,.2) ele = ellipe(0.2) assert_almost_equal(eleinc,ele,14) @@ -901,13 +901,13 @@ assert_almost_equal(eleinc, 0.58823065, 8) -class TestErf(NumpyTestCase): +class TestErf(TestCase): - def check_erf(self): + def test_erf(self): er = erf(.25) assert_almost_equal(er,0.2763263902,8) - def check_erf_zeros(self): + def test_erf_zeros(self): erz = erf_zeros(5) erzr= array([1.45061616+1.88094300j, 2.24465928+2.61657514j, @@ -916,15 +916,15 @@ 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) - def check_erfcinv(self): + def test_erfcinv(self): i = erfcinv(1) assert_equal(i,0) - def check_erfinv(self): + def test_erfinv(self): i = erfinv(0) assert_equal(i,0) - def check_errprint(self): + def test_errprint(self): a = errprint() b = 1-a #a is the state 1-a inverts state c = errprint(b) #returns last state 'a' @@ -933,8 +933,8 @@ assert_equal(d,b) #makes sure state was returned #assert_equal(d,1-a) -class TestEuler(NumpyTestCase): - def check_euler(self): +class TestEuler(TestCase): + def test_euler(self): eu0 = euler(0) eu1 = euler(1) eu2 = euler(2) # just checking segfaults @@ -955,45 +955,45 @@ errmax = max(err) assert_almost_equal(errmax, 0.0, 14) -class TestExp(NumpyTestCase): - def check_exp2(self): +class TestExp(TestCase): + def test_exp2(self): ex = exp2(2) exrl = 2**2 assert_equal(ex,exrl) - def check_exp2more(self): + def test_exp2more(self): exm = exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) - def check_exp10(self): + def test_exp10(self): ex = exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) - def check_exp10more(self): + def test_exp10more(self): exm = exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) - def check_expm1(self): + def test_expm1(self): ex = (expm1(2),expm1(3),expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) - def check_expm1more(self): + def test_expm1more(self): ex1 = (expm1(2),expm1(2.1),expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) -class TestFresnel(NumpyTestCase): - def check_fresnel(self): +class TestFresnel(TestCase): + def test_fresnel(self): frs = array(fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place - def check_fresnel_zeros(self): + def test_fresnel_zeros(self): szo, czo = fresnel_zeros(5) assert_array_almost_equal(szo, array([ 2.0093+0.2885j, @@ -1012,86 +1012,86 @@ assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) - def check_fresnelc_zeros(self): + def test_fresnelc_zeros(self): szo, czo = fresnel_zeros(6) frc = fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) - def check_fresnels_zeros(self): + def test_fresnels_zeros(self): szo, czo = fresnel_zeros(5) frs = fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) -class TestGamma(NumpyTestCase): - def check_gamma(self): +class TestGamma(TestCase): + def test_gamma(self): gam = gamma(5) assert_equal(gam,24.0) - def check_gammaln(self): + def test_gammaln(self): gamln = gammaln(3) lngam = log(gamma(3)) assert_almost_equal(gamln,lngam,8) - def check_gammainc(self): + def test_gammainc(self): gama = gammainc(.5,.5) assert_almost_equal(gama,.7,1) - def check_gammaincc(self): + def test_gammaincc(self): gicc = gammaincc(.5,.5) greal = 1 - gammainc(.5,.5) assert_almost_equal(gicc,greal,8) - def check_gammainccinv(self): + def test_gammainccinv(self): gccinv = gammainccinv(.5,.5) gcinv = gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) - def check_gammaincinv(self): + def test_gammaincinv(self): y = gammaincinv(.4,.4) x = gammainc(.4,y) assert_almost_equal(x,0.4,1) - def check_rgamma(self): + def test_rgamma(self): rgam = rgamma(8) rlgam = 1/gamma(8) assert_almost_equal(rgam,rlgam,8) -class TestHankel(NumpyTestCase): - def check_negv(self): +class TestHankel(TestCase): + def test_negv(self): assert_almost_equal(hankel1(-3,2), -hankel1(3,2), 14) - def check_hankel1(self): + def test_hankel1(self): hank1 = hankel1(1,.1) hankrl = (jv(1,.1)+yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(hankel1e(-3,2), -hankel1e(3,2), 14) - def check_hankel1e(self): + def test_hankel1e(self): hank1e = hankel1e(1,.1) hankrle = hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(hankel2(-3,2), -hankel2(3,2), 14) - def check_hankel2(self): + def test_hankel2(self): hank2 = hankel2(1,.1) hankrl2 = (jv(1,.1)-yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(hankel2e(-3,2), -hankel2e(3,2), 14) - def check_hankl2e(self): + def test_hankl2e(self): hank2e = hankel2e(1,.1) hankrl2e = hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) -class TestHermite(NumpyTestCase): - def check_hermite(self): +class TestHermite(TestCase): + def test_hermite(self): H0 = hermite(0) H1 = hermite(1) H2 = hermite(2) @@ -1105,7 +1105,7 @@ assert_array_almost_equal(H4.c,[16,0,-48,0,12],12) assert_array_almost_equal(H5.c,[32,0,-160,0,120,0],12) - def check_hermitenorm(self): + def test_hermitenorm(self): # He_n(x) = 2**(-n/2) H_n(x/sqrt(2)) psub = poly1d([1.0/sqrt(2),0]) H0 = hermitenorm(0) @@ -1130,9 +1130,9 @@ _gam = cephes.gamma -class TestGegenbauer(NumpyTestCase): +class TestGegenbauer(TestCase): - def check_gegenbauer(self): + def test_gegenbauer(self): a = 5*rand()-0.5 if any(a==0): a = -0.2 Ca0 = gegenbauer(0,a) @@ -1153,31 +1153,31 @@ 0,15*poch(a,3),0])/15.0,11) -class TestHyper(NumpyTestCase): - def check_h1vp(self): +class TestHyper(TestCase): + def test_h1vp(self): h1 = h1vp(1,.1) h1real = (jvp(1,.1)+yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) - def check_h2vp(self): + def test_h2vp(self): h2 = h2vp(1,.1) h2real = (jvp(1,.1)-yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) - def check_hyp0f1(self): + def test_hyp0f1(self): pass - def check_hyp1f1(self): + def test_hyp1f1(self): hyp1 = hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) - def check_hyp1f2(self): + def test_hyp1f2(self): pass - def check_hyp2f0(self): + def test_hyp2f0(self): pass - def check_hyp2f1(self): + def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], @@ -1200,10 +1200,10 @@ cv = hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) - def check_hyp3f0(self): + def test_hyp3f0(self): pass - def check_hyperu(self): + def test_hyperu(self): val1 = hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] @@ -1216,8 +1216,8 @@ /(gamma(a)*gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) -class TestBessel(NumpyTestCase): - def check_i0(self): +class TestBessel(TestCase): + def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], @@ -1231,12 +1231,12 @@ cv = i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) - def check_i0e(self): + def test_i0e(self): oize = i0e(.1) oizer = ive(0,.1) assert_almost_equal(oize,oizer,8) - def check_i1(self): + def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], @@ -1249,68 +1249,68 @@ cv = i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) - def check_i1e(self): + def test_i1e(self): oi1e = i1e(.1) oi1er = ive(1,.1) assert_almost_equal(oi1e,oi1er,8) - def check_iti0k0(self): + def test_iti0k0(self): iti0 = array(iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) - def check_it2i0k0(self): + def test_it2i0k0(self): it2k = it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) - def check_itj0y0(self): + def test_itj0y0(self): it0 = array(itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) - def check_it2j0y0(self): + def test_it2j0y0(self): it2 = array(it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) - def check_negv(self): + def test_negv(self): assert_equal(iv(3,2), iv(-3,2)) - def check_iv(self): + def test_iv(self): iv1 = iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) - def check_negv(self): + def test_negv(self): assert_equal(ive(3,2), ive(-3,2)) - def check_ive(self): + def test_ive(self): ive1 = ive(0,.1) iv1 = iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) - def check_ivp0(self): + def test_ivp0(self): assert_almost_equal(iv(1,2), ivp(0,2), 10) - def check_ivp(self): + def test_ivp(self): y=(iv(0,2)+iv(2,2))/2 x = ivp(1,2) assert_almost_equal(x,y,10) - def check_j0(self): + def test_j0(self): oz = j0(.1) ozr = jn(0,.1) assert_almost_equal(oz,ozr,8) - def check_j1(self): + def test_j1(self): o1 = j1(.1) o1r = jn(1,.1) assert_almost_equal(o1,o1r,8) - def check_jn(self): + def test_jn(self): jnnr = jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(jv(-3,2), -jv(3,2), 14) - def check_jv(self): + def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], @@ -1321,10 +1321,10 @@ yc = jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) - def check_negv(self): + def test_negv(self): assert_almost_equal(jve(-3,2), -jve(3,2), 14) - def check_jve(self): + def test_jve(self): jvexp = jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = jve(1,.2+1j) @@ -1332,7 +1332,7 @@ jvexpr = jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) - def check_jn_zeros(self): + def test_jn_zeros(self): jn0 = jn_zeros(0,5) jn1 = jn_zeros(1,5) assert_array_almost_equal(jn0,array([ 2.4048255577, @@ -1346,14 +1346,14 @@ 13.32369, 16.47063]),4) - def check_jnjnp_zeros(self): + def test_jnjnp_zeros(self): pass #jnjp = jnjnp(3) #assert_array_almost_equal(jnjp,(array([ #I don't think specfun jdzo is working properly the outputs do not seem to correlate #to the inputs - def check_jnp_zeros(self): + def test_jnp_zeros(self): jnp = jnp_zeros(1,5) assert_array_almost_equal(jnp, array([ 1.84118, 5.33144, @@ -1361,7 +1361,7 @@ 11.70600, 14.86359]),4) - def check_jnyn_zeros(self): + def test_jnyn_zeros(self): jnz = jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([ 3.83171, 7.01559, @@ -1384,32 +1384,32 @@ 13.28576, 16.44006])),4) - def check_jvp(self): + def test_jvp(self): jvprim = jvp(2,2) jv0 = (jv(1,2)-jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) - def check_k0(self): + def test_k0(self): ozk = k0(.1) ozkr = kv(0,.1) assert_almost_equal(ozk,ozkr,8) - def check_k0e(self): + def test_k0e(self): ozke = k0e(.1) ozker = kve(0,.1) assert_almost_equal(ozke,ozker,8) - def check_k1(self): + def test_k1(self): o1k = k1(.1) o1kr = kv(1,.1) assert_almost_equal(o1k,o1kr,8) - def check_k1e(self): + def test_k1e(self): o1ke = k1e(.1) o1ker = kve(1,.1) assert_almost_equal(o1ke,o1ker,8) - def check_jacobi(self): + def test_jacobi(self): a = 5*rand() - 1 b = 5*rand() - 1 P0 = jacobi(0,a,b) @@ -1427,28 +1427,28 @@ p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) - def check_kn(self): + def test_kn(self): kn1 = kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) - def check_negv(self): + def test_negv(self): assert_equal(kv(3.0, 2.2), kv(-3.0, 2.2)) - def check_kv0(self): + def test_kv0(self): kv0 = kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) - def check_kv1(self): + def test_kv1(self): kv1 = kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) - def check_kv2(self): + def test_kv2(self): kv2 = kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) - def check_negv(self): + def test_negv(self): assert_equal(kve(3.0, 2.2), kve(-3.0, 2.2)) - def check_kve(self): + def test_kve(self): kve1 = kve(0,.2) kv1 = kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) @@ -1457,35 +1457,35 @@ kv2 = kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) - def check_kvp_v0n1(self): + def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-kv(1,z), kvp(0,z, n=1), 10) - def check_kvp_n1(self): + def test_kvp_n1(self): v = 3. z = 2.2 xc = -kv(v+1,z) + v/z*kv(v,z) x = kvp(v,z, n=1) assert_almost_equal(xc, x, 10) #this function (kvp) is broken - def check_kvp_n2(self): + def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * kv(v,z) + kv(v+1,z)/z x = kvp(v, z, n=2) assert_almost_equal(xc, x, 10) - def check_y0(self): + def test_y0(self): oz = y0(.1) ozr = yn(0,.1) assert_almost_equal(oz,ozr,8) - def check_y1(self): + def test_y1(self): o1 = y1(.1) o1r = yn(1,.1) assert_almost_equal(o1,o1r,8) - def check_y0_zeros(self): + def test_y0_zeros(self): yo,ypo = y0_zeros(2) zo,zpo = y0_zeros(2,complex=1) all = r_[yo,zo] @@ -1494,51 +1494,51 @@ assert_array_almost_equal(abs(yv(1,all)-allval),0.0,11) - def check_y1_zeros(self): + def test_y1_zeros(self): y1 = y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) - def check_y1p_zeros(self): + def test_y1p_zeros(self): y1p = y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([ 0.5768+0.904j]), array([-0.7635+0.5892j])),3) - def check_yn_zeros(self): + def test_yn_zeros(self): an = yn_zeros(4,2) assert_array_almost_equal(an,array([ 5.64515, 9.36162]),5) - def check_ynp_zeros(self): + def test_ynp_zeros(self): ao = ynp_zeros(0,2) assert_array_almost_equal(ao,array([ 2.19714133, 5.42968104]),6) - def check_yn(self): + def test_yn(self): yn2n = yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(yv(-3,2), -yv(3,2), 14) - def check_yv(self): + def test_yv(self): yv2 = yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(yve(-3,2), -yve(3,2), 14) - def check_yve(self): + def test_yve(self): yve2 = yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = yv(1,.2+1j)*exp(-1) yve22 = yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) - def check_yvp(self): + def test_yvp(self): yvpr = (yv(1,.2) - yv(3,.2))/2.0 yvp1 = yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) -class TestLaguerre(NumpyTestCase): - def check_laguerre(self): +class TestLaguerre(TestCase): + def test_laguerre(self): lag0 = laguerre(0) lag1 = laguerre(1) lag2 = laguerre(2) @@ -1552,7 +1552,7 @@ assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) - def check_genlaguerre(self): + def test_genlaguerre(self): k = 5*rand()-0.9 lag0 = genlaguerre(0,k) lag1 = genlaguerre(1,k) @@ -1565,8 +1565,8 @@ # Base polynomials come from Abrahmowitz and Stegan -class TestLegendre(NumpyTestCase): - def check_legendre(self): +class TestLegendre(TestCase): + def test_legendre(self): leg0 = legendre(0) leg1 = legendre(1) leg2 = legendre(2) @@ -1581,26 +1581,26 @@ assert_almost_equal(leg5.c,array([63,0,-70,0,15,0])/8.0) -class TestLambda(NumpyTestCase): - def check_lmbda(self): +class TestLambda(TestCase): + def test_lmbda(self): lam = lmbda(1,.1) lamr = (array([jn(0,.1), 2*jn(1,.1)/.1]), array([jvp(0,.1), -2*jv(1,.1)/.01 + 2*jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) -class TestLog1p(NumpyTestCase): - def check_log1p(self): +class TestLog1p(TestCase): + def test_log1p(self): l1p = (log1p(10),log1p(11),log1p(12)) l1prl = (log(11),log(12),log(13)) assert_array_almost_equal(l1p,l1prl,8) - def check_log1pmore(self): + def test_log1pmore(self): l1pm = (log1p(1),log1p(1.1),log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) -class TestLegendreFunctions(NumpyTestCase): - def check_lpmn(self): +class TestLegendreFunctions(TestCase): + def test_lpmn(self): lp = lpmn(0,2,.5) assert_array_almost_equal(lp,(array([ [ 1.00000 , 0.50000, @@ -1609,7 +1609,7 @@ 1.00000 , 1.50000]])),4) - def check_lpn(self): + def test_lpn(self): lpnf = lpn(2,.5) assert_array_almost_equal(lpnf,(array( [ 1.00000 , 0.50000, @@ -1618,111 +1618,111 @@ 1.00000 , 1.50000])),4) - def check_lpmv(self): + def test_lpmv(self): lp = lpmv(0,2,.5) assert_almost_equal(lp,-0.125,3) - def check_lqmn(self): + def test_lqmn(self): lqmnf = lqmn(0,2,.5) lqmnf = lqmn(0,2,.5) lqf = lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) - def check_lqn(self): + def test_lqn(self): lqf = lqn(2,.5) assert_array_almost_equal(lqf,(array([ 0.5493, -0.7253, -0.8187]), array([ 1.3333, 1.216 , -0.8427])),4) -class TestMathieu(NumpyTestCase): +class TestMathieu(TestCase): - def check_mathieu_a(self): + def test_mathieu_a(self): pass - def check_mathieu_even_coef(self): + def test_mathieu_even_coef(self): mc = mathieu_even_coef(2,5) #Q not defined broken and cannot figure out proper reporting order - def check_mathieu_odd_coef(self): + def test_mathieu_odd_coef(self): pass #same problem as above -class TestFresnelIntegral(NumpyTestCase): +class TestFresnelIntegral(TestCase): - def check_modfresnelp(self): + def test_modfresnelp(self): pass - def check_modfresnelm(self): + def test_modfresnelm(self): pass -class TestOblCvSeq(NumpyTestCase): - def check_obl_cv_seq(self): +class TestOblCvSeq(TestCase): + def test_obl_cv_seq(self): obl = obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([ -0.348602, 1.393206, 5.486800, 11.492120]),5) -class TestParabolicCylinder(NumpyTestCase): - def check_pbdn_seq(self): +class TestParabolicCylinder(TestCase): + def test_pbdn_seq(self): pb = pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([ 0.9975, 0.0998]), array([-0.0499, 0.9925])),4) - def check_pbdv(self): + def test_pbdv(self): pbv = pbdv(1,.2) derrl = 1/2*(.2)*pbdv(1,.2)[0] - pbdv(0,.2)[0] - def check_pbdv_seq(self): + def test_pbdv_seq(self): pbn = pbdn_seq(1,.1) pbv = pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) -class TestPolygamma(NumpyTestCase): +class TestPolygamma(TestCase): # from Table 6.2 (pg. 271) of A&S - def check_polygamma(self): + def test_polygamma(self): poly2 = polygamma(2,1) poly3 = polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) -class TestProCvSeq(NumpyTestCase): - def check_pro_cv_seq(self): +class TestProCvSeq(TestCase): + def test_pro_cv_seq(self): prol = pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([ 0.319000, 2.593084, 6.533471, 12.514462]),5) -class TestPsi(NumpyTestCase): - def check_psi(self): +class TestPsi(TestCase): + def test_psi(self): ps = psi(1) assert_almost_equal(ps,-0.57721566490153287,8) -class TestRadian(NumpyTestCase): - def check_radian(self): +class TestRadian(TestCase): + def test_radian(self): rad = radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) - def check_radianmore(self): + def test_radianmore(self): rad1 = radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) -class TestRiccati(NumpyTestCase): - def check_riccati_jn(self): +class TestRiccati(TestCase): + def test_riccati_jn(self): jnrl = (sph_jn(1,.2)[0]*.2,sph_jn(1,.2)[0]+sph_jn(1,.2)[1]*.2) ricjn = riccati_jn(1,.2) assert_array_almost_equal(ricjn,jnrl,8) - def check_riccati_yn(self): + def test_riccati_yn(self): ynrl = (sph_yn(1,.2)[0]*.2,sph_yn(1,.2)[0]+sph_yn(1,.2)[1]*.2) ricyn = riccati_yn(1,.2) assert_array_almost_equal(ricyn,ynrl,8) -class TestRound(NumpyTestCase): - def check_round(self): +class TestRound(TestCase): + def test_round(self): rnd = map(int,(round(10.1),round(10.4),round(10.5),round(10.6))) # Note: According to the documentation, scipy.special.round is @@ -1733,9 +1733,9 @@ rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) -class _test_sh_legendre(NumpyTestCase): +class _test_sh_legendre(TestCase): - def check_sh_legendre(self): + def test_sh_legendre(self): # P*_n(x) = P_n(2x-1) psub = poly1d([2,-1]) Ps0 = sh_legendre(0) @@ -1757,9 +1757,9 @@ assert_array_almost_equal(Ps4.c,pse4.c,12) assert_array_almost_equal(Ps5.c,pse5.c,12) -class _test_sh_chebyt(NumpyTestCase): +class _test_sh_chebyt(TestCase): - def check_sh_chebyt(self): + def test_sh_chebyt(self): # T*_n(x) = T_n(2x-1) psub = poly1d([2,-1]) Ts0 = sh_chebyt(0) @@ -1782,9 +1782,9 @@ assert_array_almost_equal(Ts5.c,tse5.c,12) -class _test_sh_chebyu(NumpyTestCase): +class _test_sh_chebyu(TestCase): - def check_sh_chebyu(self): + def test_sh_chebyu(self): # U*_n(x) = U_n(2x-1) psub = poly1d([2,-1]) Us0 = sh_chebyu(0) @@ -1806,9 +1806,9 @@ assert_array_almost_equal(Us4.c,use4.c,12) assert_array_almost_equal(Us5.c,use5.c,11) -class _test_sh_jacobi(NumpyTestCase): +class _test_sh_jacobi(TestCase): - def check_sh_jacobi(self): + def test_sh_jacobi(self): # G^(p,q)_n(x) = n! gamma(n+p)/gamma(2*n+p) * P^(p-q,q-1)_n(2*x-1) conv = lambda n,p: _gam(n+1)*_gam(n+p)/_gam(2*n+p) psub = poly1d([2,-1]) @@ -1835,11 +1835,11 @@ assert_array_almost_equal(G4.c,ge4.c,13) assert_array_almost_equal(G5.c,ge5.c,13) -class TestSpherical(NumpyTestCase): - def check_sph_harm(self): +class TestSpherical(TestCase): + def test_sph_harm(self): pass - def check_sph_in(self): + def test_sph_in(self): i1n = sph_in(1,.2) inp0 = (i1n[0][1]) inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1]) @@ -1847,12 +1847,12 @@ 0.066933714568029540839]),12) assert_array_almost_equal(i1n[1],[inp0,inp1],12) - def check_sph_inkn(self): + def test_sph_inkn(self): spikn = r_[sph_in(1,.2)+sph_kn(1,.2)] inkn = r_[sph_inkn(1,.2)] assert_array_almost_equal(inkn,spikn,10) - def check_sph_jn(self): + def test_sph_jn(self): s1 = sph_jn(2,.2) s10 = -s1[0][1] s11 = s1[0][0]-2.0/0.2*s1[0][1] @@ -1862,12 +1862,12 @@ 0.0026590560795273856680],12) assert_array_almost_equal(s1[1],[s10,s11,s12],12) - def check_sph_jnyn(self): + def test_sph_jnyn(self): jnyn = r_[sph_jn(1,.2) + sph_yn(1,.2)] # tuple addition jnyn1 = r_[sph_jnyn(1,.2)] assert_array_almost_equal(jnyn1,jnyn,9) - def check_sph_kn(self): + def test_sph_kn(self): kn = sph_kn(2,.2) kn0 = -kn[0][1] kn1 = -kn[0][0]-2.0/0.2*kn[0][1] @@ -1877,7 +1877,7 @@ 585.15696310385559829],12) assert_array_almost_equal(kn[1],[kn0,kn1,kn2],9) - def check_sph_yn(self): + def test_sph_yn(self): sy1 = sph_yn(2,.2)[0][2] sy2 = sph_yn(0,.2)[0][0] sphpy = (sph_yn(1,.2)[0][0]-2*sph_yn(2,.2)[0][2])/3 #correct derivative value @@ -1887,4 +1887,4 @@ assert_almost_equal(sy3,sphpy,4) #compare correct derivative val. (correct =-system val). if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/special/tests/test_spfun_stats.py =================================================================== --- branches/testing_cleanup/scipy/special/tests/test_spfun_stats.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/special/tests/test_spfun_stats.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,11 +1,11 @@ import numpy as N -from numpy.testing import * +from scipy.testing import * -set_package_path() + from scipy.special import gammaln, multigammaln -restore_path() -class TestMultiGammaLn(NumpyTestCase): + +class TestMultiGammaLn(TestCase): def test1(self): a = N.abs(N.random.randn()) assert_array_equal(multigammaln(a, 1), gammaln(a)) @@ -35,4 +35,4 @@ pass if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/models/tests/test_bspline.py =================================================================== --- branches/testing_cleanup/scipy/stats/models/tests/test_bspline.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/models/tests/test_bspline.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -3,13 +3,13 @@ """ import numpy as N -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * import scipy.stats.models as S import scipy.stats.models.bspline as B -class TestBSpline(NumpyTestCase): +class TestBSpline(TestCase): def test1(self): b = B.BSpline(N.linspace(0,10,11), x=N.linspace(0,10,101)) @@ -20,4 +20,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/models/tests/test_formula.py =================================================================== --- branches/testing_cleanup/scipy/stats/models/tests/test_formula.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/models/tests/test_formula.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -7,11 +7,11 @@ import numpy as N import numpy.random as R import numpy.linalg as L -from numpy.testing import assert_almost_equal, NumpyTest, NumpyTestCase +from scipy.testing import * from scipy.stats.models import utils, formula, contrast -class TestTerm(NumpyTestCase): +class TestTerm(TestCase): def test_init(self): t1 = formula.Term("trivial") @@ -47,7 +47,7 @@ f = intercept * t1 self.assertEqual(str(f), str(formula.Formula(t1))) -class TestFormula(NumpyTestCase): +class TestFormula(TestCase): def setUp(self): self.X = R.standard_normal((40,10)) @@ -227,4 +227,4 @@ self.assertEquals(estimable, False) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/models/tests/test_glm.py =================================================================== --- branches/testing_cleanup/scipy/stats/models/tests/test_glm.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/models/tests/test_glm.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -4,16 +4,16 @@ import numpy as N import numpy.random as R -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * import scipy.stats.models as S import scipy.stats.models.glm as models W = R.standard_normal -class TestRegression(NumpyTestCase): +class TestRegression(TestCase): - def check_Logistic(self): + def test_Logistic(self): X = W((40,10)) Y = N.greater(W((40,)), 0) family = S.family.Binomial() @@ -21,7 +21,7 @@ results = cmodel.fit(Y) self.assertEquals(results.df_resid, 30) - def check_Logisticdegenerate(self): + def test_Logisticdegenerate(self): X = W((40,10)) X[:,0] = X[:,1] + X[:,2] Y = N.greater(W((40,)), 0) @@ -31,4 +31,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/models/tests/test_regression.py =================================================================== --- branches/testing_cleanup/scipy/stats/models/tests/test_regression.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/models/tests/test_regression.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -3,13 +3,13 @@ """ from numpy.random import standard_normal -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * from scipy.stats.models.regression import OLSModel, ARModel W = standard_normal -class TestRegression(NumpyTestCase): +class TestRegression(TestCase): def testOLS(self): X = W((40,10)) @@ -42,4 +42,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/models/tests/test_rlm.py =================================================================== --- branches/testing_cleanup/scipy/stats/models/tests/test_rlm.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/models/tests/test_rlm.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -3,13 +3,13 @@ """ import numpy.random as R -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * import scipy.stats.models.rlm as models W = R.standard_normal -class TestRegression(NumpyTestCase): +class TestRegression(TestCase): def test_Robust(self): X = W((40,10)) @@ -27,4 +27,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/models/tests/test_scale.py =================================================================== --- branches/testing_cleanup/scipy/stats/models/tests/test_scale.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/models/tests/test_scale.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -3,13 +3,13 @@ """ import numpy.random as R -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * import scipy.stats.models.robust.scale as scale W = R.standard_normal -class TestScale(NumpyTestCase): +class TestScale(TestCase): def test_MAD(self): X = W((40,10)) @@ -50,4 +50,4 @@ self.assertEquals(m.shape, (40,10)) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/models/tests/test_utils.py =================================================================== --- branches/testing_cleanup/scipy/stats/models/tests/test_utils.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/models/tests/test_utils.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -4,11 +4,11 @@ import numpy as N import numpy.random as R -from numpy.testing import assert_almost_equal, NumpyTest, NumpyTestCase +from scipy.testing import * from scipy.stats.models import utils -class TestUtils(NumpyTestCase): +class TestUtils(TestCase): def test_recipr(self): X = N.array([[2,1],[-1,0]]) @@ -55,4 +55,4 @@ self.assertRaises(ValueError, utils.StepFunction, x, y) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/tests/test_distributions.py =================================================================== --- branches/testing_cleanup/scipy/stats/tests/test_distributions.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/tests/test_distributions.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -3,17 +3,17 @@ """ -from numpy.testing import * +from scipy.testing import * -set_package_path() + import numpy from numpy import typecodes, array -import stats -restore_path() +import scipy.stats as stats + import types -def kolmogorov_test(diststr,args=(),N=20,significance=0.01): +def kolmogorov_check(diststr,args=(),N=20,significance=0.01): qtest = stats.ksoneisf(significance,N) cdf = eval('stats.'+diststr+'.cdf') dist = eval('stats.'+diststr) @@ -27,7 +27,6 @@ # generate test cases to test cdf and distribution consistency - dists = ['uniform','norm','lognorm','expon','beta', 'powerlaw','bradford','burr','fisk','cauchy','halfcauchy', 'foldcauchy','gamma','gengamma','loggamma', @@ -40,39 +39,40 @@ 'genlogistic', 'logistic','gumbel_l','gumbel_r','gompertz', 'hypsecant', 'laplace', 'reciprocal','triang','tukeylambda'] -for dist in dists: - distfunc = eval('stats.'+dist) - nargs = distfunc.numargs - alpha = 0.01 - if dist == 'fatiguelife': - alpha = 0.001 - if dist == 'erlang': - args = str((4,)+tuple(rand(2))) - elif dist == 'frechet': - args = str(tuple(2*rand(1))+(0,)+tuple(2*rand(2))) - elif dist == 'triang': - args = str(tuple(rand(nargs))) - elif dist == 'reciprocal': - vals = rand(nargs) - vals[1] = vals[0] + 1.0 - args = str(tuple(vals)) - else: - args = str(tuple(1.0+rand(nargs))) - exstr = r""" -class Test%(dist)s(NumpyTestCase): - def check_cdf(self): - D,pval = stats.kstest('%(dist)s','',args=%(args)s,N=30) - if (pval < %(alpha)f): - D,pval = stats.kstest('%(dist)s','',args=%(args)s,N=30) - #if (pval < %(alpha)f): - # D,pval = stats.kstest('%(dist)s','',args=%(args)s,N=30) - assert (pval > %(alpha)f), "D = " + str(D) + "; pval = " + str(pval) + "; alpha = " + str(alpha) + "\nargs = " + str(%(args)s) -""" % {'dist' : dist, 'args' : args, 'alpha' : alpha} - exec exstr +# check function for test generator +def check_distribution(dist, args, alpha): + D,pval = stats.kstest(dist,'',args=args, N=30) + if (pval < alpha): + D,pval = stats.kstest(dit,'',args=args, N=30) + #if (pval < alpha): + # D,pval = stats.kstest(dist,'',args=args, N=30) + assert (pval > alpha), "D = " + str(D) + "; pval = " + str(pval) + \ + "; alpha = " + str(alpha) + "\nargs = " + str(args) +# nose test genererator +def test_all_distributions(): + for dist in dists: + distfunc = eval('stats.'+dist) + nargs = distfunc.numargs + alpha = 0.01 + if dist == 'fatiguelife': + alpha = 0.001 + if dist == 'erlang': + args = (4,)+tuple(rand(2)) + elif dist == 'frechet': + args = tuple(2*rand(1))+(0,)+tuple(2*rand(2)) + elif dist == 'triang': + args = tuple(rand(nargs)) + elif dist == 'reciprocal': + vals = rand(nargs) + vals[1] = vals[0] + 1.0 + args = tuple(vals) + else: + args = tuple(1.0+rand(nargs)) + yield check_distribution, dist, args, alpha\ -class TestRandInt(NumpyTestCase): - def check_rvs(self): +class TestRandInt(TestCase): + def test_rvs(self): vals = stats.randint.rvs(5,30,size=100) assert(numpy.all(vals < 30) & numpy.all(vals >= 5)) assert(len(vals) == 100) @@ -84,21 +84,21 @@ assert isinstance(val, numpy.ScalarType),`type(val)` assert(val.dtype.char in typecodes['AllInteger']) - def check_pdf(self): + def test_pdf(self): k = numpy.r_[0:36] out = numpy.where((k >= 5) & (k < 30), 1.0/(30-5), 0) vals = stats.randint.pmf(k,5,30) assert_array_almost_equal(vals,out) - def check_cdf(self): + def test_cdf(self): x = numpy.r_[0:36:100j] k = numpy.floor(x) out = numpy.select([k>=30,k>=5],[1.0,(k-5.0+1)/(30-5.0)],0) vals = stats.randint.cdf(x,5,30) assert_array_almost_equal(vals, out, decimal=12) -class TestBinom(NumpyTestCase): - def check_rvs(self): +class TestBinom(TestCase): + def test_rvs(self): vals = stats.binom.rvs(10, 0.75, size=(2, 50)) assert(numpy.all(vals >= 0) & numpy.all(vals <= 10)) assert(numpy.shape(vals) == (2, 50)) @@ -108,8 +108,8 @@ assert(val.dtype.char in typecodes['AllInteger']) -class TestBernoulli(NumpyTestCase): - def check_rvs(self): +class TestBernoulli(TestCase): + def test_rvs(self): vals = stats.bernoulli.rvs(0.75, size=(2, 50)) assert(numpy.all(vals >= 0) & numpy.all(vals <= 1)) assert(numpy.shape(vals) == (2, 50)) @@ -118,8 +118,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestNBinom(NumpyTestCase): - def check_rvs(self): +class TestNBinom(TestCase): + def test_rvs(self): vals = stats.nbinom.rvs(10, 0.75, size=(2, 50)) assert(numpy.all(vals >= 0)) assert(numpy.shape(vals) == (2, 50)) @@ -128,8 +128,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestGeom(NumpyTestCase): - def check_rvs(self): +class TestGeom(TestCase): + def test_rvs(self): vals = stats.geom.rvs(0.75, size=(2, 50)) assert(numpy.all(vals >= 0)) assert(numpy.shape(vals) == (2, 50)) @@ -138,11 +138,11 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) - def check_pmf(self): + def test_pmf(self): vals = stats.geom.pmf([1,2,3],0.5) assert_array_almost_equal(vals,[0.5,0.25,0.125]) - def check_cdf_sf(self): + def test_cdf_sf(self): vals = stats.geom.cdf([1,2,3],0.5) vals_sf = stats.geom.sf([1,2,3],0.5) expected = array([0.5,0.75,0.875]) @@ -150,8 +150,8 @@ assert_array_almost_equal(vals_sf,1-expected) -class TestHypergeom(NumpyTestCase): - def check_rvs(self): +class TestHypergeom(TestCase): + def test_rvs(self): vals = stats.hypergeom.rvs(20, 10, 3, size=(2, 50)) assert(numpy.all(vals >= 0) & numpy.all(vals <= 3)) @@ -161,8 +161,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestLogser(NumpyTestCase): - def check_rvs(self): +class TestLogser(TestCase): + def test_rvs(self): vals = stats.logser.rvs(0.75, size=(2, 50)) assert(numpy.all(vals >= 1)) assert(numpy.shape(vals) == (2, 50)) @@ -171,8 +171,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestPoisson(NumpyTestCase): - def check_rvs(self): +class TestPoisson(TestCase): + def test_rvs(self): vals = stats.poisson.rvs(0.5, size=(2, 50)) assert(numpy.all(vals >= 0)) assert(numpy.shape(vals) == (2, 50)) @@ -181,8 +181,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestZipf(NumpyTestCase): - def check_rvs(self): +class TestZipf(TestCase): + def test_rvs(self): vals = stats.zipf.rvs(1.5, size=(2, 50)) assert(numpy.all(vals >= 1)) assert(numpy.shape(vals) == (2, 50)) @@ -191,8 +191,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestDLaplace(NumpyTestCase): - def check_rvs(self): +class TestDLaplace(TestCase): + def test_rvs(self): vals = stats.dlaplace.rvs(1.5 , size=(2, 50)) assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) @@ -200,8 +200,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestRvDiscrete(NumpyTestCase): - def check_rvs(self): +class TestRvDiscrete(TestCase): + def test_rvs(self): states = [-1,0,1,2,3,4] probability = [0.0,0.3,0.4,0.0,0.3,0.0] samples = 1000 @@ -211,9 +211,9 @@ for s,p in zip(states,probability): assert abs(sum(x == s)/float(samples) - p) < 0.05 -class TestExpon(NumpyTestCase): - def check_zero(self): +class TestExpon(TestCase): + def test_zero(self): assert_equal(stats.expon.pdf(0),1) if __name__ == "__main__": - NumpyTest('stats.distributions').run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/tests/test_morestats.py =================================================================== --- branches/testing_cleanup/scipy/stats/tests/test_morestats.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/tests/test_morestats.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -1,14 +1,11 @@ # Author: Travis Oliphant, 2002 # -from numpy.testing import * +from scipy.testing import * -set_package_path() -import scipy -import numpy -import stats -restore_path() +import scipy.stats as stats + import numpy as N from numpy.random import RandomState @@ -23,49 +20,49 @@ g9 = [1.002, 0.998, 0.996, 0.995, 0.996, 1.004, 1.004, 0.998, 0.999, 0.991] g10= [0.991, 0.995, 0.984, 0.994, 0.997, 0.997, 0.991, 0.998, 1.004, 0.997] -class TestShapiro(NumpyTestCase): - def check_basic(self): +class TestShapiro(TestCase): + def test_basic(self): x1 = [0.11,7.87,4.61,10.14,7.95,3.14,0.46, 4.43,0.21,4.75,0.71,1.52,3.24, 0.93,0.42,4.97,9.53,4.55,0.47,6.66] - w,pw = scipy.stats.shapiro(x1) + w,pw = stats.shapiro(x1) assert_almost_equal(w,0.90047299861907959,6) assert_almost_equal(pw,0.042089745402336121,6) x2 = [1.36,1.14,2.92,2.55,1.46,1.06,5.27,-1.11, 3.48,1.10,0.88,-0.51,1.46,0.52,6.20,1.69, 0.08,3.67,2.81,3.49] - w,pw = scipy.stats.shapiro(x2) + w,pw = stats.shapiro(x2) assert_almost_equal(w,0.9590270,6) assert_almost_equal(pw,0.52460,3) -class TestAnderson(NumpyTestCase): - def check_normal(self): +class TestAnderson(TestCase): + def test_normal(self): rs = RandomState(1234567890) x1 = rs.standard_exponential(size=50) x2 = rs.standard_normal(size=50) - A,crit,sig = scipy.stats.anderson(x1) + A,crit,sig = stats.anderson(x1) assert_array_less(crit[:-1], A) - A,crit,sig = scipy.stats.anderson(x2) + A,crit,sig = stats.anderson(x2) assert_array_less(A, crit[-2:]) - def check_expon(self): + def test_expon(self): rs = RandomState(1234567890) x1 = rs.standard_exponential(size=50) x2 = rs.standard_normal(size=50) - A,crit,sig = scipy.stats.anderson(x1,'expon') + A,crit,sig = stats.anderson(x1,'expon') assert_array_less(A, crit[-2:]) - A,crit,sig = scipy.stats.anderson(x2,'expon') + A,crit,sig = stats.anderson(x2,'expon') assert_array_less(crit[:-1], A) -class TestAnsari(NumpyTestCase): - def check_small(self): +class TestAnsari(TestCase): + def test_small(self): x = [1,2,3,3,4] y = [3,2,6,1,6,1,4,1] W, pval = stats.ansari(x,y) assert_almost_equal(W,23.5,11) assert_almost_equal(pval,0.13499256881897437,11) - def check_approx(self): + def test_approx(self): ramsay = N.array((111, 107, 100, 99, 102, 106, 109, 108, 104, 99, 101, 96, 97, 102, 107, 113, 116, 113, 110, 98)) parekh = N.array((107, 108, 106, 98, 105, 103, 110, 105, 104, @@ -74,13 +71,13 @@ assert_almost_equal(W,185.5,11) assert_almost_equal(pval,0.18145819972867083,11) - def check_exact(self): + def test_exact(self): W,pval = stats.ansari([1,2,3,4],[15,5,20,8,10,12]) assert_almost_equal(W,10.0,11) assert_almost_equal(pval,0.533333333333333333,7) -class TestBartlett(NumpyTestCase): - def check_data(self): +class TestBartlett(TestCase): + def test_data(self): args = [] for k in range(1,11): args.append(eval('g%d'%k)) @@ -88,8 +85,8 @@ assert_almost_equal(T,20.78587342806484,7) assert_almost_equal(pval,0.0136358632781,7) -class TestLevene(NumpyTestCase): - def check_data(self): +class TestLevene(TestCase): + def test_data(self): args = [] for k in range(1,11): args.append(eval('g%d'%k)) @@ -97,8 +94,8 @@ assert_almost_equal(W,1.7059176930008939,7) assert_almost_equal(pval,0.0990829755522,7) -class TestBinomTest(NumpyTestCase): - def check_data(self): +class TestBinomTest(TestCase): + def test_data(self): pval = stats.binom_test(100,250) assert_almost_equal(pval,0.0018833009350757682,11) pval = stats.binom_test(201,405) @@ -106,12 +103,12 @@ pval = stats.binom_test([682,243],p=3.0/4) assert_almost_equal(pval,0.38249155957481695,11) -class TestFindRepeats(NumpyTestCase): - def check_basic(self): +class TestFindRepeats(TestCase): + def test_basic(self): a = [1,2,3,4,1,2,3,4,1,2,5] - res,nums = scipy.stats.find_repeats(a) + res,nums = stats.find_repeats(a) assert_array_equal(res,[1,2,3,4]) assert_array_equal(nums,[3,3,2,2]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/stats/tests/test_stats.py =================================================================== --- branches/testing_cleanup/scipy/stats/tests/test_stats.py 2008-01-02 05:41:05 UTC (rev 3763) +++ branches/testing_cleanup/scipy/stats/tests/test_stats.py 2008-01-02 07:54:58 UTC (rev 3764) @@ -7,15 +7,13 @@ """ import sys -from numpy.testing import * -from numpy import * +from scipy.testing import * +from numpy import array, arange, zeros, ravel, float32, float64, power import numpy -import scipy -set_package_path() -import stats -restore_path() +import scipy.stats as stats + """ Numbers in docstrings begining with 'W' refer to the section numbers and headings found in the STATISTICS QUIZ of Leland Wilkinson. These are considered to be essential functionality. True testing and @@ -28,7 +26,7 @@ ## Datasets ## These data sets are from the nasty.dat sets used by Wilkinson ## for MISS, need to be able to represent missing values -## For completeness, I should write the relavant tests and count them as failures +## For completeness, I should write the relevant tests and count them as failures ## Somewhat acceptable, since this is still beta software. It would count as a ## good target for 1.0 status X = array([1,2,3,4,5,6,7,8,9],float) @@ -48,7 +46,7 @@ X8 = X7 * X X9 = X8 * X -class TestRound(NumpyTestCase): +class TestRound(TestCase): """ W.II. ROUND You should get the numbers 1 to 9. Many language compilers, @@ -71,7 +69,7 @@ statistical calculations. """ - def check_rounding0(self): + def test_rounding0(self): """ W.II.A.0. Print ROUND with only one digit. You should get the numbers 1 to 9. Many language compilers, @@ -83,22 +81,22 @@ y = round(ROUND[i]) assert_equal(y,i+1) - def check_rounding1(self): + def test_rounding1(self): """ W.II.A.1. Y = INT(2.6*7 -0.2) (Y should be 18)""" y = int(2.6*7 -0.2) assert_equal(y, 18) - def check_rounding2(self): + def test_rounding2(self): """ W.II.A.2. Y = 2-INT(EXP(LOG(SQR(2)*SQR(2)))) (Y should be 0)""" y=2-int(numpy.exp(numpy.log(numpy.sqrt(2.)*numpy.sqrt(2.)))) assert_equal(y,0) - def check_rounding3(self): + def test_rounding3(self): """ W.II.A.3. Y = INT(3-EXP(LOG(SQR(2)*SQR(2)))) (Y should be 1)""" y=(int(round((3-numpy.exp(numpy.log(numpy.sqrt(2.0)*numpy.sqrt(2.0))))))) assert_equal(y,1) -class TestBasicStats(NumpyTestCase): +class TestBasicStats(TestCase): """ W.II.C. Compute basic statistic on all the variables. The means should be the fifth value of all the variables (case FIVE). @@ -107,86 +105,86 @@ II. C. Basic Statistics """ - def check_meanX(self): - y = scipy.stats.mean(X) + def test_meanX(self): + y = stats.mean(X) assert_almost_equal(y, 5.0) - def check_stdX(self): - y = scipy.stats.std(X) + def test_stdX(self): + y = stats.std(X) assert_almost_equal(y, 2.738612788) - def check_tmeanX(self): - y = scipy.stats.tmean(X, (2, 8), (True, True)) + def test_tmeanX(self): + y = stats.tmean(X, (2, 8), (True, True)) assert_almost_equal(y, 5.0) - def check_tvarX(self): - y = scipy.stats.tvar(X, (2, 8), (True, True)) + def test_tvarX(self): + y = stats.tvar(X, (2, 8), (True, True)) assert_almost_equal(y, 4.6666666666666661) - def check_tstdX(self): - y = scipy.stats.tstd(X, (2, 8), (True, True)) + def test_tstdX(self): + y = stats.tstd(X, (2, 8), (True, True)) assert_almost_equal(y, 2.1602468994692865) - def check_meanZERO(self): - y = scipy.stats.mean(ZERO) + def test_meanZERO(self): + y = stats.mean(ZERO) assert_almost_equal(y, 0.0) - def check_stdZERO(self): - y = scipy.stats.std(ZERO) + def test_stdZERO(self): + y = stats.std(ZERO) assert_almost_equal(y, 0.0) ## Really need to write these tests to handle missing values properly -## def check_meanMISS(self): -## y = scipy.stats.mean(MISS) +## def test_meanMISS(self): +## y = stats.mean(MISS) ## assert_almost_equal(y, 0.0) ## -## def check_stdMISS(self): -## y = scipy.stats.stdev(MISS) +## def test_stdMISS(self): +## y = stats.stdev(MISS) ## assert_almost_equal(y, 0.0) - def check_meanBIG(self): - y = scipy.stats.mean(BIG) + def test_meanBIG(self): + y = stats.mean(BIG) assert_almost_equal(y, 99999995.00) - def check_stdBIG(self): - y = scipy.stats.std(BIG) + def test_stdBIG(self): + y = stats.std(BIG) assert_almost_equal(y, 2.738612788) - def check_meanLITTLE(self): - y = scipy.stats.mean(LITTLE) + def test_meanLITTLE(self): + y = stats.mean(LITTLE) assert_approx_equal(y, 0.999999950) - def check_stdLITTLE(self): - y = scipy.stats.std(LITTLE) + def test_stdLITTLE(self): + y = stats.std(LITTLE) assert_approx_equal(y, 2.738612788e-8) - def check_meanHUGE(self): - y = scipy.stats.mean(HUGE) + def test_meanHUGE(self): + y = stats.mean(HUGE) assert_approx_equal(y, 5.00000e+12) - def check_stdHUGE(self): - y = scipy.stats.std(HUGE) + def test_stdHUGE(self): + y = stats.std(HUGE) assert_approx_equal(y, 2.738612788e12) - def check_meanTINY(self): - y = scipy.stats.mean(TINY) + def test_meanTINY(self): + y = stats.mean(TINY) assert_almost_equal(y, 0.0) - def check_stdTINY(self): - y = scipy.stats.std(TINY) + def test_stdTINY(self): + y = stats.std(TINY) assert_almost_equal(y, 0.0) - def check_meanROUND(self): - y = scipy.stats.mean(ROUND) + def test_meanROUND(self): + y = stats.mean(ROUND) assert_approx_equal(y, 4.500000000) - def check_stdROUND(self): - y = scipy.stats.std(ROUND) + def test_stdROUND(self): + y = stats.std(ROUND) assert_approx_equal(y, 2.738612788) -class TestNanFunc(NumpyTestCase): +class TestNanFunc(TestCase): def __init__(self, *args, **kw): - NumpyTestCase.__init__(self, *args, **kw) + TestCase.__init__(self, *args, **kw) self.X = X.copy() self.Xall = X.copy() @@ -197,52 +195,52 @@ self.Xsome[0] = numpy.nan self.Xsomet = self.Xsomet[1:] - def check_nanmean_none(self): + def test_nanmean_none(self): """Check nanmean when no values are nan.""" m = stats.stats.nanmean(X) assert_approx_equal(m, X[4]) - def check_nanmean_some(self): + def test_nanmean_some(self): """Check nanmean when some values only are nan.""" m = stats.stats.nanmean(self.Xsome) assert_approx_equal(m, 5.5) - def check_nanmean_all(self): + def test_nanmean_all(self): """Check nanmean when all values are nan.""" m = stats.stats.nanmean(self.Xall) assert numpy.isnan(m) - def check_nanstd_none(self): + def test_nanstd_none(self): """Check nanstd when no values are nan.""" s = stats.stats.nanstd(self.X) assert_approx_equal(s, stats.stats.std(self.X)) - def check_nanstd_some(self): + def test_nanstd_some(self): """Check nanstd when some values only are nan.""" s = stats.stats.nanstd(self.Xsome) assert_approx_equal(s, stats.stats.std(self.Xsomet)) - def check_nanstd_all(self): + def test_nanstd_all(self): """Check nanstd when all values are nan.""" s = stats.stats.nanstd(self.Xall) assert numpy.isnan(s) - def check_nanmedian_none(self): + def test_nanmedian_none(self): """Check nanmedian when no values are nan.""" m = stats.stats.nanmedian(self.X) assert_approx_equal(m, stats.stats.median(self.X)) - def check_nanmedian_some(self): + def test_nanmedian_some(self): """Check nanmedian when some values only are nan.""" m = stats.stats.nanmedian(self.Xsome) assert_approx_equal(m, stats.stats.median(self.Xsomet)) - def check_nanmedian_all(self): + def test_nanmedian_all(self): """Check nanmedian when all values are nan.""" m = stats.stats.nanmedian(self.Xall) assert numpy.isnan(m) -class TestCorr(NumpyTestCase): +class TestCorr(TestCase): """ W.II.D. Compute a correlation matrix on all the variables. All the correlations, except for ZERO and MISS, shoud be exactly 1. @@ -250,172 +248,172 @@ other variables. The same should go for SPEARMAN corelations, if your program has them. """ - def check_pXX(self): - y = scipy.stats.pearsonr(X,X) + def test_pXX(self): + y = stats.pearsonr(X,X) r = y[0] assert_approx_equal(r,1.0) - def check_pXBIG(self): - y = scipy.stats.pearsonr(X,BIG) + def test_pXBIG(self): + y = stats.pearsonr(X,BIG) r = y[0] assert_approx_equal(r,1.0) - def check_pXLITTLE(self): - y = scipy.stats.pearsonr(X,LITTLE) + def test_pXLITTLE(self): + y = stats.pearsonr(X,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_pXHUGE(self): - y = scipy.stats.pearsonr(X,HUGE) + def test_pXHUGE(self): + y = stats.pearsonr(X,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_pXTINY(self): - y = scipy.stats.pearsonr(X,TINY) + def test_pXTINY(self): + y = stats.pearsonr(X,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pXROUND(self): - y = scipy.stats.pearsonr(X,ROUND) + def test_pXROUND(self): + y = stats.pearsonr(X,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGBIG(self): - y = scipy.stats.pearsonr(BIG,BIG) + def test_pBIGBIG(self): + y = stats.pearsonr(BIG,BIG) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGLITTLE(self): - y = scipy.stats.pearsonr(BIG,LITTLE) + def test_pBIGLITTLE(self): + y = stats.pearsonr(BIG,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGHUGE(self): - y = scipy.stats.pearsonr(BIG,HUGE) + def test_pBIGHUGE(self): + y = stats.pearsonr(BIG,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGTINY(self): - y = scipy.stats.pearsonr(BIG,TINY) + def test_pBIGTINY(self): + y = stats.pearsonr(BIG,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGROUND(self): - y = scipy.stats.pearsonr(BIG,ROUND) + def test_pBIGROUND(self): + y = stats.pearsonr(BIG,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pLITTLELITTLE(self): - y = scipy.stats.pearsonr(LITTLE,LITTLE) + def test_pLITTLELITTLE(self): + y = stats.pearsonr(LITTLE,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_pLITTLEHUGE(self): - y = scipy.stats.pearsonr(LITTLE,HUGE) + def test_pLITTLEHUGE(self): + y = stats.pearsonr(LITTLE,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_pLITTLETINY(self): - y = scipy.stats.pearsonr(LITTLE,TINY) + def test_pLITTLETINY(self): + y = stats.pearsonr(LITTLE,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pLITTLEROUND(self): - y = scipy.stats.pearsonr(LITTLE,ROUND) + def test_pLITTLEROUND(self): + y = stats.pearsonr(LITTLE,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pHUGEHUGE(self): - y = scipy.stats.pearsonr(HUGE,HUGE) + def test_pHUGEHUGE(self): + y = stats.pearsonr(HUGE,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_pHUGETINY(self): - y = scipy.stats.pearsonr(HUGE,TINY) + def test_pHUGETINY(self): + y = stats.pearsonr(HUGE,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pHUGEROUND(self): - y = scipy.stats.pearsonr(HUGE,ROUND) + def test_pHUGEROUND(self): + y = stats.pearsonr(HUGE,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pTINYTINY(self): - y = scipy.stats.pearsonr(TINY,TINY) + def test_pTINYTINY(self): + y = stats.pearsonr(TINY,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pTINYROUND(self): - y = scipy.stats.pearsonr(TINY,ROUND) + def test_pTINYROUND(self): + y = stats.pearsonr(TINY,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pROUNDROUND(self): - y = scipy.stats.pearsonr(ROUND,ROUND) + def test_pROUNDROUND(self): + y = stats.pearsonr(ROUND,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sXX(self): - y = scipy.stats.spearmanr(X,X) + def test_sXX(self): + y = stats.spearmanr(X,X) r = y[0] assert_approx_equal(r,1.0) - def check_sXBIG(self): - y = scipy.stats.spearmanr(X,BIG) + def test_sXBIG(self): + y = stats.spearmanr(X,BIG) r = y[0] assert_approx_equal(r,1.0) - def check_sXLITTLE(self): - y = scipy.stats.spearmanr(X,LITTLE) + def test_sXLITTLE(self): + y = stats.spearmanr(X,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_sXHUGE(self): - y = scipy.stats.spearmanr(X,HUGE) + def test_sXHUGE(self): + y = stats.spearmanr(X,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_sXTINY(self): - y = scipy.stats.spearmanr(X,TINY) + def test_sXTINY(self): + y = stats.spearmanr(X,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sXROUND(self): - y = scipy.stats.spearmanr(X,ROUND) + def test_sXROUND(self): + y = stats.spearmanr(X,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGBIG(self): - y = scipy.stats.spearmanr(BIG,BIG) + def test_sBIGBIG(self): + y = stats.spearmanr(BIG,BIG) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGLITTLE(self): - y = scipy.stats.spearmanr(BIG,LITTLE) + def test_sBIGLITTLE(self): + y = stats.spearmanr(BIG,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGHUGE(self): - y = scipy.stats.spearmanr(BIG,HUGE) + def test_sBIGHUGE(self): + y = stats.spearmanr(BIG,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGTINY(self): - y = scipy.stats.spearmanr(BIG,TINY) + def test_sBIGTINY(self): + y = stats.spearmanr(BIG,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGROUND(self): - y = scipy.stats.spearmanr(BIG,ROUND) + def test_sBIGROUND(self): + y = stats.spearmanr(BIG,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sLITTLELITTLE(self): - y = scipy.stats.spearmanr(LITTLE,LITTLE) + def test_sLITTLELITTLE(self): + y = stats.spearmanr(LITTLE,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_sLITTLEHUGE(self): - y = scipy.stats.spearmanr(LITTLE,HUGE) + def test_sLITTLEHUGE(self): + y = stats.spearmanr(LITTLE,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_sLITTLETINY(self): - y = scipy.stats.spearmanr(LITTLE,TINY) + def test_sLITTLETINY(self): + y = stats.spearmanr(LITTLE,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sLITTLEROUND(self): - y = scipy.stats.spearmanr(LITTLE,ROUND) + def test_sLITTLEROUND(self): + y = stats.spearmanr(LITTLE,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sHUGEHUGE(self): - y = scipy.stats.spearmanr(HUGE,HUGE) + def test_sHUGEHUGE(self): + y = stats.spearmanr(HUGE,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_sHUGETINY(self): - y = scipy.stats.spearmanr(HUGE,TINY) + def test_sHUGETINY(self): + y = stats.spearmanr(HUGE,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sHUGEROUND(self): - y = scipy.stats.spearmanr(HUGE,ROUND) + def test_sHUGEROUND(self): + y = stats.spearmanr(HUGE,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sTINYTINY(self): - y = scipy.stats.spearmanr(TINY,TINY) + def test_sTINYTINY(self): + y = stats.spearmanr(TINY,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sTINYROUND(self): - y = scipy.stats.spearmanr(TINY,ROUND) + def test_sTINYROUND(self): + y = stats.spearmanr(TINY,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sROUNDROUND(self): - y = scipy.stats.spearmanr(ROUND,ROUND) + def test_sROUNDROUND(self): + y = stats.spearmanr(ROUND,ROUND) r = y[0] assert_approx_equal(r,1.0) @@ -429,13 +427,13 @@ ### I need to figure out how to do this one. -class TestRegression(NumpyTestCase): - def check_linregressBIGX(self): +class TestRegression(TestCase): + def test_linregressBIGX(self): """ W.II.F. Regress BIG on X. The constant should be 99999990 and the regression coefficient should be 1. """ - y = scipy.stats.linregress(X,BIG) + y = stats.linregress(X,BIG) intercept = y[1] r=y[2] assert_almost_equal(intercept,99999990) @@ -453,13 +451,13 @@ ## The datasets X1 . . X9 are at the top of the file. - def check_regressXX(self): + def test_regressXX(self): """ W.IV.B. Regress X on X. The constant should be exactly 0 and the regression coefficient should be 1. This is a perfectly valid regression. The program should not complain. """ - y = scipy.stats.linregress(X,X) + y = stats.linregress(X,X) intercept = y[1] r=y[2] assert_almost_equal(intercept,0.0) @@ -471,14 +469,14 @@ ## fundamental regression error. ### Need to figure out how to handle multiple linear regression. Not obvious - def check_regressZEROX(self): + def test_regressZEROX(self): """ W.IV.D. Regress ZERO on X. The program should inform you that ZERO has no variance or it should go ahead and compute the regression and report a correlation and total sum of squares of exactly 0. """ - y = scipy.stats.linregress(X,ZERO) + y = stats.linregress(X,ZERO) intercept = y[1] r=y[2] assert_almost_equal(intercept,0.0) @@ -494,9 +492,9 @@ ################################################## ### Test for sum -class TestGMean(NumpyTestCase): +class TestGMean(TestCase): - def check_1D_list(self): + def test_1D_list(self): a = (1,2,3,4) actual= stats.gmean(a) desired = power(1*2*3*4,1./4.) @@ -505,7 +503,7 @@ desired1 = stats.gmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=14) - def check_1D_array(self): + def test_1D_array(self): a = array((1,2,3,4), float32) actual= stats.gmean(a) desired = power(1*2*3*4,1./4.) @@ -514,7 +512,7 @@ desired1 = stats.gmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=7) - def check_2D_array_default(self): + def test_2D_array_default(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) @@ -525,7 +523,7 @@ desired1 = stats.gmean(a,axis=0) assert_array_almost_equal(actual, desired1, decimal=14) - def check_2D_array_dim1(self): + def test_2D_array_dim1(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) @@ -534,13 +532,13 @@ desired = array((v,v,v)) assert_array_almost_equal(actual, desired, decimal=14) - def check_large_values(self): + def test_large_values(self): a = array([1e100, 1e200, 1e300]) actual = stats.gmean(a) assert_approx_equal(actual, 1e200, significant=14) -class TestHMean(NumpyTestCase): - def check_1D_list(self): +class TestHMean(TestCase): + def test_1D_list(self): a = (1,2,3,4) actual= stats.hmean(a) desired = 4. / (1./1 + 1./2 + 1./3 + 1./4) @@ -548,7 +546,7 @@ desired1 = stats.hmean(array(a),axis=-1) assert_almost_equal(actual, desired1, decimal=14) - def check_1D_array(self): + def test_1D_array(self): a = array((1,2,3,4), float64) actual= stats.hmean(a) desired = 4. / (1./1 + 1./2 + 1./3 + 1./4) @@ -557,7 +555,7 @@ desired1 = stats.hmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=14) - def check_2D_array_default(self): + def test_2D_array_default(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) @@ -568,7 +566,7 @@ actual1 = stats.hmean(a,axis=0) assert_array_almost_equal(actual1, desired, decimal=14) - def check_2D_array_dim1(self): + def test_2D_array_dim1(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) @@ -579,8 +577,8 @@ assert_array_almost_equal(actual1, desired1, decimal=14) -class TestMean(NumpyTestCase): - def check_basic(self): +class TestMean(TestCase): + def test_basic(self): a = [3,4,5,10,-3,-5,6] af = [3.,4,5,10,-3,-5,-6] Na = len(a) @@ -594,7 +592,7 @@ mn2 += el / float(Naf) assert_almost_equal(stats.mean(af),mn2,11) - def check_2d(self): + def test_2d(self): a = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [8.0, 12.0, 7.0]] @@ -611,15 +609,15 @@ mn2 /= N2 assert_almost_equal(stats.mean(a, axis=1), mn2, decimal=13) - def check_ravel(self): + def test_ravel(self): a = rand(5,3,5) A = 0 for val in ravel(a): A += val assert_almost_equal(stats.mean(a,axis=None),A/(5*3.0*5)) -class TestMedian(NumpyTestCase): - def check_basic(self): +class TestMedian(TestCase): + def test_basic(self): a1 = [3,4,5,10,-3,-5,6] a2 = [3,-6,-2,8,7,4,2,1] a3 = [3.,4,5,10,-3,-5,-6,7.0] @@ -627,18 +625,18 @@ assert_equal(stats.median(a2),2.5) assert_equal(stats.median(a3),3.5) -class TestPercentile(NumpyTestCase): +class TestPercentile(TestCase): def setUp(self): self.a1 = [3,4,5,10,-3,-5,6] self.a2 = [3,-6,-2,8,7,4,2,1] self.a3 = [3.,4,5,10,-3,-5,-6,7.0] - def check_median(self): + def test_median(self): assert_equal(stats.median(self.a1), 4) assert_equal(stats.median(self.a2), 2.5) assert_equal(stats.median(self.a3), 3.5) - def check_percentile(self): + def test_percentile(self): x = arange(8) * 0.5 assert_equal(stats.scoreatpercentile(x, 0), 0.) assert_equal(stats.scoreatpercentile(x, 100), 3.5) @@ -654,14 +652,14 @@ [1,1,1]) -class TestStd(NumpyTestCase): - def check_basic(self): +class TestStd(TestCase): + def test_basic(self): a = [3,4,5,10,-3,-5,6] b = [3,4,5,10,-3,-5,-6] assert_almost_equal(stats.std(a),5.2098807225172772,11) assert_almost_equal(stats.std(b),5.9281411203561225,11) - def check_2d(self): + def test_2d(self): a = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [8.0, 12.0, 7.0]] @@ -673,109 +671,109 @@ assert_array_almost_equal(stats.std(a,axis=1),b2,11) -class TestCMedian(NumpyTestCase): - def check_basic(self): +class TestCMedian(TestCase): + def test_basic(self): data = [1,2,3,1,5,3,6,4,3,2,4,3,5,2.0] assert_almost_equal(stats.cmedian(data,5),3.2916666666666665) assert_almost_equal(stats.cmedian(data,3),3.083333333333333) assert_almost_equal(stats.cmedian(data),3.0020020020020022) -class TestMedian(NumpyTestCase): - def check_basic(self): +class TestMedian(TestCase): + def test_basic(self): data1 = [1,3,5,2,3,1,19,-10,2,4.0] data2 = [3,5,1,10,23,-10,3,-2,6,8,15] assert_almost_equal(stats.median(data1),2.5) assert_almost_equal(stats.median(data2),5) -class TestMode(NumpyTestCase): - def check_basic(self): +class TestMode(TestCase): + def test_basic(self): data1 = [3,5,1,10,23,3,2,6,8,6,10,6] vals = stats.mode(data1) assert_almost_equal(vals[0][0],6) assert_almost_equal(vals[1][0],3) -class TestVariability(NumpyTestCase): +class TestVariability(TestCase): """ Comparison numbers are found using R v.1.5.1 note that length(testcase) = 4 """ testcase = [1,2,3,4] - def check_std(self): - y = scipy.stats.std(self.testcase) + def test_std(self): + y = stats.std(self.testcase) assert_approx_equal(y,1.290994449) - def check_var(self): + def test_var(self): """ var(testcase) = 1.666666667 """ - #y = scipy.stats.var(self.shoes[0]) + #y = stats.var(self.shoes[0]) #assert_approx_equal(y,6.009) - y = scipy.stats.var(self.testcase) + y = stats.var(self.testcase) assert_approx_equal(y,1.666666667) - def check_samplevar(self): + def test_samplevar(self): """ R does not have 'samplevar' so the following was used var(testcase)*(4-1)/4 where 4 = length(testcase) """ - #y = scipy.stats.samplevar(self.shoes[0]) + #y = stats.samplevar(self.shoes[0]) #assert_approx_equal(y,5.4081) - y = scipy.stats.samplevar(self.testcase) + y = stats.samplevar(self.testcase) assert_approx_equal(y,1.25) - def check_samplestd(self): - #y = scipy.stats.samplestd(self.shoes[0]) + def test_samplestd(self): + #y = stats.samplestd(self.shoes[0]) #assert_approx_equal(y,2.325532197) - y = scipy.stats.samplestd(self.testcase) + y = stats.samplestd(self.testcase) assert_approx_equal(y,1.118033989) - def check_signaltonoise(self): + def test_signaltonoise(self): """ this is not in R, so used mean(testcase,axis=0)/(sqrt(var(testcase)*3/4)) """ - #y = scipy.stats.signaltonoise(self.shoes[0]) + #y = stats.signaltonoise(self.shoes[0]) #assert_approx_equal(y,4.5709967) - y = scipy.stats.signaltonoise(self.testcase) + y = stats.signaltonoise(self.testcase) assert_approx_equal(y,2.236067977) - def check_stderr(self): + def test_stderr(self): """ this is not in R, so used sqrt(var(testcase))/sqrt(4) """ -## y = scipy.stats.stderr(self.shoes[0]) +## y = stats.stderr(self.shoes[0]) ## assert_approx_equal(y,0.775177399) - y = scipy.stats.stderr(self.testcase) + y = stats.stderr(self.testcase) assert_approx_equal(y,0.6454972244) - def check_sem(self): + def test_sem(self): """ this is not in R, so used sqrt(var(testcase)*3/4)/sqrt(3) """ - #y = scipy.stats.sem(self.shoes[0]) + #y = stats.sem(self.shoes[0]) #assert_approx_equal(y,0.775177399) - y = scipy.stats.sem(self.testcase) + y = stats.sem(self.testcase) assert_approx_equal(y,0.6454972244) - def check_z(self): + def test_z(self): """ not in R, so used (10-mean(testcase,axis=0))/sqrt(var(testcase)*3/4) """ - y = scipy.stats.z(self.testcase,scipy.stats.mean(self.testcase)) + y = stats.z(self.testcase,stats.mean(self.testcase)) assert_almost_equal(y,0.0) - def check_zs(self): + def test_zs(self): """ not in R, so tested by using (testcase[i]-mean(testcase,axis=0))/sqrt(var(testcase)*3/4) """ - y = scipy.stats.zs(self.testcase) + y = stats.zs(self.testcase) desired = ([-1.3416407864999, -0.44721359549996 , 0.44721359549996 , 1.3416407864999]) assert_array_almost_equal(desired,y,decimal=12) -class TestMoments(NumpyTestCase): +class TestMoments(TestCase): """ Comparison numbers are found using R v.1.5.1 note that length(testcase) = 4 @@ -787,56 +785,56 @@ """ testcase = [1,2,3,4] testmathworks = [1.165 , 0.6268, 0.0751, 0.3516, -0.6965] - def check_moment(self): + def test_moment(self): """ mean((testcase-mean(testcase))**power,axis=0),axis=0))**power))""" - y = scipy.stats.moment(self.testcase,1) + y = stats.moment(self.testcase,1) assert_approx_equal(y,0.0,10) - y = scipy.stats.moment(self.testcase,2) + y = stats.moment(self.testcase,2) assert_approx_equal(y,1.25) - y = scipy.stats.moment(self.testcase,3) + y = stats.moment(self.testcase,3) assert_approx_equal(y,0.0) - y = scipy.stats.moment(self.testcase,4) + y = stats.moment(self.testcase,4) assert_approx_equal(y,2.5625) - def check_variation(self): + def test_variation(self): """ variation = samplestd/mean """ -## y = scipy.stats.variation(self.shoes[0]) +## y = stats.variation(self.shoes[0]) ## assert_approx_equal(y,21.8770668) - y = scipy.stats.variation(self.testcase) + y = stats.variation(self.testcase) assert_approx_equal(y,0.44721359549996, 10) - def check_skewness(self): + def test_skewness(self): """ sum((testmathworks-mean(testmathworks,axis=0))**3,axis=0)/((sqrt(var(testmathworks)*4/5))**3)/5 """ - y = scipy.stats.skew(self.testmathworks) + y = stats.skew(self.testmathworks) assert_approx_equal(y,-0.29322304336607,10) - y = scipy.stats.skew(self.testmathworks,bias=0) + y = stats.skew(self.testmathworks,bias=0) assert_approx_equal(y,-0.437111105023940,10) - y = scipy.stats.skew(self.testcase) + y = stats.skew(self.testcase) assert_approx_equal(y,0.0,10) - def check_kurtosis(self): + def test_kurtosis(self): """ sum((testcase-mean(testcase,axis=0))**4,axis=0)/((sqrt(var(testcase)*3/4))**4)/4 sum((test2-mean(testmathworks,axis=0))**4,axis=0)/((sqrt(var(testmathworks)*4/5))**4)/5 Set flags for axis = 0 and fisher=0 (Pearson's defn of kurtosis for compatiability with Matlab) """ - y = scipy.stats.kurtosis(self.testmathworks,0,fisher=0,bias=1) + y = stats.kurtosis(self.testmathworks,0,fisher=0,bias=1) assert_approx_equal(y, 2.1658856802973,10) # Note that MATLAB has confusing docs for the following case # kurtosis(x,0) gives an unbiased estimate of Pearson's skewness # kurtosis(x) gives a biased estimate of Fisher's skewness (Pearson-3) # The MATLAB docs imply that both should give Fisher's - y = scipy.stats.kurtosis(self.testmathworks,fisher=0,bias=0) + y = stats.kurtosis(self.testmathworks,fisher=0,bias=0) assert_approx_equal(y, 3.663542721189047,10) - y = scipy.stats.kurtosis(self.testcase,0,0) + y = stats.kurtosis(self.testcase,0,0) assert_approx_equal(y,1.64) -class TestThreshold(NumpyTestCase): - def check_basic(self): +class TestThreshold(TestCase): + def test_basic(self): a = [-1,2,3,4,5,-1,-2] assert_array_equal(stats.threshold(a),a) assert_array_equal(stats.threshold(a,3,None,0), @@ -847,4 +845,4 @@ [0,2,3,4,0,0,0]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() From scipy-svn at scipy.org Wed Jan 2 16:31:52 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 2 Jan 2008 15:31:52 -0600 (CST) Subject: [Scipy-svn] r3765 - trunk/scipy/ndimage/tests Message-ID: <20080102213152.4B76939C01F@new.scipy.org> Author: jarrod.millman Date: 2008-01-02 15:31:45 -0600 (Wed, 02 Jan 2008) New Revision: 3765 Removed: trunk/scipy/ndimage/tests/test_segment.py Log: removing redundant test Deleted: trunk/scipy/ndimage/tests/test_segment.py =================================================================== --- trunk/scipy/ndimage/tests/test_segment.py 2008-01-02 07:54:58 UTC (rev 3764) +++ trunk/scipy/ndimage/tests/test_segment.py 2008-01-02 21:31:45 UTC (rev 3765) @@ -1,142 +0,0 @@ - -import numpy as N -from numpy.testing import * -import scipy.ndimage.segment as S - -inputname = 'slice112.raw' - -import os -filename = os.path.join(os.path.split(__file__)[0],inputname) - - -def shen_castan(image, IIRFilter=0.8, scLow=0.3, window=7, lowThreshold=220+2048, highThreshold=600+2048, dust=16): - labeledEdges, numberObjects = S.shen_castan_edges(scLow, IIRFilter, window, lowThreshold, highThreshold, image) - # allocated struct array for edge object measures. for now just the rect bounding box - ROIList = N.zeros(numberObjects, dtype=S.objstruct) - # return the bounding box for each connected edge - S.get_object_stats(labeledEdges, ROIList) - return labeledEdges, ROIList[ROIList['Area']>dust] - -def sobel(image, sLow=0.3, tMode=1, lowThreshold=220+2048, highThreshold=600+2048, BPHigh=10.0, apearture=21, dust=16): - # get sobel edge points. return edges that are labeled (1..numberObjects) - labeledEdges, numberObjects = S.sobel_edges(sLow, tMode, lowThreshold, highThreshold, BPHigh, apearture, image) - # allocated struct array for edge object measures. for now just the rect bounding box - ROIList = N.zeros(numberObjects, dtype=S.objstruct) - # return the bounding box for each connected edge - S.get_object_stats(labeledEdges, ROIList) - # thin (medial axis transform) of the sobel edges as the sobel produces a 'band edge' - S.morpho_thin_filt(labeledEdges, ROIList) - return labeledEdges, ROIList[ROIList['Area']>dust] - -def canny(image, cSigma=1.0, cLow=0.5, cHigh=0.8, tMode=1, lowThreshold=220+2048, highThreshold=600+2048, - BPHigh=10.0, apearture=21, dust=16): - # get canny edge points. return edges that are labeled (1..numberObjects) - labeledEdges, numberObjects = S.canny_edges(cSigma, cLow, cHigh, tMode, lowThreshold, highThreshold, - BPHigh, apearture, image) - # allocated struct array for edge object measures. for now just the rect bounding box - ROIList = N.zeros(numberObjects, dtype=S.objstruct) - # return the bounding box for each connected edge - S.get_object_stats(labeledEdges, ROIList) - return labeledEdges, ROIList[ROIList['Area']>dust] - -def get_shape_mask(labeledEdges, ROIList): - # pass in Sobel morph-thinned labeled edge image (LEI) and ROIList - # GetShapeMask will augment the ROI list - # labeledEdges is the original edge image and overwritten as mask image - # maskImage is the mask that is used for blob texture / pixel features - S.build_boundary(labeledEdges, ROIList) - return - -def get_voxel_measures(rawImage, labeledEdges, ROIList): - # - # pass raw image, labeled mask and the partially filled ROIList - # VoxelMeasures will fill the voxel features in the list - # - S.voxel_measures(rawImage, labeledEdges, ROIList) - return - -def get_texture_measures(rawImage, labeledEdges, ROIList): - # - # pass raw image, labeled mask and the partially filled ROIList - # VoxelMeasures will fill the texture (Law's, co-occurence, Gabor) features in the list - # - S.texture_measures(rawImage, labeledEdges, ROIList) - return - -def segment_regions(): - # get slice from the CT volume - image = get_slice(filename) - # need a copy of original image as filtering will occur on the extracted slice - sourceImage = image.copy() - # Sobel is the first level segmenter. Sobel magnitude and MAT (medial axis transform) - # followed by connected component analysis. What is returned is labeled edges and the object list - labeledMask, ROIList = sobel(image) - # From the labeled edges and the object list get the labeled mask for each blob object - get_shape_mask(labeledMask, ROIList) - # Use the labeled mask and source image (raw) to get voxel features - get_voxel_measures(sourceImage, labeledMask, ROIList) - # Use the labeled mask and source image (raw) to get texture features - get_texture_measures(sourceImage, labeledMask, ROIList) - return sourceImage, labeledMask, ROIList - -def grow_regions(): - # get slice from the CT volume - image = get_slice(filename) - regionMask, numberRegions = region_grow(image) - return regionMask, numberRegions - - -def region_grow(image, lowThreshold=220+2048, highThreshold=600+2048, open=7, close=7): - # morphology filters need to be clipped to 11 max and be odd - regionMask, numberRegions = S.region_grow(lowThreshold, highThreshold, close, open, image) - return regionMask, numberRegions - - -def get_slice(imageName='junk.raw', bytes=2, rows=512, columns=512): - # get a slice alrady extracted from the CT volume - #image = open(imageName, 'rb') - #slice = image.read(rows*columns*bytes) - #values = struct.unpack('h'*rows*columns, slice) - #ImageSlice = N.array(values, dtype=float).reshape(rows, columns) - - ImageSlice = N.fromfile(imageName, dtype=N.uint16).reshape(rows, columns); - - # clip the ends for this test CT image file as the spine runs off the end of the image - ImageSlice[505:512, :] = 0 - return (ImageSlice).astype(float) - -def get_slice2(image_name='junk.raw', bytes=2, shape=(512,512)): - import mmap - file = open(image_name, 'rb') - mm = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) - slice = N.frombuffer(mm, dtype='u%d' % bytes).reshape(shape) - slice = slice.astype(float) - slice[505:512,:] = 0 - return slice - -def save_slice(mySlice, filename='junk.raw', bytes=4): - # just save the slice to a fixed file - slice = mySlice.astype('u%d' % bytes) - slice.tofile(filename) - - -class TestSegment(NumpyTestCase): - def test1(self): - image = get_slice(filename) - sourceImage = image.copy() - edges, objects = sobel(image) - get_shape_mask(edges, objects) - get_voxel_measures(sourceImage, edges, objects) - get_texture_measures(sourceImage, edges, objects) - - def test2(self): - sourceImage, labeledMask, ROIList = segment_regions() - - def test3(self): - regionMask, numberRegions = grow_regions() - print regionMask.max() - #save_slice(regionMask, 'regionMask.raw') - - -if __name__ == "__main__": - NumpyTest().run() From scipy-svn at scipy.org Wed Jan 2 18:20:31 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 2 Jan 2008 17:20:31 -0600 (CST) Subject: [Scipy-svn] r3766 - trunk/scipy/io/matlab Message-ID: <20080102232031.5565239C1C5@new.scipy.org> Author: wnbell Date: 2008-01-02 17:20:18 -0600 (Wed, 02 Jan 2008) New Revision: 3766 Modified: trunk/scipy/io/matlab/mio4.py Log: use COO for faster sparse writing Modified: trunk/scipy/io/matlab/mio4.py =================================================================== --- trunk/scipy/io/matlab/mio4.py 2008-01-02 21:31:45 UTC (rev 3765) +++ trunk/scipy/io/matlab/mio4.py 2008-01-02 23:20:18 UTC (rev 3766) @@ -299,22 +299,22 @@ ''' Sparse matrices are 2D See docstring for Mat4SparseGetter ''' - imagf = self.arr.dtype.kind == 'c' - nnz = self.arr.nnz - ijd = N.zeros((nnz+1, 3+imagf), dtype='f8') - for i in range(nnz): - ijd[i,0], ijd[i,1] = self.arr.rowcol(i) - ijd[:-1,0:2] += 1 # 1 based indexing + A = self.arr.tocoo() #convert to sparse COO format (ijv) + imagf = A.dtype.kind == 'c' + ijv = N.zeros((A.nnz + 1, 3+imagf), dtype='f8') + ijv[:-1,0] = A.row + ijv[:-1,1] = A.col + ijv[:-1,0:2] += 1 # 1 based indexing if imagf: - ijd[:-1,2] = self.arr.data.real - ijd[:-1,3] = self.arr.data.imag + ijv[:-1,2] = A.data.real + ijv[:-1,3] = A.data.imag else: - ijd[:-1,2] = self.arr.data - ijd[-1,0:2] = self.arr.shape + ijv[:-1,2] = A.data + ijv[-1,0:2] = A.shape self.write_header(P=miDOUBLE, T=mxSPARSE_CLASS, - dims=ijd.shape) - self.write_bytes(ijd) + dims=ijv.shape) + self.write_bytes(ijv) def matrix_writer_factory(stream, arr, name): From scipy-svn at scipy.org Wed Jan 2 19:03:05 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 2 Jan 2008 18:03:05 -0600 (CST) Subject: [Scipy-svn] r3767 - in trunk/scipy/sparse: . tests Message-ID: <20080103000305.B7BA539C12F@new.scipy.org> Author: wnbell Date: 2008-01-02 18:02:34 -0600 (Wed, 02 Jan 2008) New Revision: 3767 Modified: trunk/scipy/sparse/bsr.py trunk/scipy/sparse/compressed.py trunk/scipy/sparse/csc.py trunk/scipy/sparse/csr.py trunk/scipy/sparse/tests/test_base.py Log: made has_sorted_indices a property Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-02 23:20:18 UTC (rev 3766) +++ trunk/scipy/sparse/bsr.py 2008-01-03 00:02:34 UTC (rev 3767) @@ -441,7 +441,7 @@ def sort_indices(self): """Sort the indices of this matrix *in place* """ - if self.has_sorted_indices(): + if self.has_sorted_indices: return from csr import csr_matrix @@ -460,7 +460,7 @@ self.data[:] = self.data[proxy.data] self.indices[:] = proxy.indices - self._has_sorted_indices = True + self.has_sorted_indices = True def prune(self): """ Remove empty space after all non-zero elements. Modified: trunk/scipy/sparse/compressed.py =================================================================== --- trunk/scipy/sparse/compressed.py 2008-01-02 23:20:18 UTC (rev 3766) +++ trunk/scipy/sparse/compressed.py 2008-01-03 00:02:34 UTC (rev 3767) @@ -414,6 +414,7 @@ col = key[1] #TODO implement CSR[ [1,2,3], X ] with sparse matmat + #TODO make use of sorted indices if isintlike(row) and isintlike(col): return self._get_single_element(row,col) @@ -486,9 +487,9 @@ warn('changing the sparsity structure of a %s_matrix is expensive. ' \ 'lil_matrix is more efficient.' % self.format, \ SparseEfficiencyWarning) + self.sort_indices() - #no harm if not sorted newindx = self.indices[start:end].searchsorted(minor_index) newindx += start @@ -567,18 +568,26 @@ self.prune() #nnz may have changed - def has_sorted_indices(self): + + def __get_sorted(self): """Determine whether the matrix has sorted indices + + True if the indices of the matrix are in + sorted order, False otherwise. """ #first check to see if result was cached if not hasattr(self,'_has_sorted_indices'): fn = sparsetools.csr_has_sorted_indices - self._has_sorted_indices = \ + self.__has_sorted_indices = \ fn( len(self.indptr) - 1, self.indptr, self.indices) + return self.__has_sorted_indices - return self._has_sorted_indices + def __set_sorted(self,val): + self.__has_sorted_indices = bool(val) + has_sorted_indices = property(fget=__get_sorted, fset=__set_sorted) + def sorted_indices(self): """Return a copy of this matrix with sorted indices """ @@ -594,10 +603,10 @@ """Sort the indices of this matrix *in place* """ - if not self.has_sorted_indices(): + if not self.has_sorted_indices: fn = sparsetools.csr_sort_indices fn( len(self.indptr) - 1, self.indptr, self.indices, self.data) - self._has_sorted_indices = True + self.has_sorted_indices = True def ensure_sorted_indices(self, inplace=False): """Return a copy of this matrix where the column indices are sorted @@ -677,7 +686,9 @@ indices = indices.copy() data = data.copy() - return self.__class__((data, indices, indptr), shape=out_shape) + A = self.__class__((data, indices, indptr), shape=out_shape) + A.has_sorted_indices = True + return A def _get_submatrix( self, shape0, shape1, slice0, slice1 ): """Return a submatrix of this matrix (new matrix is created).""" Modified: trunk/scipy/sparse/csc.py =================================================================== --- trunk/scipy/sparse/csc.py 2008-01-02 23:20:18 UTC (rev 3766) +++ trunk/scipy/sparse/csc.py 2008-01-03 00:02:34 UTC (rev 3767) @@ -128,7 +128,7 @@ from csr import csr_matrix A = csr_matrix((data, indices, indptr), self.shape) - A._has_sorted_indices = True + A.has_sorted_indices = True return A def tobsr(self, blocksize=None): Modified: trunk/scipy/sparse/csr.py =================================================================== --- trunk/scipy/sparse/csr.py 2008-01-02 23:20:18 UTC (rev 3766) +++ trunk/scipy/sparse/csr.py 2008-01-03 00:02:34 UTC (rev 3767) @@ -144,7 +144,7 @@ from csc import csc_matrix A = csc_matrix((data, indices, indptr), self.shape) - A._has_sorted_indices = True + A.has_sorted_indices = True return A def tobsr(self,blocksize=None,copy=True): Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-01-02 23:20:18 UTC (rev 3766) +++ trunk/scipy/sparse/tests/test_base.py 2008-01-03 00:02:34 UTC (rev 3767) @@ -33,6 +33,7 @@ #TODO check that spmatrix( ... , copy=X ) is respected #TODO test repr(spmatrix) #TODO test prune +#TODO test has_sorted_indices class _TestCommon: """test common functionality shared by all sparse formats""" From scipy-svn at scipy.org Wed Jan 2 19:15:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 2 Jan 2008 18:15:12 -0600 (CST) Subject: [Scipy-svn] r3768 - trunk/scipy/sparse Message-ID: <20080103001512.5CD8039C133@new.scipy.org> Author: wnbell Date: 2008-01-02 18:14:58 -0600 (Wed, 02 Jan 2008) New Revision: 3768 Modified: trunk/scipy/sparse/csr.py Log: sort inplace when converting to lil Modified: trunk/scipy/sparse/csr.py =================================================================== --- trunk/scipy/sparse/csr.py 2008-01-03 00:02:34 UTC (rev 3767) +++ trunk/scipy/sparse/csr.py 2008-01-03 00:14:58 UTC (rev 3768) @@ -114,10 +114,10 @@ from lil import lil_matrix lil = lil_matrix(self.shape,dtype=self.dtype) - csr = self.sorted_indices() #lil_matrix needs sorted rows + self.sort_indices() #lil_matrix needs sorted rows rows,data = lil.rows,lil.data - ptr,ind,dat = csr.indptr,csr.indices,csr.data + ptr,ind,dat = self.indptr,self.indices,self.data for n in xrange(self.shape[0]): start = ptr[n] From scipy-svn at scipy.org Thu Jan 3 14:06:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 13:06:02 -0600 (CST) Subject: [Scipy-svn] r3770 - in trunk/scipy/io: matlab tests Message-ID: <20080103190602.DAFF739C020@new.scipy.org> Author: stefan Date: 2008-01-03 13:05:43 -0600 (Thu, 03 Jan 2008) New Revision: 3770 Modified: trunk/scipy/io/matlab/mio5.py trunk/scipy/io/tests/test_mio.py Log: Fix Matlab v5 sparse array writer. Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-01-03 09:20:06 UTC (rev 3769) +++ trunk/scipy/io/matlab/mio5.py 2008-01-03 19:05:43 UTC (rev 3770) @@ -603,7 +603,8 @@ af['nzmax'] = nzmax self.write_dtype(af) # write array shape - self.arr=N.atleast_2d(self.arr) + if self.arr.ndim < 2: + self.arr=N.atleast_2d(self.arr) self.write_element(N.array(self.arr.shape, dtype='i4')) # write name self.write_element(N.ndarray(shape=len(self.name), dtype='S1', buffer=self.name)) @@ -663,26 +664,23 @@ def write(self): ''' Sparse matrices are 2D - See docstring for Mat5SparseGetter + ''' - imagf = self.arr.dtype.kind == 'c' - N = self.arr.nnz - ijd = N.zeros((N+1, 3+imagf), dtype='f8') - for i in range(N): - ijd[i,0], ijd[i,1] = self.arr.rowcol(i) - ijd[:-1,0:2] += 1 # 1 based indexing - if imagf: - ijd[:-1,2] = self.arr.data.real - ijd[:-1,3] = self.arr.data.imag - else: - ijd[:-1,2] = self.arr.data - ijd[-1,0:2] = self.arr.shape - self.write_header(P=miDOUBLE, - T=mxSPARSE_CLASS, - dims=ijd.shape) - self.write_bytes(ijd) + A = self.arr.tocsc() # convert to sparse COO format (ijv) + is_complex = (A.dtype.kind == 'c') + nz = A.nnz + self.write_header(mclass=mxSPARSE_CLASS, + is_complex=is_complex, + nzmax=nz) + self.write_element(A.indices.astype('i4')) + self.write_element(A.indptr.astype('i4')) + self.write_element(A.data.real) + if is_complex: + self.write_element(A.data.imag) + self.update_matrix_tag() + class Mat5WriterGetter(object): ''' Wraps stream and options, provides methods for getting Writer objects ''' def __init__(self, stream, unicode_strings): Modified: trunk/scipy/io/tests/test_mio.py =================================================================== --- trunk/scipy/io/tests/test_mio.py 2008-01-03 09:20:06 UTC (rev 3769) +++ trunk/scipy/io/tests/test_mio.py 2008-01-03 19:05:43 UTC (rev 3770) @@ -11,8 +11,8 @@ import scipy.sparse as SP set_package_path() -from matlab.mio import loadmat, savemat -from matlab.mio5 import mat_obj, mat_struct +from io.matlab.mio import loadmat, savemat +from io.matlab.mio5 import mat_obj, mat_struct restore_path() try: # Python 2.3 support @@ -165,7 +165,14 @@ case_table5_rt = [ {'name': '3dmatrix', 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }] + }, + {'name': 'sparsefloat', + 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, + }, + {'name': 'sparsecomplex', + 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, + }, + ] st = mat_struct() st.stringfield = u'Rats live on no evil star.' st.doublefield = array([sqrt(2),exp(1),pi]) From scipy-svn at scipy.org Thu Jan 3 14:22:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 13:22:32 -0600 (CST) Subject: [Scipy-svn] r3771 - in trunk/scipy/io: matlab matlab/tests tests Message-ID: <20080103192232.4300E39C12F@new.scipy.org> Author: stefan Date: 2008-01-03 13:21:53 -0600 (Thu, 03 Jan 2008) New Revision: 3771 Added: trunk/scipy/io/matlab/tests/ trunk/scipy/io/matlab/tests/data/ trunk/scipy/io/matlab/tests/test_mio.py Removed: trunk/scipy/io/tests/data/ trunk/scipy/io/tests/test_mio.py Modified: trunk/scipy/io/matlab/setup.py Log: Restructure io.matlab unittests. Modified: trunk/scipy/io/matlab/setup.py =================================================================== --- trunk/scipy/io/matlab/setup.py 2008-01-03 19:05:43 UTC (rev 3770) +++ trunk/scipy/io/matlab/setup.py 2008-01-03 19:21:53 UTC (rev 3771) @@ -3,6 +3,7 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('matlab', parent_package, top_path) + config.add_data_dir('tests') return config if __name__ == '__main__': Copied: trunk/scipy/io/matlab/tests/data (from rev 3768, trunk/scipy/io/tests/data) Copied: trunk/scipy/io/matlab/tests/test_mio.py (from rev 3770, trunk/scipy/io/tests/test_mio.py) =================================================================== --- trunk/scipy/io/tests/test_mio.py 2008-01-03 19:05:43 UTC (rev 3770) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-01-03 19:21:53 UTC (rev 3771) @@ -0,0 +1,248 @@ +#!/usr/bin/env python + +import os +from glob import glob +from cStringIO import StringIO +from tempfile import mkstemp +from numpy.testing import set_package_path, restore_path, NumpyTestCase, NumpyTest +from numpy.testing import assert_equal, assert_array_almost_equal +from numpy import arange, array, eye, pi, cos, exp, sin, sqrt, ndarray, \ + zeros, reshape, transpose, empty +import scipy.sparse as SP + +set_package_path() +from matlab.mio import loadmat, savemat +from matlab.mio5 import mat_obj, mat_struct +restore_path() + +try: # Python 2.3 support + from sets import Set as set +except: + pass + +test_data_path = os.path.join(os.path.dirname(__file__), './data') + +class TestMIOArray(NumpyTestCase): + def __init__(self, *args, **kwargs): + super(TestMIOArray, self).__init__(*args, **kwargs) + + def _check_level(self, label, expected, actual): + """ Check one level of a potentially nested object / list """ + # object array is returned from cell array in mat file + typex = type(expected) + typac = type(actual) + if isinstance(expected, ndarray) and expected.dtype.hasobject: + assert typex is typac, "Different types at %s" % label + assert len(expected) == len(actual), "Different list lengths at %s" % label + for i, ev in enumerate(expected): + level_label = "%s, [%d], " % (label, i) + self._check_level(level_label, ev, actual[i]) + return + # object, as container for matlab structs and objects + elif isinstance(expected, mat_struct) or isinstance(expected, mat_obj): + assert isinstance(actual, typex), \ + "Different types %s and %s at %s" % (typex, typac, label) + ex_fields = dir(expected) + ac_fields = dir(actual) + for k in ex_fields: + if k.startswith('__') and k.endswith('__'): + continue + assert k in ac_fields, "Missing property at %s" % label + ev = expected.__dict__[k] + v = actual.__dict__[k] + level_label = "%s, property %s, " % (label, k) + self._check_level(level_label, ev, v) + return + # hoping this is a single value, which might be an array + if SP.issparse(expected): + assert SP.issparse(actual), "Expected sparse at %s" % label + assert_array_almost_equal(actual.todense(), + expected.todense(), + err_msg = label, + decimal = 5) + elif isinstance(expected, ndarray): + if expected.shape: # allow scalar and 0d array comparisons + assert isinstance(actual, ndarray), "Expected ndarray at %s" % label + assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) + else: + assert isinstance(expected, typac), \ + "Types %s and %s do not match at %s" % (typex, typac, label) + assert_equal(actual, expected, err_msg=label) + + def _check_case(self, name, files, case): + for file_name in files: + matdict = loadmat(file_name) + label = "test %s; file %s" % (name, file_name) + for k, expected in case.items(): + k_label = "%s, variable %s" % (label, k) + assert k in matdict, "Missing key at %s" % k_label + self._check_level(k_label, expected, matdict[k]) + + # Add the load tests dynamically, with given parameters + def _make_check_case(name, files, expected): + def cc(self): + self._check_case(name, files, expected) + cc.__doc__ = "check loadmat case %s" % name + return cc + + # Add the round trip tests dynamically, with given parameters + def _make_rt_check_case(name, expected, format): + def cc(self): + mat_stream = StringIO() + savemat(mat_stream, expected, format=format) + mat_stream.seek(0) + self._check_case(name, [mat_stream], expected) + cc.__doc__ = "check loadmat case %s" % name + return cc + + # Define cases to test + theta = pi/4*arange(9,dtype=float) + case_table4 = [ + {'name': 'double', + 'expected': {'testdouble': theta} + }] + case_table4.append( + {'name': 'string', + 'expected': {'teststring': u'"Do nine men interpret?" "Nine men," I nod.'}, + }) + case_table4.append( + {'name': 'complex', + 'expected': {'testcomplex': cos(theta) + 1j*sin(theta)} + }) + A = zeros((3,5)) + A[0] = range(1,6) + A[:,0] = range(1,4) + case_table4.append( + {'name': 'matrix', + 'expected': {'testmatrix': A}, + }) + case_table4.append( + {'name': 'sparse', + 'expected': {'testsparse': SP.csc_matrix(A)}, + }) + B = A.astype(complex) + B[0,0] += 1j + case_table4.append( + {'name': 'sparsecomplex', + 'expected': {'testsparsecomplex': SP.csc_matrix(B)}, + }) + case_table4.append( + {'name': 'multi', + 'expected': {'theta': theta, + 'a': A}, + }) + case_table4.append( + {'name': 'minus', + 'expected': {'testminus': array(-1)}, + }) + case_table4.append( + {'name': 'onechar', + 'expected': {'testonechar': u'r'}, + }) + case_table5 = [ + {'name': 'cell', + 'expected': {'testcell': + array([u'This cell contains this string and 3 arrays of '+\ + 'increasing length', + array(1), array([1,2]), array([1,2,3])], + dtype=object)} + }] + case_table5.append( + {'name': 'emptycell', + 'expected': {'testemptycell': + array([array(1), array(2), array([]), + array([]), array(3)], dtype=object)} + }) + case_table5.append( + {'name': 'stringarray', + 'expected': {'teststringarray': array( + [u'one ', u'two ', u'three'], dtype=object)}, + }) + case_table5.append( + {'name': '3dmatrix', + 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} + }) + case_table5_rt = [ + {'name': '3dmatrix', + 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} + }, + {'name': 'sparsefloat', + 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, + }, + {'name': 'sparsecomplex', + 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, + }, + ] + st = mat_struct() + st.stringfield = u'Rats live on no evil star.' + st.doublefield = array([sqrt(2),exp(1),pi]) + st.complexfield = (1+1j)*array([sqrt(2),exp(1),pi]) + case_table5.append( + {'name': 'struct', + 'expected': {'teststruct': st} + }) + a = array([array(1), + array([array(2), array(3), + array([array(4), array(5)], + dtype=object)], + dtype=object)], + dtype=object) + case_table5.append( + {'name': 'cellnest', + 'expected': {'testcellnest': a}, + }) + st = mat_struct() + st.one = array(1) + st.two = mat_struct() + st.two.three = u'number 3' + case_table5.append( + {'name': 'structnest', + 'expected': {'teststructnest': st} + }) + a = array([mat_struct(), mat_struct()]) + a[0].one = array(1) + a[0].two = array(2) + a[1].one = u'number 1' + a[1].two = u'number 2' + case_table5.append( + {'name': 'structarr', + 'expected': {'teststructarr': a} + }) + a = mat_obj() + a._classname = 'inline' + a.expr = u'x' + a.inputExpr = u' x = INLINE_INPUTS_{1};' + a.args = u'x' + a.isEmpty = array(0) + a.numArgs = array(1) + a.version = array(1) + case_table5.append( + {'name': 'object', + 'expected': {'testobject': a} + }) + u_str = file( + os.path.join(test_data_path, 'japanese_utf8.txt'), + 'rb').read().decode('utf-8') + case_table5.append( + {'name': 'unicode', + 'expected': {'testunicode': u_str} + }) + # add load tests + for case in case_table4 + case_table5: + name = case['name'] + expected = case['expected'] + filt = os.path.join(test_data_path, 'test%s_*.mat' % name) + files = glob(filt) + assert files, "No files for test %s using filter %s" % (name, filt) + exec 'check_%s = _make_check_case(name, files, expected)' % name + # round trip tests + for case in case_table4 + case_table5_rt: + name = case['name'] + '_round_trip' + expected = case['expected'] + format = case in case_table4 and '4' or '5' + exec 'check_%s = _make_rt_check_case(name, expected, format)' \ + % name + + +if __name__ == "__main__": + NumpyTest().run() Deleted: trunk/scipy/io/tests/test_mio.py =================================================================== --- trunk/scipy/io/tests/test_mio.py 2008-01-03 19:05:43 UTC (rev 3770) +++ trunk/scipy/io/tests/test_mio.py 2008-01-03 19:21:53 UTC (rev 3771) @@ -1,248 +0,0 @@ -#!/usr/bin/env python - -import os -from glob import glob -from cStringIO import StringIO -from tempfile import mkstemp -from numpy.testing import set_package_path, restore_path, NumpyTestCase, NumpyTest -from numpy.testing import assert_equal, assert_array_almost_equal -from numpy import arange, array, eye, pi, cos, exp, sin, sqrt, ndarray, \ - zeros, reshape, transpose, empty -import scipy.sparse as SP - -set_package_path() -from io.matlab.mio import loadmat, savemat -from io.matlab.mio5 import mat_obj, mat_struct -restore_path() - -try: # Python 2.3 support - from sets import Set as set -except: - pass - -test_data_path = os.path.join(os.path.dirname(__file__), './data') - -class TestMIOArray(NumpyTestCase): - def __init__(self, *args, **kwargs): - super(TestMIOArray, self).__init__(*args, **kwargs) - - def _check_level(self, label, expected, actual): - """ Check one level of a potentially nested object / list """ - # object array is returned from cell array in mat file - typex = type(expected) - typac = type(actual) - if isinstance(expected, ndarray) and expected.dtype.hasobject: - assert typex is typac, "Different types at %s" % label - assert len(expected) == len(actual), "Different list lengths at %s" % label - for i, ev in enumerate(expected): - level_label = "%s, [%d], " % (label, i) - self._check_level(level_label, ev, actual[i]) - return - # object, as container for matlab structs and objects - elif isinstance(expected, mat_struct) or isinstance(expected, mat_obj): - assert isinstance(actual, typex), \ - "Different types %s and %s at %s" % (typex, typac, label) - ex_fields = dir(expected) - ac_fields = dir(actual) - for k in ex_fields: - if k.startswith('__') and k.endswith('__'): - continue - assert k in ac_fields, "Missing property at %s" % label - ev = expected.__dict__[k] - v = actual.__dict__[k] - level_label = "%s, property %s, " % (label, k) - self._check_level(level_label, ev, v) - return - # hoping this is a single value, which might be an array - if SP.issparse(expected): - assert SP.issparse(actual), "Expected sparse at %s" % label - assert_array_almost_equal(actual.todense(), - expected.todense(), - err_msg = label, - decimal = 5) - elif isinstance(expected, ndarray): - if expected.shape: # allow scalar and 0d array comparisons - assert isinstance(actual, ndarray), "Expected ndarray at %s" % label - assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) - else: - assert isinstance(expected, typac), \ - "Types %s and %s do not match at %s" % (typex, typac, label) - assert_equal(actual, expected, err_msg=label) - - def _check_case(self, name, files, case): - for file_name in files: - matdict = loadmat(file_name) - label = "test %s; file %s" % (name, file_name) - for k, expected in case.items(): - k_label = "%s, variable %s" % (label, k) - assert k in matdict, "Missing key at %s" % k_label - self._check_level(k_label, expected, matdict[k]) - - # Add the load tests dynamically, with given parameters - def _make_check_case(name, files, expected): - def cc(self): - self._check_case(name, files, expected) - cc.__doc__ = "check loadmat case %s" % name - return cc - - # Add the round trip tests dynamically, with given parameters - def _make_rt_check_case(name, expected, format): - def cc(self): - mat_stream = StringIO() - savemat(mat_stream, expected, format=format) - mat_stream.seek(0) - self._check_case(name, [mat_stream], expected) - cc.__doc__ = "check loadmat case %s" % name - return cc - - # Define cases to test - theta = pi/4*arange(9,dtype=float) - case_table4 = [ - {'name': 'double', - 'expected': {'testdouble': theta} - }] - case_table4.append( - {'name': 'string', - 'expected': {'teststring': u'"Do nine men interpret?" "Nine men," I nod.'}, - }) - case_table4.append( - {'name': 'complex', - 'expected': {'testcomplex': cos(theta) + 1j*sin(theta)} - }) - A = zeros((3,5)) - A[0] = range(1,6) - A[:,0] = range(1,4) - case_table4.append( - {'name': 'matrix', - 'expected': {'testmatrix': A}, - }) - case_table4.append( - {'name': 'sparse', - 'expected': {'testsparse': SP.csc_matrix(A)}, - }) - B = A.astype(complex) - B[0,0] += 1j - case_table4.append( - {'name': 'sparsecomplex', - 'expected': {'testsparsecomplex': SP.csc_matrix(B)}, - }) - case_table4.append( - {'name': 'multi', - 'expected': {'theta': theta, - 'a': A}, - }) - case_table4.append( - {'name': 'minus', - 'expected': {'testminus': array(-1)}, - }) - case_table4.append( - {'name': 'onechar', - 'expected': {'testonechar': u'r'}, - }) - case_table5 = [ - {'name': 'cell', - 'expected': {'testcell': - array([u'This cell contains this string and 3 arrays of '+\ - 'increasing length', - array(1), array([1,2]), array([1,2,3])], - dtype=object)} - }] - case_table5.append( - {'name': 'emptycell', - 'expected': {'testemptycell': - array([array(1), array(2), array([]), - array([]), array(3)], dtype=object)} - }) - case_table5.append( - {'name': 'stringarray', - 'expected': {'teststringarray': array( - [u'one ', u'two ', u'three'], dtype=object)}, - }) - case_table5.append( - {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }) - case_table5_rt = [ - {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }, - {'name': 'sparsefloat', - 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, - }, - {'name': 'sparsecomplex', - 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, - }, - ] - st = mat_struct() - st.stringfield = u'Rats live on no evil star.' - st.doublefield = array([sqrt(2),exp(1),pi]) - st.complexfield = (1+1j)*array([sqrt(2),exp(1),pi]) - case_table5.append( - {'name': 'struct', - 'expected': {'teststruct': st} - }) - a = array([array(1), - array([array(2), array(3), - array([array(4), array(5)], - dtype=object)], - dtype=object)], - dtype=object) - case_table5.append( - {'name': 'cellnest', - 'expected': {'testcellnest': a}, - }) - st = mat_struct() - st.one = array(1) - st.two = mat_struct() - st.two.three = u'number 3' - case_table5.append( - {'name': 'structnest', - 'expected': {'teststructnest': st} - }) - a = array([mat_struct(), mat_struct()]) - a[0].one = array(1) - a[0].two = array(2) - a[1].one = u'number 1' - a[1].two = u'number 2' - case_table5.append( - {'name': 'structarr', - 'expected': {'teststructarr': a} - }) - a = mat_obj() - a._classname = 'inline' - a.expr = u'x' - a.inputExpr = u' x = INLINE_INPUTS_{1};' - a.args = u'x' - a.isEmpty = array(0) - a.numArgs = array(1) - a.version = array(1) - case_table5.append( - {'name': 'object', - 'expected': {'testobject': a} - }) - u_str = file( - os.path.join(test_data_path, 'japanese_utf8.txt'), - 'rb').read().decode('utf-8') - case_table5.append( - {'name': 'unicode', - 'expected': {'testunicode': u_str} - }) - # add load tests - for case in case_table4 + case_table5: - name = case['name'] - expected = case['expected'] - filt = os.path.join(test_data_path, 'test%s_*.mat' % name) - files = glob(filt) - assert files, "No files for test %s using filter %s" % (name, filt) - exec 'check_%s = _make_check_case(name, files, expected)' % name - # round trip tests - for case in case_table4 + case_table5_rt: - name = case['name'] + '_round_trip' - expected = case['expected'] - format = case in case_table4 and '4' or '5' - exec 'check_%s = _make_rt_check_case(name, expected, format)' \ - % name - - -if __name__ == "__main__": - NumpyTest().run() From scipy-svn at scipy.org Thu Jan 3 14:24:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 13:24:57 -0600 (CST) Subject: [Scipy-svn] r3772 - trunk/scipy/optimize/tests Message-ID: <20080103192457.22F2539C181@new.scipy.org> Author: stefan Date: 2008-01-03 13:24:40 -0600 (Thu, 03 Jan 2008) New Revision: 3772 Modified: trunk/scipy/optimize/tests/test_slsqp.py Log: Fix failing slsqp test. Modified: trunk/scipy/optimize/tests/test_slsqp.py =================================================================== --- trunk/scipy/optimize/tests/test_slsqp.py 2008-01-03 19:21:53 UTC (rev 3771) +++ trunk/scipy/optimize/tests/test_slsqp.py 2008-01-03 19:24:40 UTC (rev 3772) @@ -84,7 +84,7 @@ ieqcons = [lambda x, y: x[0]-x[1]-1.0], iprint=0, full_output=1) x,fx,its,imode,smode = res - assert_array_almost_equal(x,[2,1]) + assert_array_almost_equal(x,[2,1],decimal=3) if __name__ == "__main__": NumpyTest().run() From scipy-svn at scipy.org Thu Jan 3 14:36:52 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 13:36:52 -0600 (CST) Subject: [Scipy-svn] r3773 - trunk/scipy/io/matlab Message-ID: <20080103193652.72DEC39C12F@new.scipy.org> Author: stefan Date: 2008-01-03 13:36:34 -0600 (Thu, 03 Jan 2008) New Revision: 3773 Modified: trunk/scipy/io/matlab/mio5.py Log: Fix typo. Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-01-03 19:24:40 UTC (rev 3772) +++ trunk/scipy/io/matlab/mio5.py 2008-01-03 19:36:34 UTC (rev 3773) @@ -666,7 +666,7 @@ ''' Sparse matrices are 2D ''' - A = self.arr.tocsc() # convert to sparse COO format (ijv) + A = self.arr.tocsc() # convert to sparse CSC format is_complex = (A.dtype.kind == 'c') nz = A.nnz From scipy-svn at scipy.org Thu Jan 3 16:51:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 15:51:16 -0600 (CST) Subject: [Scipy-svn] r3774 - in branches/testing_cleanup/scipy/sandbox/dhuard: . tests Message-ID: <20080103215116.0120B39C01F@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-03 15:51:10 -0600 (Thu, 03 Jan 2008) New Revision: 3774 Added: branches/testing_cleanup/scipy/sandbox/dhuard/__init__.py branches/testing_cleanup/scipy/sandbox/dhuard/tests/ branches/testing_cleanup/scipy/sandbox/dhuard/tests/test_histogram.py branches/testing_cleanup/scipy/sandbox/dhuard/tests/test_stats.py Removed: branches/testing_cleanup/scipy/sandbox/dhuard/test_histogram.py branches/testing_cleanup/scipy/sandbox/dhuard/test_stats.py Log: Rearranged tests, added init file Added: branches/testing_cleanup/scipy/sandbox/dhuard/__init__.py =================================================================== Deleted: branches/testing_cleanup/scipy/sandbox/dhuard/test_histogram.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/dhuard/test_histogram.py 2008-01-03 19:36:34 UTC (rev 3773) +++ branches/testing_cleanup/scipy/sandbox/dhuard/test_histogram.py 2008-01-03 21:51:10 UTC (rev 3774) @@ -1,99 +0,0 @@ -from numpy.testing import * -from histogram import _histogram_fixed_binsize, _histogram_digitize,\ - _histogram_searchsort, histogram,_optimize_binning -import numpy as np -from numpy.random import rand - -class TestHistogram1DFunctions(NumpyTestCase): - def check_consistency(self): - n = 100 - r = rand(n)*12-1 - bins = range(11) - a = _histogram_fixed_binsize(r, bins[0], bins[1]-bins[0], len(bins)-1) - b = _histogram_digitize(r, None, np.array(bins), False) - c = _histogram_searchsort(r,bins) - assert_array_equal(a,b) - assert_array_equal(c,b) - -class TestHistogram(NumpyTestCase): - def check_simple(self): - n=100 - v=rand(n) - (a,b)=histogram(v) - #check if the sum of the bins equals the number of samples - assert_equal(np.sum(a,axis=0),n) - #check that the bin counts are evenly spaced when the data is from a linear function - (a,b)=histogram(np.linspace(0,10,100)) - assert_array_equal(a,10) - #Check the construction of the bin array - a, b = histogram(v, bins=4, range=[.2,.8]) - assert_array_almost_equal(b['edges'],np.linspace(.2, .8, 5),8) - #Check the number of outliers - assert_equal((v<.2).sum(), b['lower']) - assert_equal((v>.8).sum(),b['upper']) - #Check the normalization - bins = [0,.5,.75,1] - a,b = histogram(v, bins, normed=True) - assert_almost_equal((a*np.diff(bins)).sum(), 1) - - def check_axis(self): - n,m = 100,20 - v = rand(n,m) - a,b = histogram(v, bins=5) - # Check dimension is reduced (axis=None). - assert_equal(a.ndim, 1) - #Check total number of count is equal to the number of samples. - assert_equal(a.sum(), n*m) - a,b = histogram(v, bins = 7, axis=0) - # Check shape of new array is ok. - assert(a.ndim == 2) - assert_array_equal(a.shape,[7, m]) - # Check normalization is consistent - a,b = histogram(v, bins = 7, axis=0, normed=True) - assert_array_almost_equal((a.T*np.diff(b['edges'])).sum(1), np.ones((m)),5) - a,b = histogram(v, bins = 7, axis=1, normed=True) - assert_array_equal(a.shape, [n,7]) - assert_array_almost_equal((a*np.diff(b['edges'])).sum(1), np.ones((n))) - # Check results are consistent with 1d estimate - a1, b1 = histogram(v[0,:], bins=b['edges'], normed=True) - assert_array_almost_equal(a1, a[0,:],7) - - def check_weights(self): - # Check weights = constant gives the same answer as no weights. - v = rand(100) - w = np.ones(100)*5 - a,b = histogram(v) - na,nb = histogram(v, normed=True) - wa,wb = histogram(v, weights=w) - nwa,nwb = histogram(v, weights=w, normed=True) - assert_array_equal(a*5, wa) - assert_array_almost_equal(na, nwa,8) - # Check weights are properly applied. - v = np.linspace(0,10,10) - w = np.concatenate((np.zeros(5), np.ones(5))) - wa,wb = histogram(v, bins=np.linspace(0,10.01, 11),weights=w) - assert_array_almost_equal(wa, w) - - def check_strategies(self): - v = rand(100) - ae,be = histogram(v, strategy='binsize') - ab,bb = histogram(v, strategy='digitize') - as,bs = histogram(v, strategy='searchsort') - assert_array_equal(ae, ab) - assert_array_equal(ae, as) - - w = rand(100) - ae,be = histogram(v, weights=w, strategy='binsize') - ab,bb = histogram(v, weights=w, strategy='digitize') - as,bs = histogram(v, weights=w, strategy='searchsort') - assert_array_almost_equal(ae, ab,8) - assert_array_almost_equal(ae, as,8) - - def check_automatic_binning(self): - v = rand(100) - h,b = histogram(v, 'Scott') - h,b = histogram(v, 'Freedman') - - -if __name__ == "__main__": - NumpyTest().run() Deleted: branches/testing_cleanup/scipy/sandbox/dhuard/test_stats.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/dhuard/test_stats.py 2008-01-03 19:36:34 UTC (rev 3773) +++ branches/testing_cleanup/scipy/sandbox/dhuard/test_stats.py 2008-01-03 21:51:10 UTC (rev 3774) @@ -1,45 +0,0 @@ -""" -Test statistical functions. -""" - - -from numpy.testing import * -import stats -import numpy as np - -N = 100 -np.random.seed(2) -r = np.random.randn(N) - -class TestEmpiricalCDF(NumpyTestCase): - def check_hazen(self): - - f = stats.empiricalcdf(r) - assert_equal(len(f), len(r)) - assert_array_equal(np.argsort(r), np.argsort(f)) - assert_array_equal(np.sort(f), (np.arange(N)+.5)/N) - - def check_weibull(self): - f = stats.empiricalcdf(r, 'weibull') - assert_array_equal(np.sort(f), (np.arange(N)+1.)/(N+1.)) - - def check_california(self): - f = stats.empiricalcdf(r, 'california') - assert_array_equal(np.sort(f), (np.arange(N))/float(N)) - -class TestScoreAtPercentile(NumpyTestCase): - def check_simple(self): - r = np.random.randn(1000) - s = stats.scoreatpercentile(r, [15.9,50,84.1]) - assert_array_almost_equal(s, [-1,0,1], 1) - -class TestPercentileOfScore(NumpyTestCase): - def check_simple(self): - r = np.random.randn(3000) - p = stats.percentileofscore(r, [-1,0,1]) - assert_array_almost_equal(p, [15.9, 50, 84.1], 0) - - - -if __name__ == '__main__': - NumpyTest().run() Copied: branches/testing_cleanup/scipy/sandbox/dhuard/tests/test_histogram.py (from rev 3726, branches/testing_cleanup/scipy/sandbox/dhuard/test_histogram.py) =================================================================== --- branches/testing_cleanup/scipy/sandbox/dhuard/test_histogram.py 2007-12-27 07:49:22 UTC (rev 3726) +++ branches/testing_cleanup/scipy/sandbox/dhuard/tests/test_histogram.py 2008-01-03 21:51:10 UTC (rev 3774) @@ -0,0 +1,99 @@ +from scipy.testing import * +from scipy.sandbox.dhuard.histogram import _histogram_fixed_binsize, _histogram_digitize,\ + _histogram_searchsort, histogram,_optimize_binning +import numpy as np +from numpy.random import rand + +class TestHistogram1DFunctions(TestCase): + def test_consistency(self): + n = 100 + r = rand(n)*12-1 + bins = range(11) + a = _histogram_fixed_binsize(r, bins[0], bins[1]-bins[0], len(bins)-1) + b = _histogram_digitize(r, None, np.array(bins), False) + c = _histogram_searchsort(r,bins) + assert_array_equal(a,b) + assert_array_equal(c,b) + +class TestHistogram(TestCase): + def test_simple(self): + n=100 + v=rand(n) + (a,b)=histogram(v) + #check if the sum of the bins equals the number of samples + assert_equal(np.sum(a,axis=0),n) + #check that the bin counts are evenly spaced when the data is from a linear function + (a,b)=histogram(np.linspace(0,10,100)) + assert_array_equal(a,10) + #Check the construction of the bin array + a, b = histogram(v, bins=4, range=[.2,.8]) + assert_array_almost_equal(b['edges'],np.linspace(.2, .8, 5),8) + #Check the number of outliers + assert_equal((v<.2).sum(), b['lower']) + assert_equal((v>.8).sum(),b['upper']) + #Check the normalization + bins = [0,.5,.75,1] + a,b = histogram(v, bins, normed=True) + assert_almost_equal((a*np.diff(bins)).sum(), 1) + + def test_axis(self): + n,m = 100,20 + v = rand(n,m) + a,b = histogram(v, bins=5) + # Check dimension is reduced (axis=None). + assert_equal(a.ndim, 1) + #Check total number of count is equal to the number of samples. + assert_equal(a.sum(), n*m) + a,b = histogram(v, bins = 7, axis=0) + # Check shape of new array is ok. + assert(a.ndim == 2) + assert_array_equal(a.shape,[7, m]) + # Check normalization is consistent + a,b = histogram(v, bins = 7, axis=0, normed=True) + assert_array_almost_equal((a.T*np.diff(b['edges'])).sum(1), np.ones((m)),5) + a,b = histogram(v, bins = 7, axis=1, normed=True) + assert_array_equal(a.shape, [n,7]) + assert_array_almost_equal((a*np.diff(b['edges'])).sum(1), np.ones((n))) + # Check results are consistent with 1d estimate + a1, b1 = histogram(v[0,:], bins=b['edges'], normed=True) + assert_array_almost_equal(a1, a[0,:],7) + + def test_weights(self): + # Check weights = constant gives the same answer as no weights. + v = rand(100) + w = np.ones(100)*5 + a,b = histogram(v) + na,nb = histogram(v, normed=True) + wa,wb = histogram(v, weights=w) + nwa,nwb = histogram(v, weights=w, normed=True) + assert_array_equal(a*5, wa) + assert_array_almost_equal(na, nwa,8) + # Check weights are properly applied. + v = np.linspace(0,10,10) + w = np.concatenate((np.zeros(5), np.ones(5))) + wa,wb = histogram(v, bins=np.linspace(0,10.01, 11),weights=w) + assert_array_almost_equal(wa, w) + + def test_strategies(self): + v = rand(100) + ae,be = histogram(v, strategy='binsize') + ab,bb = histogram(v, strategy='digitize') + as,bs = histogram(v, strategy='searchsort') + assert_array_equal(ae, ab) + assert_array_equal(ae, as) + + w = rand(100) + ae,be = histogram(v, weights=w, strategy='binsize') + ab,bb = histogram(v, weights=w, strategy='digitize') + as,bs = histogram(v, weights=w, strategy='searchsort') + assert_array_almost_equal(ae, ab,8) + assert_array_almost_equal(ae, as,8) + + def test_automatic_binning(self): + v = rand(100) + h,b = histogram(v, 'Scott') + h,b = histogram(v, 'Freedman') + + +if __name__ == "__main__": + unittest.main() Copied: branches/testing_cleanup/scipy/sandbox/dhuard/tests/test_stats.py (from rev 3726, branches/testing_cleanup/scipy/sandbox/dhuard/test_stats.py) =================================================================== --- branches/testing_cleanup/scipy/sandbox/dhuard/test_stats.py 2007-12-27 07:49:22 UTC (rev 3726) +++ branches/testing_cleanup/scipy/sandbox/dhuard/tests/test_stats.py 2008-01-03 21:51:10 UTC (rev 3774) @@ -0,0 +1,44 @@ +""" +Test statistical functions. +""" + +from scipy.testing import * +from scipy.sandbox.dhuard import stats +import numpy as np + +N = 100 +np.random.seed(2) +r = np.random.randn(N) + +class TestEmpiricalCDF(TestCase): + def test_hazen(self): + + f = stats.empiricalcdf(r) + assert_equal(len(f), len(r)) + assert_array_equal(np.argsort(r), np.argsort(f)) + assert_array_equal(np.sort(f), (np.arange(N)+.5)/N) + + def test_weibull(self): + f = stats.empiricalcdf(r, 'weibull') + assert_array_equal(np.sort(f), (np.arange(N)+1.)/(N+1.)) + + def test_california(self): + f = stats.empiricalcdf(r, 'california') + assert_array_equal(np.sort(f), (np.arange(N))/float(N)) + +class TestScoreAtPercentile(TestCase): + def test_simple(self): + r = np.random.randn(1000) + s = stats.scoreatpercentile(r, [15.9,50,84.1]) + assert_array_almost_equal(s, [-1,0,1], 1) + +class TestPercentileOfScore(TestCase): + def test_simple(self): + r = np.random.randn(3000) + p = stats.percentileofscore(r, [-1,0,1]) + assert_array_almost_equal(p, [15.9, 50, 84.1], 0) + + + +if __name__ == '__main__': + unittest.main() From scipy-svn at scipy.org Thu Jan 3 17:15:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 16:15:51 -0600 (CST) Subject: [Scipy-svn] r3775 - trunk/scipy/io/matlab Message-ID: <20080103221551.8FD0839C2E7@new.scipy.org> Author: wnbell Date: 2008-01-03 16:15:45 -0600 (Thu, 03 Jan 2008) New Revision: 3775 Modified: trunk/scipy/io/matlab/mio5.py Log: sort CSC row indices before MATLAB export Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-01-03 21:51:10 UTC (rev 3774) +++ trunk/scipy/io/matlab/mio5.py 2008-01-03 22:15:45 UTC (rev 3775) @@ -667,6 +667,7 @@ ''' A = self.arr.tocsc() # convert to sparse CSC format + A.sort_indices() is_complex = (A.dtype.kind == 'c') nz = A.nnz From scipy-svn at scipy.org Thu Jan 3 17:17:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 16:17:03 -0600 (CST) Subject: [Scipy-svn] r3776 - trunk/scipy/io/matlab Message-ID: <20080103221703.6FE0539C10C@new.scipy.org> Author: wnbell Date: 2008-01-03 16:16:43 -0600 (Thu, 03 Jan 2008) New Revision: 3776 Modified: trunk/scipy/io/matlab/mio5.py Log: add brief comment Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-01-03 22:15:45 UTC (rev 3775) +++ trunk/scipy/io/matlab/mio5.py 2008-01-03 22:16:43 UTC (rev 3776) @@ -667,7 +667,7 @@ ''' A = self.arr.tocsc() # convert to sparse CSC format - A.sort_indices() + A.sort_indices() # MATLAB expects sorted row indices is_complex = (A.dtype.kind == 'c') nz = A.nnz From scipy-svn at scipy.org Thu Jan 3 19:20:45 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 18:20:45 -0600 (CST) Subject: [Scipy-svn] r3777 - trunk/scipy/io/matlab Message-ID: <20080104002045.6F7A839C02A@new.scipy.org> Author: stefan Date: 2008-01-03 18:20:17 -0600 (Thu, 03 Jan 2008) New Revision: 3777 Modified: trunk/scipy/io/matlab/mio5.py Log: Fix array name writing in MATLAB v5 format. Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-01-03 22:16:43 UTC (rev 3776) +++ trunk/scipy/io/matlab/mio5.py 2008-01-04 00:20:17 UTC (rev 3777) @@ -604,10 +604,13 @@ self.write_dtype(af) # write array shape if self.arr.ndim < 2: - self.arr=N.atleast_2d(self.arr) + new_arr = N.atleast_2d(self.arr) + if type(new_arr) != type(self.arr): + raise ValueError("Array should be 2-dimensional.") + self.arr = new_arr self.write_element(N.array(self.arr.shape, dtype='i4')) # write name - self.write_element(N.ndarray(shape=len(self.name), dtype='S1', buffer=self.name)) + self.write_element(N.array([ord(c) for c in self.name], 'i1')) def update_matrix_tag(self): curr_pos = self.file_stream.tell() From scipy-svn at scipy.org Thu Jan 3 20:30:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 3 Jan 2008 19:30:20 -0600 (CST) Subject: [Scipy-svn] r3778 - in branches/testing_cleanup/scipy/sandbox: arpack/tests buildgrid cdavid/tests constants delaunay/tests fdfpack/tests lobpcg/tests maskedarray maskedarray/tests montecarlo/tests numexpr numexpr/tests pyloess pyloess/tests rbf/tests spline/tests timeseries timeseries/lib timeseries/tests Message-ID: <20080104013020.80FFC39C02A@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-03 19:29:56 -0600 (Thu, 03 Jan 2008) New Revision: 3778 Modified: branches/testing_cleanup/scipy/sandbox/arpack/tests/test_speigs.py branches/testing_cleanup/scipy/sandbox/buildgrid/test_build_grid.py branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_autocorr.py branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_lpc.py branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_segmentaxis.py branches/testing_cleanup/scipy/sandbox/constants/constants.py branches/testing_cleanup/scipy/sandbox/delaunay/tests/test_triangulate.py branches/testing_cleanup/scipy/sandbox/fdfpack/tests/test_fdf.py branches/testing_cleanup/scipy/sandbox/lobpcg/tests/large_scale.py branches/testing_cleanup/scipy/sandbox/lobpcg/tests/test_lobpcg.py branches/testing_cleanup/scipy/sandbox/maskedarray/extras.py branches/testing_cleanup/scipy/sandbox/maskedarray/morestats.py branches/testing_cleanup/scipy/sandbox/maskedarray/mrecords.py branches/testing_cleanup/scipy/sandbox/maskedarray/mstats.py branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_core.py branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_extras.py branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_morestats.py branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_mrecords.py branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_mstats.py branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_subclassing.py branches/testing_cleanup/scipy/sandbox/montecarlo/tests/test_dictsampler.py branches/testing_cleanup/scipy/sandbox/montecarlo/tests/test_intsampler.py branches/testing_cleanup/scipy/sandbox/numexpr/__init__.py branches/testing_cleanup/scipy/sandbox/numexpr/compiler.py branches/testing_cleanup/scipy/sandbox/numexpr/expressions.py branches/testing_cleanup/scipy/sandbox/numexpr/tests/test_numexpr.py branches/testing_cleanup/scipy/sandbox/pyloess/mpyloess.py branches/testing_cleanup/scipy/sandbox/pyloess/tests/test_mpyloess.py branches/testing_cleanup/scipy/sandbox/pyloess/tests/test_pyloess.py branches/testing_cleanup/scipy/sandbox/rbf/tests/test_rbf.py branches/testing_cleanup/scipy/sandbox/spline/tests/test_fitpack.py branches/testing_cleanup/scipy/sandbox/spline/tests/test_spline.py branches/testing_cleanup/scipy/sandbox/timeseries/dates.py branches/testing_cleanup/scipy/sandbox/timeseries/extras.py branches/testing_cleanup/scipy/sandbox/timeseries/lib/filters.py branches/testing_cleanup/scipy/sandbox/timeseries/lib/interpolate.py branches/testing_cleanup/scipy/sandbox/timeseries/lib/moving_funcs.py branches/testing_cleanup/scipy/sandbox/timeseries/report.py branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_dates.py branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_extras.py branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_timeseries.py branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_trecords.py branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py branches/testing_cleanup/scipy/sandbox/timeseries/tseries.py Log: Sandbox tests nose compatible as far as they are runnable Modified: branches/testing_cleanup/scipy/sandbox/arpack/tests/test_speigs.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/arpack/tests/test_speigs.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/arpack/tests/test_speigs.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,11 +1,9 @@ #!/usr/bin/env python -import sys from scipy.testing import * -from arpack.speigs import * +from scipy.sandbox.arpack.speigs import * - import numpy as N class TestEigs(TestCase): @@ -30,7 +28,7 @@ nev=4 eigvs = ARPACK_eigs(matvec, A.shape[0], nev=nev) calc_vals = eigvs[0] - # Ensure the calculate eigenvectors have the same sign as the refence values + # Ensure the calculated eigenvectors have the same sign as the reference values calc_vecs = eigvs[1] / [N.sign(x[0]) for x in eigvs[1].T] assert_array_almost_equal(calc_vals, vals[0:nev], decimal=7) assert_array_almost_equal(calc_vecs, N.array(vecs)[:,0:nev], decimal=7) Modified: branches/testing_cleanup/scipy/sandbox/buildgrid/test_build_grid.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/buildgrid/test_build_grid.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/buildgrid/test_build_grid.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,183 +1,184 @@ - -""" Tests for BuildGrid.c module. -To view the grids I used QuikGrid from -http://www.PerspectiveEdge.com -""" - -import sys,math,random,time -random.seed(7) - -global ncol,nrow,step,xmin,ymin,simple -xmin,ymin,step = 0.0,0.0,1.0 - -# Surface model: -simple = True # simple: (a1+b1*x)*(a2+b2*y) - # This is almost a plain. - -simple = False # !simple: cos(a*x*x)*cos(b*y*y) - # In this case only left bottom part of surface - # should be believable. - -def gridsizes(nodes,ratio=1.0): - # ratio = ncol/nrow - nodes = max(100,nodes) - ratio = max(0.1,min(ratio,10.0)) - nrow = int(math.sqrt(nodes/ratio)) - ncol = nodes/nrow+1 - return ncol,nrow - -ncol,nrow = gridsizes(10**5) # I used 10**3 - 10**7 nodes - -ax,ay = math.pi/(4*ncol+1),math.pi/(4*nrow+1) - -percent = 10.2 # how many data points w.r.t. grid nodes: -datapoints = int(0.01 * percent * ncol * nrow) or 5 -print "Testing",("complex","simple")[simple], -print "surface. Grid size %d x %d (%d nodes)" % (ncol,nrow,ncol*nrow) -print "About %d datapoints (%.2f%% of nodes)" % (datapoints,percent) - -# Test flag -build_only = True # no output to files -build_only = False # output to files - -# Trimming distance -trimdist = 5*step # make trimming -trimdist = 0.0 # do not make trimming -if trimdist < step: - print "No trimming" -else: - print "With trimming",trimdist - -def surface(x,y): - if simple: - return 100+100*(1+float(x)/ncol)*(1+float(y)/nrow) - return 100+50*(math.cos(ax*x*x)*math.cos(ay*y*y)+1) - -def surfaceGen(): - while True: - if trimdist < step: - x = random.uniform(-1,ncol) # some points may be - y = random.uniform(-1,nrow) # out of grid - else: - trdist = int(trimdist/step+0.5) - x = random.uniform(-1+trdist,ncol-trdist) # all the points - y = random.uniform(-1+trdist,nrow-trdist) # are inside the grid - z = surface(x,y) - yield x,y,z - -def makeInputXYZ(outfile,nvals): - surgen = surfaceGen() - x,y,z = [],[],[] - fo = open(outfile,"wt") # for fromfile() - while(nvals > 0): - xv,yv,zv = surgen.next() - fo.write("%.3f %.3f %.3f\n" % (xv,yv,zv)) - x.append(xv) # for fromxyz() - y.append(yv) - z.append(zv) - nvals -= 1 - fo.close() - return x,y,z - -# create input data file with -xyzfile = "inpdata.xyz" # input for fromfile() -xp,yp,zp = makeInputXYZ(xyzfile, datapoints) - - -import BuildGrid - -# get file statistics -nvals,xmin,xmax,ymin,ymax,zmin,zmax,zavrg,zstnd = \ - BuildGrid.filestatistics(xyzfile) -print xyzfile,'statistics. Number of values',nvals -print 'X min %9.1f max %9.1f' % (xmin,xmax) -print 'Y min %9.1f max %9.1f' % (ymin,ymax) -print 'S min %9.1f max %9.1f' % (zmin,zmax) -print 'S avrg %7.2f stnd %7.3f' % (zavrg,zstnd) - -# build grid 'fromfile' -t0 = time.clock() -grid = BuildGrid.fromfile(xyzfile=xyzfile, - nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, - method='Good', # or 'Best' - not implemented - trimming=trimdist, # if no trimming - full grid - unvalue=123.321, # will be used if trimming > 0 - abserror=0.001, # may be == 0 - relerror=0.0001) # ignores if abserror > 0 -print 'fromfile():',xyzfile,len(grid)-ncol*nrow,"(%.2f sec, %.0f nodes/sec)" %\ - (time.clock()-t0,ncol*nrow/(time.clock()-t0)) - - -# put grid data to xyz file -if not build_only: - outfile = "outdata1.xyz" - t0 = time.clock() - rv = BuildGrid.tofile(filename=outfile, griddata=grid, gridtype='xyz', - nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, unvalue=1234.4321) - print 'tofile():',outfile,rv,"(%.2f sec)" % (time.clock()-t0) - - -# build grid from xyz lists -t0 = time.clock() -grid2 = BuildGrid.fromxyz(xdata=xp,ydata=yp,zdata=zp, - nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, - method='Good', # or 'Best' (not implemented) - trimming=trimdist, # if no trimming - full grid - unvalue=123.321, # will be used if trimming > 0 - abserror=0.001, # may be == 0 - relerror=0.0001) # ignores if abserror > 0 -print 'fromxyz():',len(grid)-ncol*nrow,"(%.2f sec, %.0f nodes/sec)" %\ - (time.clock()-t0,ncol*nrow/(time.clock()-t0)) - -# put grid to file -if not build_only: - outfile = "outdata2.xyz" - t0 = time.clock() - rv = BuildGrid.tofile(filename=outfile, griddata=grid2, gridtype='xyz', - nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, unvalue=1234.4321) - print 'tofile():',outfile,rv,"(%.2f sec)" % (time.clock()-t0) - - -# write full exact grid -if not build_only: - exactfile = "exactdata.xyz" - t0 = time.clock() - fo = open(exactfile,"wt") - for nr in xrange(nrow): - for nc in xrange(ncol): - fo.write("%.2f %.2f %.3f\n" % (nc,nr,surface(nc,nr))) - fo.close() - print 'exact file:',exactfile,"(%.2f sec)" % (time.clock()-t0) - - -if build_only: - sys.exit() - -# Compare Input & Output: -layer = max(5,min(ncol,nrow)/10) -def avst(left,rite,low,top): - av = st = 0.0 - nv = 0 - for nr in xrange(low,top): - for nc in xrange(left,rite): - d = grid[nr*ncol+nc]-surface(nc,nr) - av += d - st += d*d - nv += 1 - av /= nv - st = st/nv-av*av - if st > 0.0: st = math.sqrt(st) - return av,st - -print "Comparing %d x %d squares" % (layer,layer),"of grid lines" -av,st = avst(0,layer,0,layer) -print "Bottom Left: av = %8.3f st = %8.3f" % (av,st) -av,st = avst(ncol-layer,ncol,0,layer) -print "Bottom Right: av = %8.3f st = %8.3f" % (av,st) -av,st = avst(0,layer,nrow-layer,nrow) -print "Top Left: av = %8.3f st = %8.3f" % (av,st) -av,st = avst(ncol-layer,ncol,nrow-layer,nrow) -print "Top Right: av = %8.3f st = %8.3f" % (av,st) -av,st = avst(ncol/2-layer/2,ncol/2+layer/2,nrow/2-layer/2,nrow/2+layer/2) -print "Middle: av = %8.3f st = %8.3f" % (av,st) - + +""" Tests for BuildGrid.c module. +To view the grids I used QuikGrid from +http://www.PerspectiveEdge.com +""" + +import sys,math,random,time +from scipy.sandbox import buildgrid + +random.seed(7) + +global ncol,nrow,step,xmin,ymin,simple +xmin,ymin,step = 0.0,0.0,1.0 + +# Surface model: +simple = True # simple: (a1+b1*x)*(a2+b2*y) + # This is almost a plain. + +simple = False # !simple: cos(a*x*x)*cos(b*y*y) + # In this case only left bottom part of surface + # should be believable. + +def gridsizes(nodes,ratio=1.0): + # ratio = ncol/nrow + nodes = max(100,nodes) + ratio = max(0.1,min(ratio,10.0)) + nrow = int(math.sqrt(nodes/ratio)) + ncol = nodes/nrow+1 + return ncol,nrow + +ncol,nrow = gridsizes(10**5) # I used 10**3 - 10**7 nodes + +ax,ay = math.pi/(4*ncol+1),math.pi/(4*nrow+1) + +percent = 10.2 # how many data points w.r.t. grid nodes: +datapoints = int(0.01 * percent * ncol * nrow) or 5 +print "Testing",("complex","simple")[simple], +print "surface. Grid size %d x %d (%d nodes)" % (ncol,nrow,ncol*nrow) +print "About %d datapoints (%.2f%% of nodes)" % (datapoints,percent) + +# Test flag +build_only = True # no output to files +build_only = False # output to files + +# Trimming distance +trimdist = 5*step # make trimming +trimdist = 0.0 # do not make trimming +if trimdist < step: + print "No trimming" +else: + print "With trimming",trimdist + +def surface(x,y): + if simple: + return 100+100*(1+float(x)/ncol)*(1+float(y)/nrow) + return 100+50*(math.cos(ax*x*x)*math.cos(ay*y*y)+1) + +def surfaceGen(): + while True: + if trimdist < step: + x = random.uniform(-1,ncol) # some points may be + y = random.uniform(-1,nrow) # out of grid + else: + trdist = int(trimdist/step+0.5) + x = random.uniform(-1+trdist,ncol-trdist) # all the points + y = random.uniform(-1+trdist,nrow-trdist) # are inside the grid + z = surface(x,y) + yield x,y,z + +def makeInputXYZ(outfile,nvals): + surgen = surfaceGen() + x,y,z = [],[],[] + fo = open(outfile,"wt") # for fromfile() + while(nvals > 0): + xv,yv,zv = surgen.next() + fo.write("%.3f %.3f %.3f\n" % (xv,yv,zv)) + x.append(xv) # for fromxyz() + y.append(yv) + z.append(zv) + nvals -= 1 + fo.close() + return x,y,z + +# create input data file with +xyzfile = "inpdata.xyz" # input for fromfile() +xp,yp,zp = makeInputXYZ(xyzfile, datapoints) + + + +# get file statistics +nvals,xmin,xmax,ymin,ymax,zmin,zmax,zavrg,zstnd = \ + buildgrid.filestatistics(xyzfile) +print xyzfile,'statistics. Number of values',nvals +print 'X min %9.1f max %9.1f' % (xmin,xmax) +print 'Y min %9.1f max %9.1f' % (ymin,ymax) +print 'S min %9.1f max %9.1f' % (zmin,zmax) +print 'S avrg %7.2f stnd %7.3f' % (zavrg,zstnd) + +# build grid 'fromfile' +t0 = time.clock() +grid = buildgrid.fromfile(xyzfile=xyzfile, + nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, + method='Good', # or 'Best' - not implemented + trimming=trimdist, # if no trimming - full grid + unvalue=123.321, # will be used if trimming > 0 + abserror=0.001, # may be == 0 + relerror=0.0001) # ignores if abserror > 0 +print 'fromfile():',xyzfile,len(grid)-ncol*nrow,"(%.2f sec, %.0f nodes/sec)" %\ + (time.clock()-t0,ncol*nrow/(time.clock()-t0)) + + +# put grid data to xyz file +if not build_only: + outfile = "outdata1.xyz" + t0 = time.clock() + rv = buildgrid.tofile(filename=outfile, griddata=grid, gridtype='xyz', + nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, unvalue=1234.4321) + print 'tofile():',outfile,rv,"(%.2f sec)" % (time.clock()-t0) + + +# build grid from xyz lists +t0 = time.clock() +grid2 = buildgrid.fromxyz(xdata=xp,ydata=yp,zdata=zp, + nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, + method='Good', # or 'Best' (not implemented) + trimming=trimdist, # if no trimming - full grid + unvalue=123.321, # will be used if trimming > 0 + abserror=0.001, # may be == 0 + relerror=0.0001) # ignores if abserror > 0 +print 'fromxyz():',len(grid)-ncol*nrow,"(%.2f sec, %.0f nodes/sec)" %\ + (time.clock()-t0,ncol*nrow/(time.clock()-t0)) + +# put grid to file +if not build_only: + outfile = "outdata2.xyz" + t0 = time.clock() + rv = buildgrid.tofile(filename=outfile, griddata=grid2, gridtype='xyz', + nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, unvalue=1234.4321) + print 'tofile():',outfile,rv,"(%.2f sec)" % (time.clock()-t0) + + +# write full exact grid +if not build_only: + exactfile = "exactdata.xyz" + t0 = time.clock() + fo = open(exactfile,"wt") + for nr in xrange(nrow): + for nc in xrange(ncol): + fo.write("%.2f %.2f %.3f\n" % (nc,nr,surface(nc,nr))) + fo.close() + print 'exact file:',exactfile,"(%.2f sec)" % (time.clock()-t0) + + +if build_only: + sys.exit() + +# Compare Input & Output: +layer = max(5,min(ncol,nrow)/10) +def avst(left,rite,low,top): + av = st = 0.0 + nv = 0 + for nr in xrange(low,top): + for nc in xrange(left,rite): + d = grid[nr*ncol+nc]-surface(nc,nr) + av += d + st += d*d + nv += 1 + av /= nv + st = st/nv-av*av + if st > 0.0: st = math.sqrt(st) + return av,st + +print "Comparing %d x %d squares" % (layer,layer),"of grid lines" +av,st = avst(0,layer,0,layer) +print "Bottom Left: av = %8.3f st = %8.3f" % (av,st) +av,st = avst(ncol-layer,ncol,0,layer) +print "Bottom Right: av = %8.3f st = %8.3f" % (av,st) +av,st = avst(0,layer,nrow-layer,nrow) +print "Top Left: av = %8.3f st = %8.3f" % (av,st) +av,st = avst(ncol-layer,ncol,nrow-layer,nrow) +print "Top Right: av = %8.3f st = %8.3f" % (av,st) +av,st = avst(ncol/2-layer/2,ncol/2+layer/2,nrow/2-layer/2,nrow/2+layer/2) +print "Middle: av = %8.3f st = %8.3f" % (av,st) + Modified: branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_autocorr.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_autocorr.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_autocorr.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -9,13 +9,12 @@ from numpy.ctypeslib import ndpointer, load_library from ctypes import c_uint +from scipy.sandbox.cdavid.autocorr import _raw_autocorr_1d, \ + _raw_autocorr_1d_noncontiguous, \ + autocorr_oneside_nofft as autocorr,\ + autocorr_fft , nextpow2, \ + _autocorr_oneside_nofft_py as autocorr_py -from cdavid.autocorr import _raw_autocorr_1d, _raw_autocorr_1d_noncontiguous -from cdavid.autocorr import autocorr_oneside_nofft as autocorr -from cdavid.autocorr import autocorr_fft , nextpow2 -from cdavid.autocorr import _autocorr_oneside_nofft_py as autocorr_py - - import numpy # number of decimals to check Modified: branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_lpc.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_lpc.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_lpc.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -7,13 +7,9 @@ from numpy.ctypeslib import ndpointer, load_library from ctypes import c_uint +from scipy.sandbox.cdavid.lpc import _lpc2_py as lpc_py, \ + lpc_ref, lpc2, autocorr_oneside_nofft - -from cdavid.lpc import _lpc2_py as lpc_py -from cdavid.lpc import lpc_ref, lpc2 -from cdavid.autocorr import autocorr_oneside_nofft - - import numpy # number of decimals to check Modified: branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_segmentaxis.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_segmentaxis.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/cdavid/tests/test_segmentaxis.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -6,7 +6,7 @@ import numpy as N -from cdavid.segmentaxis import segment_axis +from scipy.sandbox.cdavid.segmentaxis import segment_axis # #Optional: Modified: branches/testing_cleanup/scipy/sandbox/constants/constants.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/constants/constants.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/constants/constants.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -12,7 +12,7 @@ physical constants: imported from CODATA unit conversion: see e.g. NIST special publication 811 Use at own risk: double-check values before calculating your Mars orbit-insertion burn. -Some constants exist in a few variants, which are marked with sufixes. +Some constants exist in a few variants, which are marked with suffixes. The ones without any suffix should be the most common one. """ Modified: branches/testing_cleanup/scipy/sandbox/delaunay/tests/test_triangulate.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/delaunay/tests/test_triangulate.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/delaunay/tests/test_triangulate.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,6 +1,7 @@ from scipy.sandbox import delaunay as dlny from numpy import random import scipy as sp +from scipy.testing import * def onright(x0, y0, x1, y1, x, y): """Return True if (x,y) is to the right of the vector from (x0,y0) to @@ -16,12 +17,11 @@ assert r2 < r -class TestSanity(object): - def setup_method(self, method): +class TestSanity(TestCase): + def setUp(self): self.rs = random.RandomState(1234567890) def test_counts(self): - assert False for n in (10, 30, 100, 300, 1000, 3000): x, y = self.rs.uniform(0, 100, size=(2, n)) tri = dlny.Triangulation(x, y) @@ -35,7 +35,6 @@ assert sp.sum((tri.triangle_neighbors == -1).astype(sp.int32).flat) == k def test_ccw_triangles(self): - assert False for n in (10, 30, 100, 300, 1000, 3000): x, y = self.rs.uniform(0, 100, size=(2, n)) tri = dlny.Triangulation(x, y) @@ -44,7 +43,6 @@ assert not onright(x[i], y[i], x[j], y[j], x[k], y[k]) def test_ccw_hull(self): - assert False for n in (10, 30, 100, 300, 1000, 3000): x, y = self.rs.uniform(0, 100, size=(2, n)) tri = dlny.Triangulation(x, y) @@ -57,7 +55,6 @@ assert not onright(x[i], y[i], x[j], y[j], x[k], y[k]) def test_circle_condition(self): - assert False for n in (10, 30, 100, 300, 1000, 3000): x, y = self.rs.uniform(0, 100, size=(2, n)) tri = dlny.Triangulation(x, y) @@ -68,3 +65,8 @@ alldist2 = (sp.subtract.outer(x, tri.circumcenters[:,0])**2 + sp.subtract.outer(y, tri.circumcenters[:,1])**2) assert sp.alltrue(r2 <= alldist2) + + +if __name__ == '__main__': + unittest.main() + Modified: branches/testing_cleanup/scipy/sandbox/fdfpack/tests/test_fdf.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/fdfpack/tests/test_fdf.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/fdfpack/tests/test_fdf.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,8 +1,7 @@ - from scipy.testing import * -from fdfpack import periodic_finite_difference as diff +from scipy.sandbox.fdfpack import periodic_finite_difference as diff from numpy import arange, add, array,sin,cos,pi Modified: branches/testing_cleanup/scipy/sandbox/lobpcg/tests/large_scale.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/lobpcg/tests/large_scale.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/lobpcg/tests/large_scale.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,4 +1,5 @@ -from scipy import * +from scipy import array, arange, ones, sort, cos, pi, rand, \ + set_printoptions, r_ from scipy.sandbox import lobpcg from scipy.sparse import spdiags, speye from pylab import loglog, show, xlabel, ylabel, title Modified: branches/testing_cleanup/scipy/sandbox/lobpcg/tests/test_lobpcg.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/lobpcg/tests/test_lobpcg.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/lobpcg/tests/test_lobpcg.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,4 +1,5 @@ -from scipy import * +from scipy import array, arange, ones, sort, cos, pi, rand, \ + set_printoptions, r_, diag, linalg from scipy.sandbox import lobpcg from symeig import symeig from pylab import plot, show, legend, xlabel, ylabel Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/extras.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/extras.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/extras.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -35,7 +35,7 @@ from numpy.core.numeric import array as nxarray from numpy.core.fromnumeric import asarray as nxasarray -from numpy.lib.index_tricks import concatenator +from numpy.lib.index_tricks import AxisConcatenator import numpy.lib.function_base as function_base #............................................................................... @@ -568,11 +568,11 @@ #---- --- Concatenation helpers --- #####-------------------------------------------------------------------------- -class mconcatenator(concatenator): +class mconcatenator(AxisConcatenator): """Translates slice objects to concatenation along an axis.""" def __init__(self, axis=0): - concatenator.__init__(self, axis, matrix=False) + AxisConcatenator.__init__(self, axis, matrix=False) def __getitem__(self,key): if isinstance(key, str): Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/morestats.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/morestats.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/morestats.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -21,10 +21,10 @@ import numpy.core.numeric as numeric from numpy.core.numeric import concatenate -import maskedarray as MA -from maskedarray.core import masked, nomask, MaskedArray, masked_array -from maskedarray.extras import apply_along_axis, dot -from maskedarray.mstats import trim_both, trimmed_stde, mquantiles, mmedian, stde_median +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray.core import masked, nomask, MaskedArray, masked_array +from scipy.sandbox.maskedarray.extras import apply_along_axis, dot +from scipy.sandbox.maskedarray.mstats import trim_both, trimmed_stde, mquantiles, mmedian, stde_median from scipy.stats.distributions import norm, beta, t, binom from scipy.stats.morestats import find_repeats Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/mrecords.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/mrecords.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/mrecords.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -28,10 +28,10 @@ _byteorderconv = numpy.core.records._byteorderconv _typestr = ntypes._typestr -import maskedarray -from maskedarray import MaskedArray, masked, nomask, masked_array,\ +import scipy.sandbox.maskedarray +from scipy.sandbox.maskedarray import MaskedArray, masked, nomask, masked_array,\ make_mask, mask_or, getmask, getmaskarray, filled -from maskedarray.core import default_fill_value, masked_print_option +from scipy.sandbox.maskedarray.core import default_fill_value, masked_print_option import warnings Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/mstats.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/mstats.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/mstats.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -19,9 +19,9 @@ import numpy.core.numeric as numeric from numpy.core.numeric import concatenate -import maskedarray -from maskedarray.core import masked, nomask, MaskedArray, masked_array -from maskedarray.extras import apply_along_axis, dot +import scipy.sandbox.maskedarray +from scipy.sandbox.maskedarray.core import masked, nomask, MaskedArray, masked_array +from scipy.sandbox.maskedarray.extras import apply_along_axis, dot __all__ = ['cov','meppf','plotting_positions','meppf','mmedian','mquantiles', 'stde_median','trim_tail','trim_both','trimmed_mean','trimmed_stde', Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_core.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_core.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_core.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -14,15 +14,13 @@ import numpy import numpy.core.fromnumeric as fromnumeric -from scipy.testing import NumpyTest, TestCase -from scipy.testing.utils import build_err_msg +from scipy.testing import * from numpy import array as narray -import maskedarray.testutils -from maskedarray.testutils import * +from scipy.sandbox.maskedarray.testutils import * -import maskedarray.core as coremodule -from maskedarray.core import * +import scipy.sandbox.maskedarray.core as coremodule +from scipy.sandbox.maskedarray.core import * pi = numpy.pi Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_extras.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_extras.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_extras.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -12,16 +12,13 @@ __date__ = '$Date$' import numpy as N -from scipy.testing import NumpyTest, TestCase -from scipy.testing.utils import build_err_msg +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import * +import scipy.sandbox.maskedarray.testutils +from scipy.sandbox.maskedarray.testutils import * -import maskedarray.core -from maskedarray.core import * -import maskedarray.extras -from maskedarray.extras import * +from scipy.sandbox.maskedarray.core import * +from scipy.sandbox.maskedarray.extras import * class TestAverage(TestCase): "Several tests of average. Why so many ? Good point..." Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_morestats.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_morestats.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_morestats.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -11,19 +11,14 @@ __date__ = '$Date: 2007-10-04 15:31:14 -0400 (Thu, 04 Oct 2007) $' import numpy +from scipy.testing import * +from scipy.sandbox.maskedarray import masked, masked_array +import scipy.sandbox.maskedarray.mstats +from scipy.sandbox.maskedarray.mstats import * +from scipy.sandbox.maskedarray.morestats import * +from scipy.sandbox.maskedarray.testutils import * -import maskedarray -from maskedarray import masked, masked_array -import maskedarray.mstats -from maskedarray.mstats import * -import maskedarray.morestats -from maskedarray.morestats import * - -import maskedarray.testutils -from maskedarray.testutils import * - - class TestMisc(TestCase): # def __init__(self, *args, **kwargs): Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_mrecords.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_mrecords.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_mrecords.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -14,19 +14,15 @@ import numpy as N import numpy.core.fromnumeric as fromnumeric -from scipy.testing import NumpyTest, TestCase -from scipy.testing.utils import build_err_msg +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import * +from scipy.sandbox.maskedarray.testutils import * +from scipy.sandbox import maskedarray +from scipy.sandbox.maskedarray import masked_array, masked, nomask -import maskedarray -from maskedarray import masked_array, masked, nomask - #import maskedarray.mrecords #from maskedarray.mrecords import mrecarray, fromarrays, fromtextfile, fromrecords -import maskedarray.mrecords -from maskedarray.mrecords import MaskedRecords, \ +from scipy.sandbox.maskedarray.mrecords import MaskedRecords, \ fromarrays, fromtextfile, fromrecords, addfield #.............................................................................. Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_mstats.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_mstats.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_mstats.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -12,14 +12,13 @@ import numpy -import maskedarray -from maskedarray import masked, masked_array +from scipy.testing import * +from scipy.sandbox import maskedarray +from scipy.sandbox.maskedarray import masked, masked_array -import maskedarray.testutils -from maskedarray.testutils import * +from scipy.sandbox.maskedarray.testutils import * +from scipy.sandbox.maskedarray.mstats import * -from maskedarray.mstats import * - #.............................................................................. class TestQuantiles(TestCase): "Base test class for MaskedArrays." Modified: branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_subclassing.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_subclassing.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/maskedarray/tests/test_subclassing.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -13,13 +13,12 @@ import numpy as N import numpy.core.numeric as numeric -from scipy.testing import NumpyTest, TestCase +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import * +from scipy.sandbox.maskedarray.testutils import * -import maskedarray.core as coremodule -from maskedarray.core import * +import scipy.sandbox.maskedarray.core as coremodule +from scipy.sandbox.maskedarray.core import * class SubArray(N.ndarray): Modified: branches/testing_cleanup/scipy/sandbox/montecarlo/tests/test_dictsampler.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/montecarlo/tests/test_dictsampler.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/montecarlo/tests/test_dictsampler.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -12,15 +12,12 @@ import sys from scipy.testing import * -from numpy import * +from numpy import sum, array, average, sqrt #from scipy.montecarlo import * from scipy.sandbox.montecarlo import * from scipy import stats -import unittest - - class test_dict_sampler(TestCase): def test_simple(self): """ Modified: branches/testing_cleanup/scipy/sandbox/montecarlo/tests/test_intsampler.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/montecarlo/tests/test_intsampler.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/montecarlo/tests/test_intsampler.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -20,12 +20,10 @@ import sys from scipy.testing import * -from numpy import * from scipy.sandbox.montecarlo import * from scipy import stats - class test_int_sampler(TestCase): def test_simple(self): # Sample from a Poisson distribution, P(lambda = 10.0) Modified: branches/testing_cleanup/scipy/sandbox/numexpr/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/numexpr/__init__.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/numexpr/__init__.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,7 +1,4 @@ -from numexpr.info import __doc__ -from numexpr.expressions import E -from numexpr.compiler import numexpr, disassemble, evaluate +from scipy.sandbox.numexpr.info import __doc__ +from scipy.sandbox.numexpr.expressions import E +from scipy.sandbox.numexpr.compiler import numexpr, disassemble, evaluate -def test(level=1, verbosity=1): - from numpy.testing import NumpyTest - NumpyTest().test(level, verbosity) Modified: branches/testing_cleanup/scipy/sandbox/numexpr/compiler.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/numexpr/compiler.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/numexpr/compiler.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,7 +1,7 @@ import sys import numpy -from numexpr import interpreter, expressions +from scipy.sandbox.numexpr import interpreter, expressions typecode_to_kind = {'b': 'bool', 'i': 'int', 'l': 'long', 'f': 'float', 'c': 'complex', 's': 'str', 'n' : 'none'} Modified: branches/testing_cleanup/scipy/sandbox/numexpr/expressions.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/numexpr/expressions.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/numexpr/expressions.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -6,7 +6,7 @@ import numpy -from numexpr import interpreter +from scipy.sandbox.numexpr import interpreter class Expression(object): def __init__(self): Modified: branches/testing_cleanup/scipy/sandbox/numexpr/tests/test_numexpr.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/numexpr/tests/test_numexpr.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/numexpr/tests/test_numexpr.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -1,9 +1,10 @@ import new -from numpy import * +from numpy import array, arange, sin, zeros, sum, int32, empty, \ + prod, uint16, complex_, float64, rec from scipy.testing import * -from numexpr import E, numexpr, evaluate, disassemble +from scipy.sandbox.numexpr import E, numexpr, evaluate, disassemble class test_numexpr(TestCase): Modified: branches/testing_cleanup/scipy/sandbox/pyloess/mpyloess.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/pyloess/mpyloess.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/pyloess/mpyloess.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -42,9 +42,8 @@ nempty = numeric.empty nlogical_not = numpy.logical_not -import maskedarray.core -from maskedarray.core import masked, nomask, mask_or -from maskedarray.core import masked_array as marray +from scipy.sandbox.maskedarray.core import masked, nomask, mask_or, \ + masked_array as marray import _lowess, _stl, _mloess Modified: branches/testing_cleanup/scipy/sandbox/pyloess/tests/test_mpyloess.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/pyloess/tests/test_mpyloess.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/pyloess/tests/test_mpyloess.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -18,19 +18,16 @@ import numpy.core.numeric as numeric fromiter = numpy.fromiter -import maskedarray +from scipy.sandbox import maskedarray marray = maskedarray.masked_array masked_values = maskedarray.masked_values -from scipy.testing import NumpyTest, TestCase -from maskedarray.testutils import build_err_msg, \ +from scipy.testing import * +from scipy.sandbox.maskedarray.testutils import build_err_msg, \ assert_equal, assert_almost_equal +from scipy.sandbox.pyloess.mpyloess import lowess, stl, loess, loess_anova -import mpyloess -reload(mpyloess) -from mpyloess import lowess, stl, loess, loess_anova - #####--------------------------------------------------------------------------- #---- --- LOWESS --- #####--------------------------------------------------------------------------- Modified: branches/testing_cleanup/scipy/sandbox/pyloess/tests/test_pyloess.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/pyloess/tests/test_pyloess.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/pyloess/tests/test_pyloess.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -21,13 +21,9 @@ narray = numpy.array -from scipy.testing import NumpyTest, TestCase -from scipy.testing.utils import build_err_msg, \ - assert_equal, assert_almost_equal +from scipy.testing import * -import pyloess -reload(pyloess) -from pyloess import lowess, stl, loess, loess_anova +from scipy.sandbox.pyloess import lowess, stl, loess, loess_anova #####--------------------------------------------------------------------------- #---- --- LOWESS --- Modified: branches/testing_cleanup/scipy/sandbox/rbf/tests/test_rbf.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/rbf/tests/test_rbf.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/rbf/tests/test_rbf.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -6,7 +6,7 @@ from numpy import linspace, sin, random, exp -from rbf.rbf import Rbf +from scipy.sandbox.rbf.rbf import Rbf class TestRbf1d(TestCase): Modified: branches/testing_cleanup/scipy/sandbox/spline/tests/test_fitpack.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/spline/tests/test_fitpack.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/spline/tests/test_fitpack.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -16,14 +16,14 @@ from numpy import array, arange, around, pi, sin, ravel, zeros, asarray -from spline.fitpack import splprep, splrep, splev, sproot, splint, spalde -from spline.fitpack import bisplev, bisplrep, splprep +from scipy.sandbox.spline.fitpack import splprep, splrep, splev, sproot, \ + splint, spalde, bisplev, bisplrep, splprep set_local_path() from dierckx_test_data import * +restore_path() - class TestSplrepSplev(TestCase): def test_curfit_against_dierckx_smth(self): x,y = curfit_test['x'],curfit_test['y'] Modified: branches/testing_cleanup/scipy/sandbox/spline/tests/test_spline.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/spline/tests/test_spline.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/spline/tests/test_spline.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -17,16 +17,14 @@ from numpy import array, arange, around, pi, sin, cos -from spline.spline import UnivariateSpline,LSQUnivariateSpline,\ - InterpolatedUnivariateSpline -from spline.spline import LSQBivariateSpline, SmoothBivariateSpline,\ +from scipy.sandbox.spline.spline import UnivariateSpline,LSQUnivariateSpline,\ + InterpolatedUnivariateSpline, LSQBivariateSpline, SmoothBivariateSpline,\ RectBivariateSpline - set_local_path() from dierckx_test_data import * +restore_path() - class TestUnivariateSpline(TestCase): def test_linear_constant(self): x = [1,2,3] Modified: branches/testing_cleanup/scipy/sandbox/timeseries/dates.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/dates.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/dates.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -25,7 +25,7 @@ import numpy.core.numerictypes as ntypes from numpy.core.numerictypes import generic -import maskedarray as MA +import scipy.sandbox.maskedarray as MA from parser import DateFromString, DateTimeFromString Modified: branches/testing_cleanup/scipy/sandbox/timeseries/extras.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/extras.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/extras.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -12,8 +12,8 @@ import numpy -import maskedarray -from maskedarray import masked +import scipy.sandbox.maskedarray +from scipy.sandbox.maskedarray import masked import const as _c from tseries import TimeSeries Modified: branches/testing_cleanup/scipy/sandbox/timeseries/lib/filters.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/lib/filters.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/lib/filters.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -17,8 +17,8 @@ from scipy.signal import convolve, get_window -import maskedarray as MA -from maskedarray import MaskedArray, nomask, getmask, getmaskarray, masked +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray import MaskedArray, nomask, getmask, getmaskarray, masked marray = MA.array from moving_funcs import mov_average_expw, cmov_average, cmov_mean, \ Modified: branches/testing_cleanup/scipy/sandbox/timeseries/lib/interpolate.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/lib/interpolate.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/lib/interpolate.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -14,9 +14,9 @@ from scipy.interpolate import fitpack -import maskedarray as MA -from maskedarray.core import masked, nomask, getmask -from maskedarray.extras import flatnotmasked_edges +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray.core import masked, nomask, getmask +from scipy.sandbox.maskedarray.extras import flatnotmasked_edges marray = MA.array __all__ = [ Modified: branches/testing_cleanup/scipy/sandbox/timeseries/lib/moving_funcs.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/lib/moving_funcs.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/lib/moving_funcs.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -23,11 +23,11 @@ from scipy.signal import convolve, get_window -import maskedarray as MA -from maskedarray import MaskedArray, nomask, getmask, getmaskarray, masked +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray import MaskedArray, nomask, getmask, getmaskarray, masked marray = MA.array -from timeseries.cseries import MA_mov_sum, MA_mov_median, MA_mov_min, \ +from scipy.sandbox.timeseries.cseries import MA_mov_sum, MA_mov_median, MA_mov_min, \ MA_mov_max def _process_result_dict(orig_data, result_dict): Modified: branches/testing_cleanup/scipy/sandbox/timeseries/report.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/report.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/report.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -59,8 +59,8 @@ import sys import operator, types, copy -import timeseries as ts -import maskedarray as ma +import tseries as ts +import scipy.sandbox.maskedarray as ma __all__ = [ 'Report', 'wrap_onspace', 'wrap_onspace_strict', Modified: branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_dates.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_dates.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_dates.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -16,21 +16,17 @@ import numpy import numpy.core.fromnumeric as fromnumeric import numpy.core.numeric as numeric -from scipy.testing import NumpyTest, TestCase -from scipy.testing.utils import build_err_msg +from scipy.testing import * -import maskedarray -from maskedarray import masked_array +from scipy.sandbox.maskedarray import masked_array -import maskedarray.testutils -from maskedarray.testutils import assert_equal, assert_array_equal +from scipy.sandbox.maskedarray.testutils import assert_equal, assert_array_equal -import timeseries as ts -from timeseries import const as C -from timeseries.parser import DateFromString, DateTimeFromString -from timeseries import Date, DateArray,\ - now, date_array, date_array_fromlist -from timeseries.cseries import freq_dict +import scipy.sandbox.timeseries as ts +from scipy.sandbox.timeseries import const as C, Date, DateArray,\ + now, date_array, date_array_fromlist +from scipy.sandbox.timeseries.parser import DateFromString, DateTimeFromString +from scipy.sandbox.timeseries.cseries import freq_dict class TestCreation(TestCase): Modified: branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_extras.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_extras.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_extras.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -13,14 +13,13 @@ import numpy -from scipy.testing import NumpyTest, TestCase -import maskedarray -from maskedarray import masked -from maskedarray.testutils import assert_equal, assert_almost_equal +from scipy.testing import * +import scipy.sandbox.maskedarray +from scipy.sandbox.maskedarray import masked +from scipy.sandbox.maskedarray.testutils import assert_equal, assert_almost_equal -from timeseries import time_series, Date -from timeseries import extras -from timeseries.extras import * +from scipy.sandbox.timeseries import time_series, Date, extras +from scipy.sandbox.timeseries.extras import * #.............................................................................. class TestMisc(TestCase): Modified: branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_timeseries.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_timeseries.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_timeseries.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -15,21 +15,18 @@ from numpy import bool_, complex_, float_, int_, object_ import numpy.core.fromnumeric as fromnumeric import numpy.core.numeric as numeric -from scipy.testing import NumpyTest, TestCase -from scipy.testing.utils import build_err_msg +from scipy.testing import * -import maskedarray -import maskedarray as MA -from maskedarray import masked_array, masked, nomask +import scipy.sandbox.maskedarray +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray import masked_array, masked, nomask -import maskedarray.testutils -from maskedarray.testutils import assert_equal, assert_array_equal +from scipy.sandbox.maskedarray.testutils import assert_equal, assert_array_equal -from timeseries import tseries -from timeseries import Date, date_array_fromlist, date_array_fromrange, date_array, thisday -from timeseries import time_series, TimeSeries, adjust_endpoints, \ - mask_period, align_series, align_with, fill_missing_dates, tsmasked, \ - concatenate, stack, split +from scipy.sandbox.timeseries import tseries, Date, date_array_fromlist, \ + date_array_fromrange, date_array, thisday, time_series, TimeSeries, \ + adjust_endpoints, mask_period, align_series, align_with, \ + fill_missing_dates, tsmasked, concatenate, stack, split class TestCreation(TestCase): "Base test class for MaskedArrays." Modified: branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_trecords.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_trecords.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/tests/test_trecords.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -14,22 +14,20 @@ import numpy import numpy.core.fromnumeric as fromnumeric -from scipy.testing import NumpyTest, TestCase -from scipy.testing.utils import build_err_msg +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import assert_equal, assert_array_equal, assert_equal_records +from scipy.sandbox.maskedarray.testutils import assert_equal, assert_array_equal, assert_equal_records -import maskedarray.core as MA -import maskedarray.mrecords as MR -from maskedarray.mrecords import addfield +import scipy.sandbox.maskedarray.core as MA +import scipy.sandbox.maskedarray.mrecords as MR +from scipy.sandbox.maskedarray.mrecords import addfield -from maskedarray.core import getmaskarray, nomask, masked_array +from scipy.sandbox.maskedarray.core import getmaskarray, nomask, masked_array -from timeseries import trecords -from timeseries.trecords import TimeSeriesRecords, TimeSeries,\ - fromarrays, fromtextfile, fromrecords, \ - date_array, time_series +from scipy.sandbox.timeseries.trecords import \ + TimeSeriesRecords, TimeSeries,\ + fromarrays, fromtextfile, fromrecords, \ + date_array, time_series #.............................................................................. Modified: branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -26,17 +26,15 @@ from numpy.core.records import format_parser, recarray, record from numpy.core.records import fromarrays as recfromarrays -import maskedarray as MA +import scipy.sandbox.maskedarray as MA #MaskedArray = MA.MaskedArray -from maskedarray.core import MaskedArray, MAError, default_fill_value, \ - masked_print_option -from maskedarray.core import masked, nomask, getmask, getmaskarray, make_mask,\ +from scipy.sandbox.maskedarray.core import MaskedArray, MAError, default_fill_value, \ + masked_print_option, masked, nomask, getmask, getmaskarray, make_mask,\ make_mask_none, mask_or, masked_array, filled -import maskedarray.mrecords as MR -from maskedarray.mrecords import _checknames, _guessvartypes, openfile,\ - MaskedRecords -from maskedarray.mrecords import fromrecords as mrecfromrecords +import scipy.sandbox.maskedarray.mrecords as MR +from scipy.sandbox.maskedarray.mrecords import _checknames, _guessvartypes, openfile,\ + MaskedRecords, fromrecords as mrecfromrecords from tseries import TimeSeries, time_series, _getdatalength from dates import Date, DateArray, date_array Modified: branches/testing_cleanup/scipy/sandbox/timeseries/tseries.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/tseries.py 2008-01-04 00:20:17 UTC (rev 3777) +++ branches/testing_cleanup/scipy/sandbox/timeseries/tseries.py 2008-01-04 01:29:56 UTC (rev 3778) @@ -25,8 +25,8 @@ from numpy.core.records import recarray from numpy.core.records import fromarrays as recfromarrays -import maskedarray -from maskedarray import MaskedArray, MAError, masked, nomask, \ +import scipy.sandbox.maskedarray as maskedarray +from scipy.sandbox.maskedarray import MaskedArray, MAError, masked, nomask, \ filled, getmask, getmaskarray, hsplit, make_mask_none, mask_or, make_mask, \ masked_array From scipy-svn at scipy.org Fri Jan 4 02:01:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 4 Jan 2008 01:01:00 -0600 (CST) Subject: [Scipy-svn] r3779 - in trunk/scipy/sparse: . sparsetools tests Message-ID: <20080104070100.B1BE439C010@new.scipy.org> Author: wnbell Date: 2008-01-04 01:00:52 -0600 (Fri, 04 Jan 2008) New Revision: 3779 Modified: trunk/scipy/sparse/bsr.py trunk/scipy/sparse/compressed.py trunk/scipy/sparse/sparsetools/sparsetools.h trunk/scipy/sparse/sparsetools/sparsetools.i trunk/scipy/sparse/sparsetools/sparsetools.py trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx trunk/scipy/sparse/tests/test_base.py Log: added eliminate_zeros() to compressed formats Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-04 01:29:56 UTC (rev 3778) +++ trunk/scipy/sparse/bsr.py 2008-01-04 07:00:52 UTC (rev 3779) @@ -434,7 +434,29 @@ ############################################################## # methods that examine or modify the internal data structure # ############################################################## - + + def eliminate_zeros(self): + R,C = self.blocksize + M,N = self.shape + + mask = (self.data != 0).reshape(-1,R*C).sum(axis=1) #nonzero blocks + + nonzero_blocks = mask.nonzero()[0] + + if len(nonzero_blocks) == 0: + return #nothing to do + + self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks] + + from csr import csr_matrix + + # modifies self.indptr and self.indices *in place* + proxy = csr_matrix((mask,self.indices,self.indptr),shape=(M/R,N/C)) + proxy.eliminate_zeros() + + self.prune() + + def sum_duplicates(self): raise NotImplementedError Modified: trunk/scipy/sparse/compressed.py =================================================================== --- trunk/scipy/sparse/compressed.py 2008-01-04 01:29:56 UTC (rev 3778) +++ trunk/scipy/sparse/compressed.py 2008-01-04 07:00:52 UTC (rev 3779) @@ -555,6 +555,17 @@ # methods that examine or modify the internal data structure # ############################################################## + def eliminate_zeros(self): + """Remove zero entries from the matrix + + The is an *in place* operation + """ + fn = sparsetools.csr_eliminate_zeros + M,N = self._swap(self.shape) + fn( M, N, self.indptr, self.indices, self.data) + + self.prune() #nnz may have changed + def sum_duplicates(self): """Eliminate duplicate matrix entries by adding them together @@ -572,8 +583,10 @@ def __get_sorted(self): """Determine whether the matrix has sorted indices - True if the indices of the matrix are in - sorted order, False otherwise. + Returns + - True: if the indices of the matrix are in sorted order + - False: otherwise + """ #first check to see if result was cached Modified: trunk/scipy/sparse/sparsetools/sparsetools.h =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.h 2008-01-04 01:29:56 UTC (rev 3778) +++ trunk/scipy/sparse/sparsetools/sparsetools.h 2008-01-04 07:00:52 UTC (rev 3779) @@ -887,7 +887,8 @@ * T Ax[nnz(A)] - nonzeros * * Note: - * Ap,Aj, and Ax will be modified *inplace* + * The column indicies within each row must be in sorted order. + * Ap, Aj, and Ax will be modified *inplace* * */ template @@ -916,49 +917,47 @@ } Ap[i+1] = nnz; } +} - - //method that works on unsorted indices -// std::vector next(n_col,-1); -// std::vector sums(n_col, 0); -// -// I nnz = 0; -// -// I row_start = 0; -// I row_end = 0; -// -// for(I i = 0; i < n_row; i++){ -// I head = -2; -// -// row_start = row_end; //Ap[i] may have been changed -// row_end = Ap[i+1]; //Ap[i+1] is safe -// -// for(I jj = row_start; jj < row_end; jj++){ -// I j = Aj[jj]; -// -// sums[j] += Ax[jj]; -// -// if(next[j] == -1){ -// next[j] = head; -// head = j; -// } -// } -// -// while(head != -2){ -// I curr = head; //current column -// head = next[curr]; -// -// if(sums[curr] != 0){ -// Aj[nnz] = curr; -// Ax[nnz] = sums[curr]; -// nnz++; -// } -// -// next[curr] = -1; -// sums[curr] = 0; -// } -// Ap[i+1] = nnz; -// } +/* + * Eliminate zero entries from CSR matrix A + * + * + * Input Arguments: + * I n_row - number of rows in A (and B) + * I n_col - number of columns in A (and B) + * I Ap[n_row+1] - row pointer + * I Aj[nnz(A)] - column indices + * T Ax[nnz(A)] - nonzeros + * + * Note: + * Ap, Aj, and Ax will be modified *inplace* + * + */ +template +void csr_eliminate_zeros(const I n_row, + const I n_col, + I Ap[], + I Aj[], + T Ax[]) +{ + I nnz = 0; + I row_end = 0; + for(I i = 0; i < n_row; i++){ + I jj = row_end; + row_end = Ap[i+1]; + while( jj < row_end ){ + I j = Aj[jj]; + T x = Ax[jj]; + if(x != 0){ + Aj[nnz] = j; + Ax[nnz] = x; + nnz++; + } + jj++; + } + Ap[i+1] = nnz; + } } @@ -985,8 +984,6 @@ * Note: * Input: row and column indices *are not* assumed to be ordered * - * Output: CSR column indices *will be* in sorted order - * * Note: duplicate entries are carried over to the CSR represention * * Complexity: Linear. Specifically O(nnz(A) + max(n_row,n_col)) Modified: trunk/scipy/sparse/sparsetools/sparsetools.i =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.i 2008-01-04 01:29:56 UTC (rev 3778) +++ trunk/scipy/sparse/sparsetools/sparsetools.i 2008-01-04 07:00:52 UTC (rev 3779) @@ -259,6 +259,11 @@ /* + * Remove zeros + */ +INSTANTIATE_ALL(csr_eliminate_zeros) + +/* * Sum duplicate entries. */ INSTANTIATE_ALL(csr_sum_duplicates) Modified: trunk/scipy/sparse/sparsetools/sparsetools.py =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.py 2008-01-04 01:29:56 UTC (rev 3778) +++ trunk/scipy/sparse/sparsetools/sparsetools.py 2008-01-04 07:00:52 UTC (rev 3779) @@ -1055,6 +1055,25 @@ """ return _sparsetools.csr_sort_indices(*args) +def csr_eliminate_zeros(*args): + """ + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, signed char Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned char Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, short Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned short Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, int Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned int Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, long long Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned long long Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, float Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, double Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, long double Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_cfloat_wrapper Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_cdouble_wrapper Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax) + """ + return _sparsetools.csr_eliminate_zeros(*args) + def csr_sum_duplicates(*args): """ csr_sum_duplicates(int n_row, int n_col, int Ap, int Aj, signed char Ax) Modified: trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-01-04 01:29:56 UTC (rev 3778) +++ trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-01-04 07:00:52 UTC (rev 3779) @@ -77001,6 +77001,1213 @@ } +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + signed char *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_BYTE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (signed char*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned char *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_UBYTE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned char*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + short *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_SHORT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (short*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned short *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_USHORT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned short*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + int *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_INT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (int*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned int *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_UINT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned int*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + long long *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_LONGLONG); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (long long*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned long long *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_ULONGLONG); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned long long*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + float *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_FLOAT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (float*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + double *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_DOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (double*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + long double *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_LONGDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (long double*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_cfloat_wrapper *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CFLOAT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_cfloat_wrapper*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_cdouble_wrapper *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_cdouble_wrapper*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_clongdouble_wrapper *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CLONGDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_clongdouble_wrapper*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[6]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 5); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_1(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_2(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_3(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_4(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_5(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_6(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_7(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_8(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_9(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_10(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_11(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_12(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_13(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_14(self, args); + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'csr_eliminate_zeros'.\n Possible C/C++ prototypes are:\n"" csr_eliminate_zeros<(int,signed char)>(int const,int const,int [],int [],signed char [])\n"" csr_eliminate_zeros<(int,unsigned char)>(int const,int const,int [],int [],unsigned char [])\n"" csr_eliminate_zeros<(int,short)>(int const,int const,int [],int [],short [])\n"" csr_eliminate_zeros<(int,unsigned short)>(int const,int const,int [],int [],unsigned short [])\n"" csr_eliminate_zeros<(int,int)>(int const,int const,int [],int [],int [])\n"" csr_eliminate_zeros<(int,unsigned int)>(int const,int const,int [],int [],unsigned int [])\n"" csr_eliminate_zeros<(int,long long)>(int const,int const,int [],int [],long long [])\n"" csr_eliminate_zeros<(int,unsigned long long)>(int const,int const,int [],int [],unsigned long long [])\n"" csr_eliminate_zeros<(int,float)>(int const,int const,int [],int [],float [])\n"" csr_eliminate_zeros<(int,double)>(int const,int const,int [],int [],double [])\n"" csr_eliminate_zeros<(int,long double)>(int const,int const,int [],int [],long double [])\n"" csr_eliminate_zeros<(int,npy_cfloat_wrapper)>(int const,int const,int [],int [],npy_cfloat_wrapper [])\n"" csr_eliminate_zeros<(int,npy_cdouble_wrapper)>(int const,int const,int [],int [],npy_cdouble_wrapper [])\n"" csr_eliminate_zeros<(int,npy_clongdouble_wrapper)>(int const,int const,int [],int [],npy_clongdouble_wrapper [])\n"); + return NULL; +} + + SWIGINTERN PyObject *_wrap_csr_sum_duplicates__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int arg1 ; @@ -82221,6 +83428,22 @@ "csr_sort_indices(int n_row, int Ap, int Aj, npy_cdouble_wrapper Ax)\n" "csr_sort_indices(int n_row, int Ap, int Aj, npy_clongdouble_wrapper Ax)\n" ""}, + { (char *)"csr_eliminate_zeros", _wrap_csr_eliminate_zeros, METH_VARARGS, (char *)"\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, signed char Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned char Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, short Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned short Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, int Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned int Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, long long Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned long long Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, float Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, double Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, long double Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_cfloat_wrapper Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_cdouble_wrapper Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax)\n" + ""}, { (char *)"csr_sum_duplicates", _wrap_csr_sum_duplicates, METH_VARARGS, (char *)"\n" "csr_sum_duplicates(int n_row, int n_col, int Ap, int Aj, signed char Ax)\n" "csr_sum_duplicates(int n_row, int n_col, int Ap, int Aj, unsigned char Ax)\n" Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-01-04 01:29:56 UTC (rev 3778) +++ trunk/scipy/sparse/tests/test_base.py 2008-01-04 07:00:52 UTC (rev 3779) @@ -15,7 +15,7 @@ import numpy from numpy import arange, zeros, array, dot, ones, matrix, asmatrix, \ - asarray, vstack, ndarray, kron + asarray, vstack, ndarray, kron, transpose import random from numpy.testing import * @@ -812,6 +812,17 @@ assert_array_equal(asp.indices,[1, 2, 7, 4, 5]) assert_array_equal(asp.todense(),bsp.todense()) + def check_eliminate_zeros(self): + data = array( [1, 0, 0, 0, 2, 0, 3, 0] ) + indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) + indptr = array( [0, 3, 8] ) + asp = csr_matrix( (data, indices, indptr), shape=(2,10) ) + bsp = asp.copy() + asp.eliminate_zeros( ) + assert_array_equal(asp.nnz, 3) + assert_array_equal(asp.data,[1, 2, 3]) + assert_array_equal(asp.todense(),bsp.todense()) + def check_get_submatrix(self): a = csr_matrix( array([[1,2,3,4],[1,2,3,5],[0,2,0,1]]) ) i0 = slice( 0, 2 ) @@ -875,6 +886,17 @@ csc = csc_matrix((data, indices, indptr)) assert_array_equal(csc.shape,(6,3)) + def check_eliminate_zeros(self): + data = array( [1, 0, 0, 0, 2, 0, 3, 0] ) + indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) + indptr = array( [0, 3, 8] ) + asp = csc_matrix( (data, indices, indptr), shape=(10,2) ) + bsp = asp.copy() + asp.eliminate_zeros( ) + assert_array_equal(asp.nnz, 3) + assert_array_equal(asp.data,[1, 2, 3]) + assert_array_equal(asp.todense(),bsp.todense()) + def check_sort_indices(self): data = arange( 5 ) row = array( [7, 2, 1, 5, 4] ) @@ -1260,6 +1282,16 @@ A = kron( [[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]] ) assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A) + def check_eliminate_zeros(self): + data = kron([1, 0, 0, 0, 2, 0, 3, 0], [[1,1],[1,1]]).T + data = data.reshape(-1,2,2) + indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) + indptr = array( [0, 3, 8] ) + asp = bsr_matrix( (data, indices, indptr), shape=(4,20) ) + bsp = asp.copy() + asp.eliminate_zeros() + assert_array_equal(asp.nnz, 3*4) + assert_array_equal(asp.todense(),bsp.todense()) if __name__ == "__main__": From scipy-svn at scipy.org Fri Jan 4 04:53:33 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 4 Jan 2008 03:53:33 -0600 (CST) Subject: [Scipy-svn] r3780 - in trunk/scipy/sparse: . sparsetools tests Message-ID: <20080104095333.564A239C2B7@new.scipy.org> Author: wnbell Date: 2008-01-04 03:53:29 -0600 (Fri, 04 Jan 2008) New Revision: 3780 Modified: trunk/scipy/sparse/bsr.py trunk/scipy/sparse/sparsetools/fixed_size.h trunk/scipy/sparse/sparsetools/sparsetools.h trunk/scipy/sparse/tests/test_sparse.py Log: use recursive template for BSR matrix vector product Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-04 07:00:52 UTC (rev 3779) +++ trunk/scipy/sparse/bsr.py 2008-01-04 09:53:29 UTC (rev 3780) @@ -11,7 +11,7 @@ from sparsetools import bsr_matvec, csr_matmat_pass1, bsr_matmat_pass2 from data import _data_matrix from compressed import _cs_matrix -from base import isspmatrix +from base import isspmatrix, _formats from sputils import isshape, getdtype, to_native, isscalarlike, isdense, \ upcast @@ -53,8 +53,8 @@ - The Block Compressed Row (BSR) format is very similar to the Compressed Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense sub matrices like the last example - below. Such matrices often arise, for instance, in finite - element discretizations. + below. Such matrices often arise, for instance, in vector-valued + finite element discretizations. Examples @@ -113,11 +113,11 @@ self.data = zeros( (0,) + blocksize, getdtype(dtype, default=float) ) self.indices = zeros( 0, dtype=intc ) - X,Y = blocksize - if (M % X) != 0 or (N % Y) != 0: + R,C = blocksize + if (M % R) != 0 or (N % C) != 0: raise ValueError, 'shape must be multiple of blocksize' - self.indptr = zeros(M/X + 1, dtype=intc ) + self.indptr = zeros(M/R + 1, dtype=intc ) elif len(arg1) == 2: # (data,(row,col)) format @@ -279,7 +279,7 @@ """ if isdense(other): M,N = self.shape - X,Y = self.blocksize + R,C = self.blocksize if other.shape != (N,) and other.shape != (N,1): raise ValueError, "dimension mismatch" @@ -299,7 +299,7 @@ y = output - bsr_matvec(M/X, N/Y, X, Y, \ + bsr_matvec(M/R, N/C, R, C, \ self.indptr, self.indices, ravel(self.data), ravel(other), y) if isinstance(other, matrix): @@ -389,15 +389,15 @@ """ M,N = self.shape - X,Y = self.blocksize + R,C = self.blocksize - row = (X * arange(M/X)).repeat(diff(self.indptr)) - row = row.repeat(X*Y).reshape(-1,X,Y) - row += tile( arange(X).reshape(-1,1), (1,Y) ) + row = (R * arange(M/R)).repeat(diff(self.indptr)) + row = row.repeat(R*C).reshape(-1,R,C) + row += tile( arange(R).reshape(-1,1), (1,C) ) row = row.reshape(-1) - col = (Y * self.indices).repeat(X*Y).reshape(-1,X,Y) - col += tile( arange(Y), (X,1) ) + col = (C * self.indices).repeat(R*C).reshape(-1,R,C) + col += tile( arange(C), (R,1) ) col = col.reshape(-1) data = self.data.reshape(-1) @@ -411,16 +411,16 @@ def transpose(self): - X,Y = self.blocksize + R,C = self.blocksize M,N = self.shape if self.nnz == 0: - return bsr_matrix((N,M),blocksize=(Y,X)) + return bsr_matrix((N,M),blocksize=(C,R)) #use CSR.T to determine a permutation for BSR.T from csr import csr_matrix data = arange(len(self.indices), dtype=self.indices.dtype) - proxy = csr_matrix((data,self.indices,self.indptr),shape=(M/X,N/Y)) + proxy = csr_matrix((data,self.indices,self.indptr),shape=(M/R,N/C)) proxy = proxy.tocsc() data = self.data.swapaxes(1,2)[proxy.data] #permute data Modified: trunk/scipy/sparse/sparsetools/fixed_size.h =================================================================== --- trunk/scipy/sparse/sparsetools/fixed_size.h 2008-01-04 07:00:52 UTC (rev 3779) +++ trunk/scipy/sparse/sparsetools/fixed_size.h 2008-01-04 09:53:29 UTC (rev 3780) @@ -19,7 +19,7 @@ inline T operator()(const T * V1, const T * V2) { _dot d; - return (*V1) * (*V2) + d(++V1, ++V2); + return (*V1) * (*V2) + d(V1 + 1, V2 + 1); } }; template @@ -41,8 +41,40 @@ +/* + * Matrix Vector Product + * + */ +template +class _matvec +{ + public: + inline void operator()(const T * A, const T * X, T * Y) + { + *Y += dot(A,X); + _matvec d; + d(A + N, X, Y + 1); + } +}; +template +class _matvec<1,N,T> +{ + public: + inline void operator()(const T * A, const T * X, T * Y) + { + *Y += dot(A,X); + } +}; +template +inline void matvec(const T * A, const T * X, T * Y) +{ + _matvec d; + d(A,X,Y); +} + + template class _vec_binop_vec { Modified: trunk/scipy/sparse/sparsetools/sparsetools.h =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.h 2008-01-04 07:00:52 UTC (rev 3779) +++ trunk/scipy/sparse/sparsetools/sparsetools.h 2008-01-04 09:53:29 UTC (rev 3780) @@ -330,7 +330,7 @@ const I Bj[], I Cp[]) { -// // method that uses O(n) temp storage +// // method that uses O(1) temp storage // const I hash_size = 1 << 5; // I vals[hash_size]; // I mask[hash_size]; @@ -477,7 +477,6 @@ for(I i = 0; i < SIZE; i++){ Cx[i] = 0; } - //std::cout << "n_brow " << n_brow << " Cp[-1] " << Cp[n_brow] << " R " << R << " C " << C << " N " << N << std::endl; std::vector next(n_bcol,-1); std::vector mats(n_bcol); @@ -567,18 +566,9 @@ I Cp[], I Cj[], T Cx[], const bin_op& op) { - //Method that works for unsorted indices - // assert( csr_has_sorted_indices(n_brow,Ap,Aj) ); - // assert( csr_has_sorted_indices(n_brow,Bp,Bj) ); - - //if (R == 3 && C == 3){ - // bsr_binop_bsr_fixed(n_brow,n_bcol,Ap,Aj,Ax,Bp,Bj,Bx,Cp,Cj,Cx,op); - // return; - //} - const I RC = R*C; - T result[8*8]; - //T zeros[8*8]; + T * result = Cx; + Cp[0] = 0; I nnz = 0; @@ -600,9 +590,7 @@ if( is_nonzero_block(result,RC) ){ Cj[nnz] = A_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -616,9 +604,7 @@ if(is_nonzero_block(result,RC)){ Cj[nnz] = A_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -631,9 +617,7 @@ } if(is_nonzero_block(result,RC)){ Cj[nnz] = B_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -644,15 +628,14 @@ //tail while(A_pos < A_end){ + for(I n = 0; n < RC; n++){ result[n] = op(Ax[RC*A_pos + n],0); } if(is_nonzero_block(result,RC)){ Cj[nnz] = A_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -663,11 +646,10 @@ for(I n = 0; n < RC; n++){ result[n] = op(0,Bx[RC*B_pos + n]); } + if(is_nonzero_block(result,RC)){ Cj[nnz] = B_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -1159,38 +1141,15 @@ const T Xx[], T Yx[]) { - //TODO make a matvec template - for(I i = 0; i < n_brow; i++) { - T r0 = 0; - T r1 = 0; - T r2 = 0; - T r3 = 0; - T r4 = 0; - T r5 = 0; - T r6 = 0; - T r7 = 0; + for(I i = 0; i < R*n_brow; i++){ + Yx[i] = 0; + } + for(I i = 0; i < n_brow; i++) { for(I jj = Ap[i]; jj < Ap[i+1]; jj++) { I j = Aj[jj]; - const T * base = Ax + jj*(R*C); - if (R > 0) r0 += dot(base + 0*C, Xx + j*C); - if (R > 1) r1 += dot(base + 1*C, Xx + j*C); - if (R > 2) r2 += dot(base + 2*C, Xx + j*C); - if (R > 3) r3 += dot(base + 3*C, Xx + j*C); - if (R > 4) r4 += dot(base + 4*C, Xx + j*C); - if (R > 5) r5 += dot(base + 5*C, Xx + j*C); - if (R > 6) r6 += dot(base + 6*C, Xx + j*C); - if (R > 7) r7 += dot(base + 7*C, Xx + j*C); + matvec(Ax + jj*R*C, Xx + j*C, Yx + i*R); } - - if (R > 0) Yx[R*i+0] = r0; - if (R > 1) Yx[R*i+1] = r1; - if (R > 2) Yx[R*i+2] = r2; - if (R > 3) Yx[R*i+3] = r3; - if (R > 4) Yx[R*i+4] = r4; - if (R > 5) Yx[R*i+5] = r5; - if (R > 6) Yx[R*i+6] = r6; - if (R > 7) Yx[R*i+7] = r7; } } @@ -1241,7 +1200,7 @@ //otherwise use general method - for(I i = 0; i < n_brow; i++){ + for(I i = 0; i < R*n_brow; i++){ Yx[i] = 0; } Modified: trunk/scipy/sparse/tests/test_sparse.py =================================================================== --- trunk/scipy/sparse/tests/test_sparse.py 2008-01-04 07:00:52 UTC (rev 3779) +++ trunk/scipy/sparse/tests/test_sparse.py 2008-01-04 09:53:29 UTC (rev 3780) @@ -46,7 +46,7 @@ class TestSparseTools(NumpyTestCase): """Simple benchmarks for sparse matrix module""" - def test_arithmetic(self,level=4): + def test_arithmetic(self,level=5): matrices = [] #matrices.append( ('A','Identity', spidentity(500**2,format='csr')) ) matrices.append( ('A','Poisson5pt', poisson2d(500,format='csr')) ) @@ -128,7 +128,7 @@ print fmt % (A.format,name,shape,A.nnz,1e3*(end-start)/float(iter) ) - def bench_matvec(self,level=5): + def bench_matvec(self,level=4): matrices = [] matrices.append(('Identity', spidentity(10**4,format='dia'))) matrices.append(('Identity', spidentity(10**4,format='csr'))) From scipy-svn at scipy.org Fri Jan 4 07:29:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 4 Jan 2008 06:29:16 -0600 (CST) Subject: [Scipy-svn] r3781 - trunk/scipy/io/matlab Message-ID: <20080104122916.3D11439C087@new.scipy.org> Author: stefan Date: 2008-01-04 06:29:00 -0600 (Fri, 04 Jan 2008) New Revision: 3781 Modified: trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/miobase.py Log: Clean up padding. Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-01-04 09:53:29 UTC (rev 3780) +++ trunk/scipy/io/matlab/mio5.py 2008-01-04 12:29:00 UTC (rev 3781) @@ -190,23 +190,25 @@ def read_element(self, copy=True): raw_tag = self.mat_stream.read(8) tag = N.ndarray(shape=(), - dtype=self.dtypes['tag_full'], - buffer = raw_tag) + dtype=self.dtypes['tag_full'], + buffer=raw_tag) mdtype = tag['mdtype'].item() + byte_count = mdtype >> 16 if byte_count: # small data element format if byte_count > 4: raise ValueError, 'Too many bytes for sde format' mdtype = mdtype & 0xFFFF dt = self.dtypes[mdtype] - el_count = byte_count / dt.itemsize + el_count = byte_count // dt.itemsize return N.ndarray(shape=(el_count,), - dtype=dt, - buffer=raw_tag[4:]) + dtype=dt, + buffer=raw_tag[4:]) + byte_count = tag['byte_count'].item() if mdtype == miMATRIX: return self.current_getter(byte_count).get_array() - if mdtype in self.codecs: # encoded char data + elif mdtype in self.codecs: # encoded char data raw_str = self.mat_stream.read(byte_count) codec = self.codecs[mdtype] if not codec: @@ -214,15 +216,18 @@ el = raw_str.decode(codec) else: # numeric data dt = self.dtypes[mdtype] - el_count = byte_count / dt.itemsize + el_count = byte_count // dt.itemsize el = N.ndarray(shape=(el_count,), dtype=dt, buffer=self.mat_stream.read(byte_count)) if copy: el = el.copy() + + # Seek to next 64-bit boundary mod8 = byte_count % 8 if mod8: self.mat_stream.seek(8 - mod8, 1) + return el def matrix_getter_factory(self): @@ -572,14 +577,16 @@ tag['mdtype'] = np_to_mtypes[arr.dtype.str[1:]] else: tag['mdtype'] = mdtype - tag['byte_count'] = arr.size*arr.itemsize + + tag['byte_count'] = arr.size*arr.itemsize + padding = (8 - tag['byte_count']) % 8 + self.write_dtype(tag) self.write_bytes(arr) - # do 8 byte padding if needed - if tag['byte_count']%8 != 0: - pad = (1+tag['byte_count']//8)*8 - tag['byte_count'] - self.write_bytes(N.zeros((pad,),dtype='u1')) + # pad to next 64-bit boundary + self.write_bytes(N.zeros((padding,),'u1')) + def write_header(self, mclass, is_global=False, is_complex=False, @@ -673,7 +680,6 @@ A.sort_indices() # MATLAB expects sorted row indices is_complex = (A.dtype.kind == 'c') nz = A.nnz - self.write_header(mclass=mxSPARSE_CLASS, is_complex=is_complex, nzmax=nz) Modified: trunk/scipy/io/matlab/miobase.py =================================================================== --- trunk/scipy/io/matlab/miobase.py 2008-01-04 09:53:29 UTC (rev 3780) +++ trunk/scipy/io/matlab/miobase.py 2008-01-04 12:29:00 UTC (rev 3781) @@ -90,11 +90,9 @@ or in ('little', '<') or in ('BIG', '>') mat_dtype - return arrays in same dtype as loaded into matlab - (instead of the dtype with which they are saved) + (instead of the dtype with which they were saved) squeeze_me - whether to squeeze unit dimensions or not chars_as_strings - whether to convert char arrays to string arrays - mat_dtype - return matrices with datatype that matlab would load as - (rather than in the datatype matlab saves as) matlab_compatible - returns matrices as would be loaded by matlab (implies squeeze_me=False, chars_as_strings=False mat_dtype=True) From scipy-svn at scipy.org Fri Jan 4 16:28:50 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 4 Jan 2008 15:28:50 -0600 (CST) Subject: [Scipy-svn] r3782 - in branches/testing_cleanup/scipy: io io/matlab io/matlab/tests io/matlab/tests/data io/tests misc/tests optimize/tests sparse/tests Message-ID: <20080104212850.52EDB39C0D7@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-04 15:27:41 -0600 (Fri, 04 Jan 2008) New Revision: 3782 Added: branches/testing_cleanup/scipy/io/matlab/tests/ branches/testing_cleanup/scipy/io/matlab/tests/data/ branches/testing_cleanup/scipy/io/matlab/tests/data/japanese_utf8.txt branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/test_mio.py branches/testing_cleanup/scipy/misc/tests/test_basic.py Removed: branches/testing_cleanup/scipy/io/matlab/tests/data/ branches/testing_cleanup/scipy/io/matlab/tests/data/japanese_utf8.txt branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat branches/testing_cleanup/scipy/io/matlab/tests/test_mio.py branches/testing_cleanup/scipy/io/tests/data/ branches/testing_cleanup/scipy/io/tests/test_mio.py Modified: branches/testing_cleanup/scipy/io/__init__.py branches/testing_cleanup/scipy/io/matlab/mio5.py branches/testing_cleanup/scipy/io/matlab/setup.py branches/testing_cleanup/scipy/optimize/tests/test_slsqp.py branches/testing_cleanup/scipy/sparse/tests/test_base.py Log: matlab io refixed Modified: branches/testing_cleanup/scipy/io/__init__.py =================================================================== --- branches/testing_cleanup/scipy/io/__init__.py 2008-01-04 12:29:00 UTC (rev 3781) +++ branches/testing_cleanup/scipy/io/__init__.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -83,8 +83,6 @@ from data_store import save_as_module from mmio import mminfo, mmread, mmwrite - - __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.moduletest import test_func +test = test_func Modified: branches/testing_cleanup/scipy/io/matlab/mio5.py =================================================================== --- branches/testing_cleanup/scipy/io/matlab/mio5.py 2008-01-04 12:29:00 UTC (rev 3781) +++ branches/testing_cleanup/scipy/io/matlab/mio5.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -603,10 +603,14 @@ af['nzmax'] = nzmax self.write_dtype(af) # write array shape - self.arr=N.atleast_2d(self.arr) + if self.arr.ndim < 2: + new_arr = N.atleast_2d(self.arr) + if type(new_arr) != type(self.arr): + raise ValueError("Array should be 2-dimensional.") + self.arr = new_arr self.write_element(N.array(self.arr.shape, dtype='i4')) # write name - self.write_element(N.ndarray(shape=len(self.name), dtype='S1', buffer=self.name)) + self.write_element(N.array([ord(c) for c in self.name], 'i1')) def update_matrix_tag(self): curr_pos = self.file_stream.tell() @@ -663,26 +667,24 @@ def write(self): ''' Sparse matrices are 2D - See docstring for Mat5SparseGetter + ''' - imagf = self.arr.dtype.kind == 'c' - N = self.arr.nnz - ijd = N.zeros((N+1, 3+imagf), dtype='f8') - for i in range(N): - ijd[i,0], ijd[i,1] = self.arr.rowcol(i) - ijd[:-1,0:2] += 1 # 1 based indexing - if imagf: - ijd[:-1,2] = self.arr.data.real - ijd[:-1,3] = self.arr.data.imag - else: - ijd[:-1,2] = self.arr.data - ijd[-1,0:2] = self.arr.shape - self.write_header(P=miDOUBLE, - T=mxSPARSE_CLASS, - dims=ijd.shape) - self.write_bytes(ijd) + A = self.arr.tocsc() # convert to sparse CSC format + A.sort_indices() # MATLAB expects sorted row indices + is_complex = (A.dtype.kind == 'c') + nz = A.nnz + self.write_header(mclass=mxSPARSE_CLASS, + is_complex=is_complex, + nzmax=nz) + self.write_element(A.indices.astype('i4')) + self.write_element(A.indptr.astype('i4')) + self.write_element(A.data.real) + if is_complex: + self.write_element(A.data.imag) + self.update_matrix_tag() + class Mat5WriterGetter(object): ''' Wraps stream and options, provides methods for getting Writer objects ''' def __init__(self, stream, unicode_strings): Modified: branches/testing_cleanup/scipy/io/matlab/setup.py =================================================================== --- branches/testing_cleanup/scipy/io/matlab/setup.py 2008-01-04 12:29:00 UTC (rev 3781) +++ branches/testing_cleanup/scipy/io/matlab/setup.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -3,6 +3,7 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('matlab', parent_package, top_path) + config.add_data_dir('tests') return config if __name__ == '__main__': Copied: branches/testing_cleanup/scipy/io/matlab/tests (from rev 3778, trunk/scipy/io/matlab/tests) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data (from rev 3778, trunk/scipy/io/matlab/tests/data) Property changes on: branches/testing_cleanup/scipy/io/matlab/tests/data ___________________________________________________________________ Name: svn:ignore + *.pyc *.swp *.pyd *.so Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/japanese_utf8.txt =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/japanese_utf8.txt (from rev 3778, trunk/scipy/io/matlab/tests/data/japanese_utf8.txt) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat =================================================================== (Binary files differ) Copied: branches/testing_cleanup/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat (from rev 3778, trunk/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat) Deleted: branches/testing_cleanup/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-01-04 01:29:56 UTC (rev 3778) +++ branches/testing_cleanup/scipy/io/matlab/tests/test_mio.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -1,248 +0,0 @@ -#!/usr/bin/env python - -import os -from glob import glob -from cStringIO import StringIO -from tempfile import mkstemp -from numpy.testing import set_package_path, restore_path, NumpyTestCase, NumpyTest -from numpy.testing import assert_equal, assert_array_almost_equal -from numpy import arange, array, eye, pi, cos, exp, sin, sqrt, ndarray, \ - zeros, reshape, transpose, empty -import scipy.sparse as SP - -set_package_path() -from matlab.mio import loadmat, savemat -from matlab.mio5 import mat_obj, mat_struct -restore_path() - -try: # Python 2.3 support - from sets import Set as set -except: - pass - -test_data_path = os.path.join(os.path.dirname(__file__), './data') - -class TestMIOArray(NumpyTestCase): - def __init__(self, *args, **kwargs): - super(TestMIOArray, self).__init__(*args, **kwargs) - - def _check_level(self, label, expected, actual): - """ Check one level of a potentially nested object / list """ - # object array is returned from cell array in mat file - typex = type(expected) - typac = type(actual) - if isinstance(expected, ndarray) and expected.dtype.hasobject: - assert typex is typac, "Different types at %s" % label - assert len(expected) == len(actual), "Different list lengths at %s" % label - for i, ev in enumerate(expected): - level_label = "%s, [%d], " % (label, i) - self._check_level(level_label, ev, actual[i]) - return - # object, as container for matlab structs and objects - elif isinstance(expected, mat_struct) or isinstance(expected, mat_obj): - assert isinstance(actual, typex), \ - "Different types %s and %s at %s" % (typex, typac, label) - ex_fields = dir(expected) - ac_fields = dir(actual) - for k in ex_fields: - if k.startswith('__') and k.endswith('__'): - continue - assert k in ac_fields, "Missing property at %s" % label - ev = expected.__dict__[k] - v = actual.__dict__[k] - level_label = "%s, property %s, " % (label, k) - self._check_level(level_label, ev, v) - return - # hoping this is a single value, which might be an array - if SP.issparse(expected): - assert SP.issparse(actual), "Expected sparse at %s" % label - assert_array_almost_equal(actual.todense(), - expected.todense(), - err_msg = label, - decimal = 5) - elif isinstance(expected, ndarray): - if expected.shape: # allow scalar and 0d array comparisons - assert isinstance(actual, ndarray), "Expected ndarray at %s" % label - assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) - else: - assert isinstance(expected, typac), \ - "Types %s and %s do not match at %s" % (typex, typac, label) - assert_equal(actual, expected, err_msg=label) - - def _check_case(self, name, files, case): - for file_name in files: - matdict = loadmat(file_name) - label = "test %s; file %s" % (name, file_name) - for k, expected in case.items(): - k_label = "%s, variable %s" % (label, k) - assert k in matdict, "Missing key at %s" % k_label - self._check_level(k_label, expected, matdict[k]) - - # Add the load tests dynamically, with given parameters - def _make_check_case(name, files, expected): - def cc(self): - self._check_case(name, files, expected) - cc.__doc__ = "check loadmat case %s" % name - return cc - - # Add the round trip tests dynamically, with given parameters - def _make_rt_check_case(name, expected, format): - def cc(self): - mat_stream = StringIO() - savemat(mat_stream, expected, format=format) - mat_stream.seek(0) - self._check_case(name, [mat_stream], expected) - cc.__doc__ = "check loadmat case %s" % name - return cc - - # Define cases to test - theta = pi/4*arange(9,dtype=float) - case_table4 = [ - {'name': 'double', - 'expected': {'testdouble': theta} - }] - case_table4.append( - {'name': 'string', - 'expected': {'teststring': u'"Do nine men interpret?" "Nine men," I nod.'}, - }) - case_table4.append( - {'name': 'complex', - 'expected': {'testcomplex': cos(theta) + 1j*sin(theta)} - }) - A = zeros((3,5)) - A[0] = range(1,6) - A[:,0] = range(1,4) - case_table4.append( - {'name': 'matrix', - 'expected': {'testmatrix': A}, - }) - case_table4.append( - {'name': 'sparse', - 'expected': {'testsparse': SP.csc_matrix(A)}, - }) - B = A.astype(complex) - B[0,0] += 1j - case_table4.append( - {'name': 'sparsecomplex', - 'expected': {'testsparsecomplex': SP.csc_matrix(B)}, - }) - case_table4.append( - {'name': 'multi', - 'expected': {'theta': theta, - 'a': A}, - }) - case_table4.append( - {'name': 'minus', - 'expected': {'testminus': array(-1)}, - }) - case_table4.append( - {'name': 'onechar', - 'expected': {'testonechar': u'r'}, - }) - case_table5 = [ - {'name': 'cell', - 'expected': {'testcell': - array([u'This cell contains this string and 3 arrays of '+\ - 'increasing length', - array(1), array([1,2]), array([1,2,3])], - dtype=object)} - }] - case_table5.append( - {'name': 'emptycell', - 'expected': {'testemptycell': - array([array(1), array(2), array([]), - array([]), array(3)], dtype=object)} - }) - case_table5.append( - {'name': 'stringarray', - 'expected': {'teststringarray': array( - [u'one ', u'two ', u'three'], dtype=object)}, - }) - case_table5.append( - {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }) - case_table5_rt = [ - {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }, - {'name': 'sparsefloat', - 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, - }, - {'name': 'sparsecomplex', - 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, - }, - ] - st = mat_struct() - st.stringfield = u'Rats live on no evil star.' - st.doublefield = array([sqrt(2),exp(1),pi]) - st.complexfield = (1+1j)*array([sqrt(2),exp(1),pi]) - case_table5.append( - {'name': 'struct', - 'expected': {'teststruct': st} - }) - a = array([array(1), - array([array(2), array(3), - array([array(4), array(5)], - dtype=object)], - dtype=object)], - dtype=object) - case_table5.append( - {'name': 'cellnest', - 'expected': {'testcellnest': a}, - }) - st = mat_struct() - st.one = array(1) - st.two = mat_struct() - st.two.three = u'number 3' - case_table5.append( - {'name': 'structnest', - 'expected': {'teststructnest': st} - }) - a = array([mat_struct(), mat_struct()]) - a[0].one = array(1) - a[0].two = array(2) - a[1].one = u'number 1' - a[1].two = u'number 2' - case_table5.append( - {'name': 'structarr', - 'expected': {'teststructarr': a} - }) - a = mat_obj() - a._classname = 'inline' - a.expr = u'x' - a.inputExpr = u' x = INLINE_INPUTS_{1};' - a.args = u'x' - a.isEmpty = array(0) - a.numArgs = array(1) - a.version = array(1) - case_table5.append( - {'name': 'object', - 'expected': {'testobject': a} - }) - u_str = file( - os.path.join(test_data_path, 'japanese_utf8.txt'), - 'rb').read().decode('utf-8') - case_table5.append( - {'name': 'unicode', - 'expected': {'testunicode': u_str} - }) - # add load tests - for case in case_table4 + case_table5: - name = case['name'] - expected = case['expected'] - filt = os.path.join(test_data_path, 'test%s_*.mat' % name) - files = glob(filt) - assert files, "No files for test %s using filter %s" % (name, filt) - exec 'check_%s = _make_check_case(name, files, expected)' % name - # round trip tests - for case in case_table4 + case_table5_rt: - name = case['name'] + '_round_trip' - expected = case['expected'] - format = case in case_table4 and '4' or '5' - exec 'check_%s = _make_rt_check_case(name, expected, format)' \ - % name - - -if __name__ == "__main__": - NumpyTest().run() Copied: branches/testing_cleanup/scipy/io/matlab/tests/test_mio.py (from rev 3778, trunk/scipy/io/matlab/tests/test_mio.py) =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-01-04 01:29:56 UTC (rev 3778) +++ branches/testing_cleanup/scipy/io/matlab/tests/test_mio.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -0,0 +1,242 @@ +#!/usr/bin/env python +''' Nose test generators ''' +import os +from glob import glob +from cStringIO import StringIO +from tempfile import mkstemp +from scipy.testing import * +from numpy import arange, array, eye, pi, cos, exp, sin, sqrt, ndarray, \ + zeros, reshape, transpose, empty +import scipy.sparse as SP + +from scipy.io.matlab.mio import loadmat, savemat +from scipy.io.matlab.mio5 import mat_obj, mat_struct + +try: # Python 2.3 support + from sets import Set as set +except: + pass + +test_data_path = os.path.join(os.path.dirname(__file__), 'data') + +def _check_level(self, label, expected, actual): + """ Check one level of a potentially nested object / list """ + # object array is returned from cell array in mat file + typex = type(expected) + typac = type(actual) + if isinstance(expected, ndarray) and expected.dtype.hasobject: + assert typex is typac, "Different types at %s" % label + assert len(expected) == len(actual), "Different list lengths at %s" % label + for i, ev in enumerate(expected): + level_label = "%s, [%d], " % (label, i) + self._check_level(level_label, ev, actual[i]) + return + # object, as container for matlab structs and objects + elif isinstance(expected, mat_struct) or isinstance(expected, mat_obj): + assert isinstance(actual, typex), \ + "Different types %s and %s at %s" % (typex, typac, label) + ex_fields = dir(expected) + ac_fields = dir(actual) + for k in ex_fields: + if k.startswith('__') and k.endswith('__'): + continue + assert k in ac_fields, "Missing property at %s" % label + ev = expected.__dict__[k] + v = actual.__dict__[k] + level_label = "%s, property %s, " % (label, k) + self._check_level(level_label, ev, v) + return + # hoping this is a single value, which might be an array + if SP.issparse(expected): + assert SP.issparse(actual), "Expected sparse at %s" % label + assert_array_almost_equal(actual.todense(), + expected.todense(), + err_msg = label, + decimal = 5) + elif isinstance(expected, ndarray): + if expected.shape: # allow scalar and 0d array comparisons + assert isinstance(actual, ndarray), "Expected ndarray at %s" % label + assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) + else: + assert isinstance(expected, typac), \ + "Types %s and %s do not match at %s" % (typex, typac, label) + assert_equal(actual, expected, err_msg=label) + +def _check_case(self, name, files, case): + for file_name in files: + matdict = loadmat(file_name) + label = "test %s; file %s" % (name, file_name) + for k, expected in case.items(): + k_label = "%s, variable %s" % (label, k) + assert k in matdict, "Missing key at %s" % k_label + self._check_level(k_label, expected, matdict[k]) + +# Add the load tests dynamically, with given parameters +def _make_check_case(name, files, expected): + def cc(self): + self._check_case(name, files, expected) + cc.__doc__ = "check loadmat case %s" % name + return cc + +# Add the round trip tests dynamically, with given parameters +def _make_rt_check_case(name, expected, format): + def cc(self): + mat_stream = StringIO() + savemat(mat_stream, expected, format=format) + mat_stream.seek(0) + self._check_case(name, [mat_stream], expected) + cc.__doc__ = "check loadmat case %s" % name + return cc + +# Define cases to test +theta = pi/4*arange(9,dtype=float) +case_table4 = [ + {'name': 'double', + 'expected': {'testdouble': theta} + }] +case_table4.append( + {'name': 'string', + 'expected': {'teststring': u'"Do nine men interpret?" "Nine men," I nod.'}, + }) +case_table4.append( + {'name': 'complex', + 'expected': {'testcomplex': cos(theta) + 1j*sin(theta)} + }) +A = zeros((3,5)) +A[0] = range(1,6) +A[:,0] = range(1,4) +case_table4.append( + {'name': 'matrix', + 'expected': {'testmatrix': A}, + }) +case_table4.append( + {'name': 'sparse', + 'expected': {'testsparse': SP.csc_matrix(A)}, + }) +B = A.astype(complex) +B[0,0] += 1j +case_table4.append( + {'name': 'sparsecomplex', + 'expected': {'testsparsecomplex': SP.csc_matrix(B)}, + }) +case_table4.append( + {'name': 'multi', + 'expected': {'theta': theta, + 'a': A}, + }) +case_table4.append( + {'name': 'minus', + 'expected': {'testminus': array(-1)}, + }) +case_table4.append( + {'name': 'onechar', + 'expected': {'testonechar': u'r'}, + }) +case_table5 = [ + {'name': 'cell', + 'expected': {'testcell': + array([u'This cell contains this string and 3 arrays of '+\ + 'increasing length', + array(1), array([1,2]), array([1,2,3])], + dtype=object)} + }] +case_table5.append( + {'name': 'emptycell', + 'expected': {'testemptycell': + array([array(1), array(2), array([]), + array([]), array(3)], dtype=object)} + }) +case_table5.append( + {'name': 'stringarray', + 'expected': {'teststringarray': array( + [u'one ', u'two ', u'three'], dtype=object)}, + }) +case_table5.append( + {'name': '3dmatrix', + 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} + }) +case_table5_rt = [ + {'name': '3dmatrix', + 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} + }, + {'name': 'sparsefloat', + 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, + }, + {'name': 'sparsecomplex', + 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, + }, + ] +st = mat_struct() +st.stringfield = u'Rats live on no evil star.' +st.doublefield = array([sqrt(2),exp(1),pi]) +st.complexfield = (1+1j)*array([sqrt(2),exp(1),pi]) +case_table5.append( + {'name': 'struct', + 'expected': {'teststruct': st} + }) +a = array([array(1), + array([array(2), array(3), + array([array(4), array(5)], + dtype=object)], + dtype=object)], + dtype=object) +case_table5.append( + {'name': 'cellnest', + 'expected': {'testcellnest': a}, + }) +st = mat_struct() +st.one = array(1) +st.two = mat_struct() +st.two.three = u'number 3' +case_table5.append( + {'name': 'structnest', + 'expected': {'teststructnest': st} + }) +a = array([mat_struct(), mat_struct()]) +a[0].one = array(1) +a[0].two = array(2) +a[1].one = u'number 1' +a[1].two = u'number 2' +case_table5.append( + {'name': 'structarr', + 'expected': {'teststructarr': a} + }) +a = mat_obj() +a._classname = 'inline' +a.expr = u'x' +a.inputExpr = u' x = INLINE_INPUTS_{1};' +a.args = u'x' +a.isEmpty = array(0) +a.numArgs = array(1) +a.version = array(1) +case_table5.append( + {'name': 'object', + 'expected': {'testobject': a} + }) +u_str = file( + os.path.join(test_data_path, 'japanese_utf8.txt'), + 'rb').read().decode('utf-8') +case_table5.append( + {'name': 'unicode', + 'expected': {'testunicode': u_str} + }) + +# generator for load tests +def test_load(): + for case in case_table4 + case_table5: + name = case['name'] + expected = case['expected'] + filt = os.path.join(test_data_path, 'test%s_*.mat' % name) + files = glob(filt) + assert files, "No files for test %s using filter %s" % (name, filt) + yield _make_check_case, name, files, expected + +# round trip tests +def test_round_trip(): + for case in case_table4 + case_table5_rt: + name = case['name'] + '_round_trip' + expected = case['expected'] + format = case in case_table4 and '4' or '5' + yield _make_rt_check_case, name, expected, format + + Deleted: branches/testing_cleanup/scipy/io/tests/test_mio.py =================================================================== --- branches/testing_cleanup/scipy/io/tests/test_mio.py 2008-01-04 12:29:00 UTC (rev 3781) +++ branches/testing_cleanup/scipy/io/tests/test_mio.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -1,234 +0,0 @@ -#!/usr/bin/env python - -import os -from glob import glob -from cStringIO import StringIO -from tempfile import mkstemp -from numpy import arange, array, eye, pi, cos, exp, sin, sqrt, ndarray, \ - zeros, reshape, transpose, empty -import scipy.sparse as SP - -from scipy.testing import * - -from matlab.mio import loadmat, savemat -from matlab.mio5 import mat_obj, mat_struct - -try: # Python 2.3 support - from sets import Set as set -except: - pass - -test_data_path = os.path.join(os.path.dirname(__file__), './data') - -def _check_level(self, label, expected, actual): - """ Check one level of a potentially nested object / list """ - # object array is returned from cell array in mat file - typex = type(expected) - typac = type(actual) - if isinstance(expected, ndarray) and expected.dtype.hasobject: - assert typex is typac, "Different types at %s" % label - assert len(expected) == len(actual), "Different list lengths at %s" % label - for i, ev in enumerate(expected): - level_label = "%s, [%d], " % (label, i) - self._check_level(level_label, ev, actual[i]) - return - # object, as container for matlab structs and objects - elif isinstance(expected, mat_struct) or isinstance(expected, mat_obj): - assert isinstance(actual, typex), \ - "Different types %s and %s at %s" % (typex, typac, label) - ex_fields = dir(expected) - ac_fields = dir(actual) - for k in ex_fields: - if k.startswith('__') and k.endswith('__'): - continue - assert k in ac_fields, "Missing property at %s" % label - ev = expected.__dict__[k] - v = actual.__dict__[k] - level_label = "%s, property %s, " % (label, k) - self._check_level(level_label, ev, v) - return - # hoping this is a single value, which might be an array - if SP.issparse(expected): - assert SP.issparse(actual), "Expected sparse at %s" % label - assert_array_almost_equal(actual.todense(), - expected.todense(), - err_msg = label, - decimal = 5) - elif isinstance(expected, ndarray): - if expected.shape: # allow scalar and 0d array comparisons - assert isinstance(actual, ndarray), "Expected ndarray at %s" % label - assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) - else: - assert isinstance(expected, typac), \ - "Types %s and %s do not match at %s" % (typex, typac, label) - assert_equal(actual, expected, err_msg=label) - -def _check_case(self, name, files, case): - for file_name in files: - matdict = loadmat(file_name) - label = "test %s; file %s" % (name, file_name) - for k, expected in case.items(): - k_label = "%s, variable %s" % (label, k) - assert k in matdict, "Missing key at %s" % k_label - self._check_level(k_label, expected, matdict[k]) - -# Add the load tests dynamically, with given parameters -def _make_check_case(name, files, expected): - def cc(self): - self._check_case(name, files, expected) - cc.__doc__ = "check loadmat case %s" % name - return cc - -# Add the round trip tests dynamically, with given parameters -def _make_rt_check_case(name, expected, format): - def cc(self): - mat_stream = StringIO() - savemat(mat_stream, expected, format=format) - mat_stream.seek(0) - self._check_case(name, [mat_stream], expected) - cc.__doc__ = "check loadmat case %s" % name - return cc - -# Define cases to test -theta = pi/4*arange(9,dtype=float) -case_table4 = [ - {'name': 'double', - 'expected': {'testdouble': theta} - }] -case_table4.append( - {'name': 'string', - 'expected': {'teststring': u'"Do nine men interpret?" "Nine men," I nod.'}, - }) -case_table4.append( - {'name': 'complex', - 'expected': {'testcomplex': cos(theta) + 1j*sin(theta)} - }) -A = zeros((3,5)) -A[0] = range(1,6) -A[:,0] = range(1,4) -case_table4.append( - {'name': 'matrix', - 'expected': {'testmatrix': A}, - }) -case_table4.append( - {'name': 'sparse', - 'expected': {'testsparse': SP.csc_matrix(A)}, - }) -B = A.astype(complex) -B[0,0] += 1j -case_table4.append( - {'name': 'sparsecomplex', - 'expected': {'testsparsecomplex': SP.csc_matrix(B)}, - }) -case_table4.append( - {'name': 'multi', - 'expected': {'theta': theta, - 'a': A}, - }) -case_table4.append( - {'name': 'minus', - 'expected': {'testminus': array(-1)}, - }) -case_table4.append( - {'name': 'onechar', - 'expected': {'testonechar': u'r'}, - }) -case_table5 = [ - {'name': 'cell', - 'expected': {'testcell': - array([u'This cell contains this string and 3 arrays of '+\ - 'increasing length', - array(1), array([1,2]), array([1,2,3])], - dtype=object)} - }] -case_table5.append( - {'name': 'emptycell', - 'expected': {'testemptycell': - array([array(1), array(2), array([]), - array([]), array(3)], dtype=object)} - }) -case_table5.append( - {'name': 'stringarray', - 'expected': {'teststringarray': array( - [u'one ', u'two ', u'three'], dtype=object)}, - }) -case_table5.append( - {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }) -case_table5_rt = [ - {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }] -st = mat_struct() -st.stringfield = u'Rats live on no evil star.' -st.doublefield = array([sqrt(2),exp(1),pi]) -st.complexfield = (1+1j)*array([sqrt(2),exp(1),pi]) -case_table5.append( - {'name': 'struct', - 'expected': {'teststruct': st} - }) -a = array([array(1), - array([array(2), array(3), - array([array(4), array(5)], - dtype=object)], - dtype=object)], - dtype=object) -case_table5.append( - {'name': 'cellnest', - 'expected': {'testcellnest': a}, - }) -st = mat_struct() -st.one = array(1) -st.two = mat_struct() -st.two.three = u'number 3' -case_table5.append( - {'name': 'structnest', - 'expected': {'teststructnest': st} - }) -a = array([mat_struct(), mat_struct()]) -a[0].one = array(1) -a[0].two = array(2) -a[1].one = u'number 1' -a[1].two = u'number 2' -case_table5.append( - {'name': 'structarr', - 'expected': {'teststructarr': a} - }) -a = mat_obj() -a._classname = 'inline' -a.expr = u'x' -a.inputExpr = u' x = INLINE_INPUTS_{1};' -a.args = u'x' -a.isEmpty = array(0) -a.numArgs = array(1) -a.version = array(1) -case_table5.append( - {'name': 'object', - 'expected': {'testobject': a} - }) -u_str = file( - os.path.join(test_data_path, 'japanese_utf8.txt'), - 'rb').read().decode('utf-8') -case_table5.append( - {'name': 'unicode', - 'expected': {'testunicode': u_str} - }) -# add load tests - -def test_loads(): - for case in case_table4 + case_table5: - name = case['name'] - expected = case['expected'] - filt = os.path.join(test_data_path, 'test%s_*.mat' % name) - files = glob(filt) - assert files, "No files for test %s using filter %s" % (name, filt) - yield _make_check_case, name, files, expected - -def test_round_trips(): - for case in case_table4 + case_table5_rt: - name = case['name'] + '_round_trip' - expected = case['expected'] - format = case in case_table4 and '4' or '5' - yield _make_rt_check_case, name, expected, format - Added: branches/testing_cleanup/scipy/misc/tests/test_basic.py =================================================================== --- branches/testing_cleanup/scipy/misc/tests/test_basic.py 2008-01-04 12:29:00 UTC (rev 3781) +++ branches/testing_cleanup/scipy/misc/tests/test_basic.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -0,0 +1,46 @@ +''' Test functions for factorial, comb functions ''' + +from scipy.testing import * +import numpy as np +from scipy.misc import factorial, comb + + +class test_factorial(TestCase): + def test_basic(self): + for k in range(0,13): + assert_equal(factorial(k), + np.product(np.arange(1,k+1),axis=0)) + assert_equal(factorial(-10), 0) + + def test_exact(self): + resdict = {4:24L,10:3628800L,15:1307674368000L, + 19:121645100408832000L, + 100:93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L} + for key in resdict.keys(): + assert_equal(factorial(key,exact=1),resdict[key]) + + +class test_comb(TestCase): + + def test_basic(self): + for N in range(0,11): + for k in range(0,N+1): + ans = np.product(np.arange(N-k+1,N+1),axis=0) \ + / np.product(np.arange(1,k+1),axis=0) + assert_almost_equal(comb(N,k),ans,9) + assert(comb(-10,1) == 0) + assert(comb(10,-1) == 0) + assert(comb(-10,-3) == 0) + assert(comb(10,11) == 0) + + def test_exact(self): + resdict = {(10,2):45L, (10,5):252L, + (1000,20):339482811302457603895512614793686020778700L, + (1000,975):47641862536236518640933948075167736642053976275040L + } + for key in resdict.keys(): + assert_equal(comb(key[0],key[1],exact=1),resdict[key]) + + +if __name__ == '__main__': + unittest.main() Modified: branches/testing_cleanup/scipy/optimize/tests/test_slsqp.py =================================================================== --- branches/testing_cleanup/scipy/optimize/tests/test_slsqp.py 2008-01-04 12:29:00 UTC (rev 3781) +++ branches/testing_cleanup/scipy/optimize/tests/test_slsqp.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -83,7 +83,7 @@ ieqcons = [lambda x, y: x[0]-x[1]-1.0], iprint=0, full_output=1) x,fx,its,imode,smode = res - assert_array_almost_equal(x,[2,1]) + assert_array_almost_equal(x,[2,1],decimal=3) if __name__ == "__main__": unittest.main() Modified: branches/testing_cleanup/scipy/sparse/tests/test_base.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_base.py 2008-01-04 12:29:00 UTC (rev 3781) +++ branches/testing_cleanup/scipy/sparse/tests/test_base.py 2008-01-04 21:27:41 UTC (rev 3782) @@ -304,7 +304,7 @@ assert_equal( result.shape, (4,2) ) assert_equal( result, dot(a,b) ) - def check_formatconversions(self): + def test_formatconversions(self): A = spkron([[1,0,1],[0,1,1],[1,0,0]], [[1,1],[0,1]] ) D = A.todense() A = self.spmatrix(A) From scipy-svn at scipy.org Fri Jan 4 16:33:04 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 4 Jan 2008 15:33:04 -0600 (CST) Subject: [Scipy-svn] r3783 - branches/testing_cleanup Message-ID: <20080104213304.7013E39C247@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-04 15:33:02 -0600 (Fri, 04 Jan 2008) New Revision: 3783 Modified: branches/testing_cleanup/ Log: svnmerge properties Property changes on: branches/testing_cleanup ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 + /branches/scipy.scons:1-3533 /trunk:1-3661 From scipy-svn at scipy.org Sat Jan 5 01:05:59 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 5 Jan 2008 00:05:59 -0600 (CST) Subject: [Scipy-svn] r3784 - trunk/scipy/sparse/sparsetools Message-ID: <20080105060559.8305639C10D@new.scipy.org> Author: wnbell Date: 2008-01-05 00:05:54 -0600 (Sat, 05 Jan 2008) New Revision: 3784 Modified: trunk/scipy/sparse/sparsetools/fixed_size.h trunk/scipy/sparse/sparsetools/sparsetools.h Log: added fixed size matrix matrix products for fast BSR * BSR Modified: trunk/scipy/sparse/sparsetools/fixed_size.h =================================================================== --- trunk/scipy/sparse/sparsetools/fixed_size.h 2008-01-04 21:33:02 UTC (rev 3783) +++ trunk/scipy/sparse/sparsetools/fixed_size.h 2008-01-05 06:05:54 UTC (rev 3784) @@ -2,7 +2,7 @@ #define FIXED_SIZE_H /* - * templates for fixed size array and vector arithmetic + * templates for fixed size vector and matrix arithmetic * */ @@ -12,95 +12,139 @@ * Dot Product * */ -template +template class _dot { public: - inline T operator()(const T * V1, const T * V2) + inline T operator()(const T * X, const T * Y) { - _dot d; - return (*V1) * (*V2) + d(V1 + 1, V2 + 1); + _dot d; + return (*X) * (*Y) + d(X + SX, Y + SY); } }; -template -class _dot<1,T> +template +class _dot<1,SX,SY,T> { public: - inline T operator()(const T * V1, const T * V2) + inline T operator()(const T * X, const T * Y) { - return (*V1) * (*V2); + return (*X) * (*Y); } }; -template -inline T dot(const T * V1, const T * V2) +template +inline T dot(const T * X, const T * Y) { - _dot d; - return d(V1, V2); + _dot d; + return d(X, Y); } /* - * Matrix Vector Product + * Matrix Vector Product Y = A*X * */ -template +template class _matvec { public: inline void operator()(const T * A, const T * X, T * Y) { - *Y += dot(A,X); - _matvec d; - d(A + N, X, Y + 1); + *Y += dot(A,X); + _matvec d; + d(A + N, X, Y + SY); } }; -template -class _matvec<1,N,T> + +template +class _matvec<1,N,SX,SY,T> { public: inline void operator()(const T * A, const T * X, T * Y) { - *Y += dot(A,X); + *Y += dot(A,X); } }; -template +template inline void matvec(const T * A, const T * X, T * Y) { - _matvec d; + _matvec d; d(A,X,Y); } +/* + * Matrix Matrix Product C = A*B + * + * C is L*N + * A is L*M + * B is M*N + * + */ +template +class _matmat +{ + public: + inline void operator()(const T * A, const T * B, T * C) + { + matvec(A,B,C); + + _matmat d; + d(A, B + 1, C + 1); + } +}; +template +class _matmat +{ + public: + inline void operator()(const T * A, const T * B, T * C) + { + matvec(A,B,C); + } +}; +template +inline void matmat(const T * A, const T * B, T * C) +{ + _matmat d; + d(A,B,C); +} + + + +/* + * Binary vector operation Z = op(X,Y) + * + */ + template class _vec_binop_vec { public: - inline void operator()(const T * V1, const T * V2, T * V3, const bin_op& op) + inline void operator()(const T * X, const T * Y, T * Z, const bin_op& op) { - *V3 = op( *V1, *V2 ); + *Z = op( *X, *Y ); _vec_binop_vec d; - d(V1 + 1, V2 + 1, V3 + 1, op); + d(X + 1, Y + 1, Z + 1, op); } }; template class _vec_binop_vec<1,T,bin_op> { public: - inline void operator()(const T * V1, const T * V2, T * V3, const bin_op& op) + inline void operator()(const T * X, const T * Y, T * Z, const bin_op& op) { - *V3 = op( *V1, *V2 ); + *Z = op( *X, *Y ); } }; template -inline void vec_binop_vec(const T * V1, const T * V2, T * V3, const bin_op& op) +inline void vec_binop_vec(const T * X, const T * Y, T * Z, const bin_op& op) { _vec_binop_vec d; - d(V1,V2,V3,op); + d(X,Y,Z,op); } Modified: trunk/scipy/sparse/sparsetools/sparsetools.h =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.h 2008-01-04 21:33:02 UTC (rev 3783) +++ trunk/scipy/sparse/sparsetools/sparsetools.h 2008-01-05 06:05:54 UTC (rev 3784) @@ -462,6 +462,74 @@ Cp[i+1] = nnz; } } + + + +template +void bsr_matmat_pass2_fixed(const I n_brow, const I n_bcol, + const I Ap[], const I Aj[], const T Ax[], + const I Bp[], const I Bj[], const T Bx[], + I Cp[], I Cj[], T Cx[]) +{ + const I RC = R*C; + const I RN = R*N; + const I NC = N*C; + const I SIZE = RC*Cp[n_brow]; + + for(I i = 0; i < SIZE; i++){ + Cx[i] = 0; + } + + std::vector next(n_bcol,-1); + std::vector mats(n_bcol); + + + I nnz = 0; + + Cp[0] = 0; + + for(I i = 0; i < n_brow; i++){ + I head = -2; + I length = 0; + + I jj_start = Ap[i]; + I jj_end = Ap[i+1]; + for(I jj = jj_start; jj < jj_end; jj++){ + I j = Aj[jj]; + + I kk_start = Bp[j]; + I kk_end = Bp[j+1]; + for(I kk = kk_start; kk < kk_end; kk++){ + I k = Bj[kk]; + + if(next[k] == -1){ + next[k] = head; + head = k; + Cj[nnz] = k; + mats[k] = Cx + RC*nnz; + nnz++; + length++; + } + + const T * A = Ax + jj*RN; + const T * B = Bx + kk*NC; + T * result = mats[k]; + matmat(A,B,result); + } + } + + for(I jj = 0; jj < length; jj++){ + I temp = head; + head = next[head]; + next[temp] = -1; //clear arrays + } + + } + +} + +#define F(X,Y,Z) bsr_matmat_pass2_fixed + template void bsr_matmat_pass2(const I n_brow, const I n_bcol, const I R, const I C, const I N, @@ -469,21 +537,55 @@ const I Bp[], const I Bj[], const T Bx[], I Cp[], I Cj[], T Cx[]) { + assert(R > 0 && C > 0 && N > 0); + +#ifdef TESTING + void (*dispatch[4][4][4])(I,I,const I*,const I*,const T*, + const I*,const I*,const T*, + I*, I*, T*) = \ + { + { { F(1,1,1), F(1,1,2), F(1,1,3), F(1,1,4) }, + { F(1,2,1), F(1,2,2), F(1,2,3), F(1,2,4) }, + { F(1,3,1), F(1,3,2), F(1,3,3), F(1,3,4) }, + { F(1,4,1), F(1,4,2), F(1,4,3), F(1,4,4) }, + }, + { { F(2,1,1), F(2,1,2), F(2,1,3), F(2,1,4) }, + { F(2,2,1), F(2,2,2), F(2,2,3), F(2,2,4) }, + { F(2,3,1), F(2,3,2), F(2,3,3), F(2,3,4) }, + { F(2,4,1), F(2,4,2), F(2,4,3), F(2,4,4) }, + }, + { { F(3,1,1), F(3,1,2), F(3,1,3), F(3,1,4) }, + { F(3,2,1), F(3,2,2), F(3,2,3), F(3,2,4) }, + { F(3,3,1), F(3,3,2), F(3,3,3), F(3,3,4) }, + { F(3,4,1), F(3,4,2), F(3,4,3), F(3,4,4) }, + }, + { { F(4,1,1), F(4,1,2), F(4,1,3), F(4,1,4) }, + { F(4,2,1), F(4,2,2), F(4,2,3), F(4,2,4) }, + { F(4,3,1), F(4,3,2), F(4,3,3), F(4,3,4) }, + { F(4,4,1), F(4,4,2), F(4,4,3), F(4,4,4) }, + } + }; + + if (R <= 4 && C <= 4 && N <= 4){ + dispatch[R-1][N-1][C-1](n_brow,n_bcol,Ap,Aj,Ax,Bp,Bj,Bx,Cp,Cj,Cx); + return; + } +#endif + const I RC = R*C; const I RN = R*N; const I NC = N*C; const I SIZE = RC*Cp[n_brow]; + for(I i = 0; i < SIZE; i++){ Cx[i] = 0; } std::vector next(n_bcol,-1); std::vector mats(n_bcol); - I nnz = 0; - Cp[0] = 0; for(I i = 0; i < n_brow; i++){ @@ -518,34 +620,24 @@ result[C*r + c] += A[N*r + n] * B[C*n + c]; } - //std::cout << "result[" << r << "," << c << "] = " << result[C*r + c] << std::endl; } } } } for(I jj = 0; jj < length; jj++){ - - //if(is_nonzero_block(result,RC)){ - // Cj[nnz] = head; - // Cx[nnz] = sums[head]; - // nnz++; - //} - I temp = head; head = next[head]; - next[temp] = -1; //clear arrays } - //Cp[i+1] = nnz; } } +#undef F - template bool is_nonzero_block(const T block[], const I blocksize){ for(I i = 0; i < blocksize; i++){ @@ -1148,7 +1240,7 @@ for(I i = 0; i < n_brow; i++) { for(I jj = Ap[i]; jj < Ap[i+1]; jj++) { I j = Aj[jj]; - matvec(Ax + jj*R*C, Xx + j*C, Yx + i*R); + matvec(Ax + jj*R*C, Xx + j*C, Yx + i*R); } } } From scipy-svn at scipy.org Sat Jan 5 02:04:25 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 5 Jan 2008 01:04:25 -0600 (CST) Subject: [Scipy-svn] r3785 - branches/testing_cleanup Message-ID: <20080105070425.C60E939C014@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-05 01:04:22 -0600 (Sat, 05 Jan 2008) New Revision: 3785 Modified: branches/testing_cleanup/ Log: More svnmerge properties Property changes on: branches/testing_cleanup ___________________________________________________________________ Name: svnmerge-blocked + /trunk:3663-3666,3673,3676-3683,3685-3722,3736-3737,3739-3743,3745-3748,3750-3753,3756-3758,3760,3762-3763,3765-3768,3770-3773,3775-3777 From scipy-svn at scipy.org Sat Jan 5 03:16:35 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 5 Jan 2008 02:16:35 -0600 (CST) Subject: [Scipy-svn] r3786 - in branches/testing_cleanup: . scipy/io/matlab scipy/sparse scipy/sparse/sparsetools scipy/sparse/tests Message-ID: <20080105081635.3AFF239C0D3@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-05 02:16:25 -0600 (Sat, 05 Jan 2008) New Revision: 3786 Modified: branches/testing_cleanup/ branches/testing_cleanup/scipy/io/matlab/mio5.py branches/testing_cleanup/scipy/io/matlab/miobase.py branches/testing_cleanup/scipy/sparse/bsr.py branches/testing_cleanup/scipy/sparse/compressed.py branches/testing_cleanup/scipy/sparse/sparsetools/fixed_size.h branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.h branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.i branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.py branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools_wrap.cxx branches/testing_cleanup/scipy/sparse/tests/test_base.py Log: Merged with trunk up to 3784 Property changes on: branches/testing_cleanup ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 /trunk:1-3661 + /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3785 Modified: branches/testing_cleanup/scipy/io/matlab/mio5.py =================================================================== --- branches/testing_cleanup/scipy/io/matlab/mio5.py 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/io/matlab/mio5.py 2008-01-05 08:16:25 UTC (rev 3786) @@ -190,23 +190,25 @@ def read_element(self, copy=True): raw_tag = self.mat_stream.read(8) tag = N.ndarray(shape=(), - dtype=self.dtypes['tag_full'], - buffer = raw_tag) + dtype=self.dtypes['tag_full'], + buffer=raw_tag) mdtype = tag['mdtype'].item() + byte_count = mdtype >> 16 if byte_count: # small data element format if byte_count > 4: raise ValueError, 'Too many bytes for sde format' mdtype = mdtype & 0xFFFF dt = self.dtypes[mdtype] - el_count = byte_count / dt.itemsize + el_count = byte_count // dt.itemsize return N.ndarray(shape=(el_count,), - dtype=dt, - buffer=raw_tag[4:]) + dtype=dt, + buffer=raw_tag[4:]) + byte_count = tag['byte_count'].item() if mdtype == miMATRIX: return self.current_getter(byte_count).get_array() - if mdtype in self.codecs: # encoded char data + elif mdtype in self.codecs: # encoded char data raw_str = self.mat_stream.read(byte_count) codec = self.codecs[mdtype] if not codec: @@ -214,15 +216,18 @@ el = raw_str.decode(codec) else: # numeric data dt = self.dtypes[mdtype] - el_count = byte_count / dt.itemsize + el_count = byte_count // dt.itemsize el = N.ndarray(shape=(el_count,), dtype=dt, buffer=self.mat_stream.read(byte_count)) if copy: el = el.copy() + + # Seek to next 64-bit boundary mod8 = byte_count % 8 if mod8: self.mat_stream.seek(8 - mod8, 1) + return el def matrix_getter_factory(self): @@ -572,14 +577,16 @@ tag['mdtype'] = np_to_mtypes[arr.dtype.str[1:]] else: tag['mdtype'] = mdtype - tag['byte_count'] = arr.size*arr.itemsize + + tag['byte_count'] = arr.size*arr.itemsize + padding = (8 - tag['byte_count']) % 8 + self.write_dtype(tag) self.write_bytes(arr) - # do 8 byte padding if needed - if tag['byte_count']%8 != 0: - pad = (1+tag['byte_count']//8)*8 - tag['byte_count'] - self.write_bytes(N.zeros((pad,),dtype='u1')) + # pad to next 64-bit boundary + self.write_bytes(N.zeros((padding,),'u1')) + def write_header(self, mclass, is_global=False, is_complex=False, @@ -673,7 +680,6 @@ A.sort_indices() # MATLAB expects sorted row indices is_complex = (A.dtype.kind == 'c') nz = A.nnz - self.write_header(mclass=mxSPARSE_CLASS, is_complex=is_complex, nzmax=nz) Modified: branches/testing_cleanup/scipy/io/matlab/miobase.py =================================================================== --- branches/testing_cleanup/scipy/io/matlab/miobase.py 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/io/matlab/miobase.py 2008-01-05 08:16:25 UTC (rev 3786) @@ -90,11 +90,9 @@ or in ('little', '<') or in ('BIG', '>') mat_dtype - return arrays in same dtype as loaded into matlab - (instead of the dtype with which they are saved) + (instead of the dtype with which they were saved) squeeze_me - whether to squeeze unit dimensions or not chars_as_strings - whether to convert char arrays to string arrays - mat_dtype - return matrices with datatype that matlab would load as - (rather than in the datatype matlab saves as) matlab_compatible - returns matrices as would be loaded by matlab (implies squeeze_me=False, chars_as_strings=False mat_dtype=True) Modified: branches/testing_cleanup/scipy/sparse/bsr.py =================================================================== --- branches/testing_cleanup/scipy/sparse/bsr.py 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/sparse/bsr.py 2008-01-05 08:16:25 UTC (rev 3786) @@ -1,5 +1,4 @@ -"""Compressed Block Sparse Row matrix format -""" +"""Compressed Block Sparse Row matrix format""" __all__ = ['bsr_matrix', 'isspmatrix_bsr'] @@ -12,7 +11,7 @@ from sparsetools import bsr_matvec, csr_matmat_pass1, bsr_matmat_pass2 from data import _data_matrix from compressed import _cs_matrix -from base import isspmatrix +from base import isspmatrix, _formats from sputils import isshape, getdtype, to_native, isscalarlike, isdense, \ upcast @@ -21,44 +20,45 @@ This can be instantiated in several ways: - bsr_matrix(D, [blocksize=(R,C)]) - with a dense matrix or rank-2 ndarray D + - with a dense matrix or rank-2 ndarray D - bsr_matrix(S, [blocksize=(R,C)]) - with another sparse matrix S (equivalent to S.tocsr()) + - with another sparse matrix S (equivalent to S.tobsr()) - bsr_matrix((M, N), [blocksize=(R,C), dtype]) - to construct an empty matrix with shape (M, N) - dtype is optional, defaulting to dtype='d'. + - to construct an empty matrix with shape (M, N) + - dtype is optional, defaulting to dtype='d'. - bsr_matrix((data, ij), [blocksize=(R,C), shape=(M, N)]) - where data, ij satisfy: - a[ij[0, k], ij[1, k]] = data[k] + - where data, ij satisfy: + - a[ij[0, k], ij[1, k]] = data[k] - bsr_matrix((data, indices, indptr), [shape=(M, N)]) - is the standard BSR representation where: - the block column indices for row i are stored in - indices[ indptr[i]: indices[i+1] ] - and their corresponding block values are stored in - data[ indptr[i]: indptr[i+1] ] - If the shape parameter is not supplied, the matrix dimensions - are inferred from the index arrays. + - is the standard BSR representation where: + the block column indices for row i are stored in + - indices[ indptr[i]: indices[i+1] ] + and their corresponding block values are stored in + - data[ indptr[i]: indptr[i+1] ] + - if the shape parameter is not supplied, the matrix dimensions + are inferred from the index arrays. - *Notes* - ------- - The blocksize (R,C) must evenly divide the shape of - the matrix (M,N). That is, R and C must satisfy the - relationship M % R = 0 and N % C = 0. + Notes + ===== + + - The blocksize (R,C) must evenly divide the shape of + the matrix (M,N). That is, R and C must satisfy the + relationship M % R = 0 and N % C = 0. - The Block Compressed Row (BSR) format is very similar to the - Compressed Sparse Row (CSR) format. BSR is appropriate for - sparse matrices with dense sub matrices like the last example - below. Such matrices often arise, for instance, in finite - element discretizations. + - The Block Compressed Row (BSR) format is very similar to the + Compressed Sparse Row (CSR) format. BSR is appropriate for + sparse matrices with dense sub matrices like the last example + below. Such matrices often arise, for instance, in vector-valued + finite element discretizations. - *Examples* - ---------- + Examples + ======== >>> from scipy.sparse import * >>> from scipy import * @@ -113,11 +113,11 @@ self.data = zeros( (0,) + blocksize, getdtype(dtype, default=float) ) self.indices = zeros( 0, dtype=intc ) - X,Y = blocksize - if (M % X) != 0 or (N % Y) != 0: + R,C = blocksize + if (M % R) != 0 or (N % C) != 0: raise ValueError, 'shape must be multiple of blocksize' - self.indptr = zeros(M/X + 1, dtype=intc ) + self.indptr = zeros(M/R + 1, dtype=intc ) elif len(arg1) == 2: # (data,(row,col)) format @@ -279,7 +279,7 @@ """ if isdense(other): M,N = self.shape - X,Y = self.blocksize + R,C = self.blocksize if other.shape != (N,) and other.shape != (N,1): raise ValueError, "dimension mismatch" @@ -299,7 +299,7 @@ y = output - bsr_matvec(M/X, N/Y, X, Y, \ + bsr_matvec(M/R, N/C, R, C, \ self.indptr, self.indices, ravel(self.data), ravel(other), y) if isinstance(other, matrix): @@ -389,15 +389,15 @@ """ M,N = self.shape - X,Y = self.blocksize + R,C = self.blocksize - row = (X * arange(M/X)).repeat(diff(self.indptr)) - row = row.repeat(X*Y).reshape(-1,X,Y) - row += tile( arange(X).reshape(-1,1), (1,Y) ) + row = (R * arange(M/R)).repeat(diff(self.indptr)) + row = row.repeat(R*C).reshape(-1,R,C) + row += tile( arange(R).reshape(-1,1), (1,C) ) row = row.reshape(-1) - col = (Y * self.indices).repeat(X*Y).reshape(-1,X,Y) - col += tile( arange(Y), (X,1) ) + col = (C * self.indices).repeat(R*C).reshape(-1,R,C) + col += tile( arange(C), (R,1) ) col = col.reshape(-1) data = self.data.reshape(-1) @@ -411,16 +411,16 @@ def transpose(self): - X,Y = self.blocksize + R,C = self.blocksize M,N = self.shape if self.nnz == 0: - return bsr_matrix((N,M),blocksize=(Y,X)) + return bsr_matrix((N,M),blocksize=(C,R)) #use CSR.T to determine a permutation for BSR.T from csr import csr_matrix data = arange(len(self.indices), dtype=self.indices.dtype) - proxy = csr_matrix((data,self.indices,self.indptr),shape=(M/X,N/Y)) + proxy = csr_matrix((data,self.indices,self.indptr),shape=(M/R,N/C)) proxy = proxy.tocsc() data = self.data.swapaxes(1,2)[proxy.data] #permute data @@ -434,7 +434,29 @@ ############################################################## # methods that examine or modify the internal data structure # ############################################################## - + + def eliminate_zeros(self): + R,C = self.blocksize + M,N = self.shape + + mask = (self.data != 0).reshape(-1,R*C).sum(axis=1) #nonzero blocks + + nonzero_blocks = mask.nonzero()[0] + + if len(nonzero_blocks) == 0: + return #nothing to do + + self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks] + + from csr import csr_matrix + + # modifies self.indptr and self.indices *in place* + proxy = csr_matrix((mask,self.indices,self.indptr),shape=(M/R,N/C)) + proxy.eliminate_zeros() + + self.prune() + + def sum_duplicates(self): raise NotImplementedError Modified: branches/testing_cleanup/scipy/sparse/compressed.py =================================================================== --- branches/testing_cleanup/scipy/sparse/compressed.py 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/sparse/compressed.py 2008-01-05 08:16:25 UTC (rev 3786) @@ -553,6 +553,17 @@ # methods that examine or modify the internal data structure # ############################################################## + def eliminate_zeros(self): + """Remove zero entries from the matrix + + The is an *in place* operation + """ + fn = sparsetools.csr_eliminate_zeros + M,N = self._swap(self.shape) + fn( M, N, self.indptr, self.indices, self.data) + + self.prune() #nnz may have changed + def sum_duplicates(self): """Eliminate duplicate matrix entries by adding them together @@ -570,8 +581,10 @@ def __get_sorted(self): """Determine whether the matrix has sorted indices - True if the indices of the matrix are in - sorted order, False otherwise. + Returns + - True: if the indices of the matrix are in sorted order + - False: otherwise + """ #first check to see if result was cached Modified: branches/testing_cleanup/scipy/sparse/sparsetools/fixed_size.h =================================================================== --- branches/testing_cleanup/scipy/sparse/sparsetools/fixed_size.h 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/sparse/sparsetools/fixed_size.h 2008-01-05 08:16:25 UTC (rev 3786) @@ -2,7 +2,7 @@ #define FIXED_SIZE_H /* - * templates for fixed size array and vector arithmetic + * templates for fixed size vector and matrix arithmetic * */ @@ -12,63 +12,139 @@ * Dot Product * */ -template +template class _dot { public: - inline T operator()(const T * V1, const T * V2) + inline T operator()(const T * X, const T * Y) { - _dot d; - return (*V1) * (*V2) + d(++V1, ++V2); + _dot d; + return (*X) * (*Y) + d(X + SX, Y + SY); } }; -template -class _dot<1,T> +template +class _dot<1,SX,SY,T> { public: - inline T operator()(const T * V1, const T * V2) + inline T operator()(const T * X, const T * Y) { - return (*V1) * (*V2); + return (*X) * (*Y); } }; -template -inline T dot(const T * V1, const T * V2) +template +inline T dot(const T * X, const T * Y) { - _dot d; - return d(V1, V2); + _dot d; + return d(X, Y); } +/* + * Matrix Vector Product Y = A*X + * + */ +template +class _matvec +{ + public: + inline void operator()(const T * A, const T * X, T * Y) + { + *Y += dot(A,X); + _matvec d; + d(A + N, X, Y + SY); + } +}; +template +class _matvec<1,N,SX,SY,T> +{ + public: + inline void operator()(const T * A, const T * X, T * Y) + { + *Y += dot(A,X); + } +}; +template +inline void matvec(const T * A, const T * X, T * Y) +{ + _matvec d; + d(A,X,Y); +} + + +/* + * Matrix Matrix Product C = A*B + * + * C is L*N + * A is L*M + * B is M*N + * + */ +template +class _matmat +{ + public: + inline void operator()(const T * A, const T * B, T * C) + { + matvec(A,B,C); + + _matmat d; + d(A, B + 1, C + 1); + } +}; +template +class _matmat +{ + public: + inline void operator()(const T * A, const T * B, T * C) + { + matvec(A,B,C); + } +}; + +template +inline void matmat(const T * A, const T * B, T * C) +{ + _matmat d; + d(A,B,C); +} + + + +/* + * Binary vector operation Z = op(X,Y) + * + */ + template class _vec_binop_vec { public: - inline void operator()(const T * V1, const T * V2, T * V3, const bin_op& op) + inline void operator()(const T * X, const T * Y, T * Z, const bin_op& op) { - *V3 = op( *V1, *V2 ); + *Z = op( *X, *Y ); _vec_binop_vec d; - d(V1 + 1, V2 + 1, V3 + 1, op); + d(X + 1, Y + 1, Z + 1, op); } }; template class _vec_binop_vec<1,T,bin_op> { public: - inline void operator()(const T * V1, const T * V2, T * V3, const bin_op& op) + inline void operator()(const T * X, const T * Y, T * Z, const bin_op& op) { - *V3 = op( *V1, *V2 ); + *Z = op( *X, *Y ); } }; template -inline void vec_binop_vec(const T * V1, const T * V2, T * V3, const bin_op& op) +inline void vec_binop_vec(const T * X, const T * Y, T * Z, const bin_op& op) { _vec_binop_vec d; - d(V1,V2,V3,op); + d(X,Y,Z,op); } Modified: branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.h =================================================================== --- branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.h 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.h 2008-01-05 08:16:25 UTC (rev 3786) @@ -330,7 +330,7 @@ const I Bj[], I Cp[]) { -// // method that uses O(n) temp storage +// // method that uses O(1) temp storage // const I hash_size = 1 << 5; // I vals[hash_size]; // I mask[hash_size]; @@ -462,6 +462,74 @@ Cp[i+1] = nnz; } } + + + +template +void bsr_matmat_pass2_fixed(const I n_brow, const I n_bcol, + const I Ap[], const I Aj[], const T Ax[], + const I Bp[], const I Bj[], const T Bx[], + I Cp[], I Cj[], T Cx[]) +{ + const I RC = R*C; + const I RN = R*N; + const I NC = N*C; + const I SIZE = RC*Cp[n_brow]; + + for(I i = 0; i < SIZE; i++){ + Cx[i] = 0; + } + + std::vector next(n_bcol,-1); + std::vector mats(n_bcol); + + + I nnz = 0; + + Cp[0] = 0; + + for(I i = 0; i < n_brow; i++){ + I head = -2; + I length = 0; + + I jj_start = Ap[i]; + I jj_end = Ap[i+1]; + for(I jj = jj_start; jj < jj_end; jj++){ + I j = Aj[jj]; + + I kk_start = Bp[j]; + I kk_end = Bp[j+1]; + for(I kk = kk_start; kk < kk_end; kk++){ + I k = Bj[kk]; + + if(next[k] == -1){ + next[k] = head; + head = k; + Cj[nnz] = k; + mats[k] = Cx + RC*nnz; + nnz++; + length++; + } + + const T * A = Ax + jj*RN; + const T * B = Bx + kk*NC; + T * result = mats[k]; + matmat(A,B,result); + } + } + + for(I jj = 0; jj < length; jj++){ + I temp = head; + head = next[head]; + next[temp] = -1; //clear arrays + } + + } + +} + +#define F(X,Y,Z) bsr_matmat_pass2_fixed + template void bsr_matmat_pass2(const I n_brow, const I n_bcol, const I R, const I C, const I N, @@ -469,22 +537,55 @@ const I Bp[], const I Bj[], const T Bx[], I Cp[], I Cj[], T Cx[]) { + assert(R > 0 && C > 0 && N > 0); + +#ifdef TESTING + void (*dispatch[4][4][4])(I,I,const I*,const I*,const T*, + const I*,const I*,const T*, + I*, I*, T*) = \ + { + { { F(1,1,1), F(1,1,2), F(1,1,3), F(1,1,4) }, + { F(1,2,1), F(1,2,2), F(1,2,3), F(1,2,4) }, + { F(1,3,1), F(1,3,2), F(1,3,3), F(1,3,4) }, + { F(1,4,1), F(1,4,2), F(1,4,3), F(1,4,4) }, + }, + { { F(2,1,1), F(2,1,2), F(2,1,3), F(2,1,4) }, + { F(2,2,1), F(2,2,2), F(2,2,3), F(2,2,4) }, + { F(2,3,1), F(2,3,2), F(2,3,3), F(2,3,4) }, + { F(2,4,1), F(2,4,2), F(2,4,3), F(2,4,4) }, + }, + { { F(3,1,1), F(3,1,2), F(3,1,3), F(3,1,4) }, + { F(3,2,1), F(3,2,2), F(3,2,3), F(3,2,4) }, + { F(3,3,1), F(3,3,2), F(3,3,3), F(3,3,4) }, + { F(3,4,1), F(3,4,2), F(3,4,3), F(3,4,4) }, + }, + { { F(4,1,1), F(4,1,2), F(4,1,3), F(4,1,4) }, + { F(4,2,1), F(4,2,2), F(4,2,3), F(4,2,4) }, + { F(4,3,1), F(4,3,2), F(4,3,3), F(4,3,4) }, + { F(4,4,1), F(4,4,2), F(4,4,3), F(4,4,4) }, + } + }; + + if (R <= 4 && C <= 4 && N <= 4){ + dispatch[R-1][N-1][C-1](n_brow,n_bcol,Ap,Aj,Ax,Bp,Bj,Bx,Cp,Cj,Cx); + return; + } +#endif + const I RC = R*C; const I RN = R*N; const I NC = N*C; const I SIZE = RC*Cp[n_brow]; + for(I i = 0; i < SIZE; i++){ Cx[i] = 0; } - //std::cout << "n_brow " << n_brow << " Cp[-1] " << Cp[n_brow] << " R " << R << " C " << C << " N " << N << std::endl; std::vector next(n_bcol,-1); std::vector mats(n_bcol); - I nnz = 0; - Cp[0] = 0; for(I i = 0; i < n_brow; i++){ @@ -519,34 +620,24 @@ result[C*r + c] += A[N*r + n] * B[C*n + c]; } - //std::cout << "result[" << r << "," << c << "] = " << result[C*r + c] << std::endl; } } } } for(I jj = 0; jj < length; jj++){ - - //if(is_nonzero_block(result,RC)){ - // Cj[nnz] = head; - // Cx[nnz] = sums[head]; - // nnz++; - //} - I temp = head; head = next[head]; - next[temp] = -1; //clear arrays } - //Cp[i+1] = nnz; } } +#undef F - template bool is_nonzero_block(const T block[], const I blocksize){ for(I i = 0; i < blocksize; i++){ @@ -567,18 +658,9 @@ I Cp[], I Cj[], T Cx[], const bin_op& op) { - //Method that works for unsorted indices - // assert( csr_has_sorted_indices(n_brow,Ap,Aj) ); - // assert( csr_has_sorted_indices(n_brow,Bp,Bj) ); + const I RC = R*C; + T * result = Cx; - //if (R == 3 && C == 3){ - // bsr_binop_bsr_fixed(n_brow,n_bcol,Ap,Aj,Ax,Bp,Bj,Bx,Cp,Cj,Cx,op); - // return; - //} - - const I RC = R*C; - T result[8*8]; - //T zeros[8*8]; Cp[0] = 0; I nnz = 0; @@ -600,9 +682,7 @@ if( is_nonzero_block(result,RC) ){ Cj[nnz] = A_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -616,9 +696,7 @@ if(is_nonzero_block(result,RC)){ Cj[nnz] = A_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -631,9 +709,7 @@ } if(is_nonzero_block(result,RC)){ Cj[nnz] = B_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -644,15 +720,14 @@ //tail while(A_pos < A_end){ + for(I n = 0; n < RC; n++){ result[n] = op(Ax[RC*A_pos + n],0); } if(is_nonzero_block(result,RC)){ Cj[nnz] = A_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -663,11 +738,10 @@ for(I n = 0; n < RC; n++){ result[n] = op(0,Bx[RC*B_pos + n]); } + if(is_nonzero_block(result,RC)){ Cj[nnz] = B_j; - for(I n = 0; n < RC; n++){ - Cx[RC*nnz + n] = result[n]; - } + result += RC; nnz++; } @@ -887,7 +961,8 @@ * T Ax[nnz(A)] - nonzeros * * Note: - * Ap,Aj, and Ax will be modified *inplace* + * The column indicies within each row must be in sorted order. + * Ap, Aj, and Ax will be modified *inplace* * */ template @@ -916,49 +991,47 @@ } Ap[i+1] = nnz; } +} - - //method that works on unsorted indices -// std::vector next(n_col,-1); -// std::vector sums(n_col, 0); -// -// I nnz = 0; -// -// I row_start = 0; -// I row_end = 0; -// -// for(I i = 0; i < n_row; i++){ -// I head = -2; -// -// row_start = row_end; //Ap[i] may have been changed -// row_end = Ap[i+1]; //Ap[i+1] is safe -// -// for(I jj = row_start; jj < row_end; jj++){ -// I j = Aj[jj]; -// -// sums[j] += Ax[jj]; -// -// if(next[j] == -1){ -// next[j] = head; -// head = j; -// } -// } -// -// while(head != -2){ -// I curr = head; //current column -// head = next[curr]; -// -// if(sums[curr] != 0){ -// Aj[nnz] = curr; -// Ax[nnz] = sums[curr]; -// nnz++; -// } -// -// next[curr] = -1; -// sums[curr] = 0; -// } -// Ap[i+1] = nnz; -// } +/* + * Eliminate zero entries from CSR matrix A + * + * + * Input Arguments: + * I n_row - number of rows in A (and B) + * I n_col - number of columns in A (and B) + * I Ap[n_row+1] - row pointer + * I Aj[nnz(A)] - column indices + * T Ax[nnz(A)] - nonzeros + * + * Note: + * Ap, Aj, and Ax will be modified *inplace* + * + */ +template +void csr_eliminate_zeros(const I n_row, + const I n_col, + I Ap[], + I Aj[], + T Ax[]) +{ + I nnz = 0; + I row_end = 0; + for(I i = 0; i < n_row; i++){ + I jj = row_end; + row_end = Ap[i+1]; + while( jj < row_end ){ + I j = Aj[jj]; + T x = Ax[jj]; + if(x != 0){ + Aj[nnz] = j; + Ax[nnz] = x; + nnz++; + } + jj++; + } + Ap[i+1] = nnz; + } } @@ -985,8 +1058,6 @@ * Note: * Input: row and column indices *are not* assumed to be ordered * - * Output: CSR column indices *will be* in sorted order - * * Note: duplicate entries are carried over to the CSR represention * * Complexity: Linear. Specifically O(nnz(A) + max(n_row,n_col)) @@ -1162,38 +1233,15 @@ const T Xx[], T Yx[]) { - //TODO make a matvec template + for(I i = 0; i < R*n_brow; i++){ + Yx[i] = 0; + } + for(I i = 0; i < n_brow; i++) { - T r0 = 0; - T r1 = 0; - T r2 = 0; - T r3 = 0; - T r4 = 0; - T r5 = 0; - T r6 = 0; - T r7 = 0; - for(I jj = Ap[i]; jj < Ap[i+1]; jj++) { I j = Aj[jj]; - const T * base = Ax + jj*(R*C); - if (R > 0) r0 += dot(base + 0*C, Xx + j*C); - if (R > 1) r1 += dot(base + 1*C, Xx + j*C); - if (R > 2) r2 += dot(base + 2*C, Xx + j*C); - if (R > 3) r3 += dot(base + 3*C, Xx + j*C); - if (R > 4) r4 += dot(base + 4*C, Xx + j*C); - if (R > 5) r5 += dot(base + 5*C, Xx + j*C); - if (R > 6) r6 += dot(base + 6*C, Xx + j*C); - if (R > 7) r7 += dot(base + 7*C, Xx + j*C); + matvec(Ax + jj*R*C, Xx + j*C, Yx + i*R); } - - if (R > 0) Yx[R*i+0] = r0; - if (R > 1) Yx[R*i+1] = r1; - if (R > 2) Yx[R*i+2] = r2; - if (R > 3) Yx[R*i+3] = r3; - if (R > 4) Yx[R*i+4] = r4; - if (R > 5) Yx[R*i+5] = r5; - if (R > 6) Yx[R*i+6] = r6; - if (R > 7) Yx[R*i+7] = r7; } } @@ -1244,7 +1292,7 @@ //otherwise use general method - for(I i = 0; i < n_brow; i++){ + for(I i = 0; i < R*n_brow; i++){ Yx[i] = 0; } Modified: branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.i =================================================================== --- branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.i 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.i 2008-01-05 08:16:25 UTC (rev 3786) @@ -259,6 +259,11 @@ /* + * Remove zeros + */ +INSTANTIATE_ALL(csr_eliminate_zeros) + +/* * Sum duplicate entries. */ INSTANTIATE_ALL(csr_sum_duplicates) Modified: branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.py =================================================================== --- branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.py 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools.py 2008-01-05 08:16:25 UTC (rev 3786) @@ -1055,6 +1055,25 @@ """ return _sparsetools.csr_sort_indices(*args) +def csr_eliminate_zeros(*args): + """ + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, signed char Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned char Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, short Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned short Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, int Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned int Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, long long Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned long long Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, float Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, double Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, long double Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_cfloat_wrapper Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_cdouble_wrapper Ax) + csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax) + """ + return _sparsetools.csr_eliminate_zeros(*args) + def csr_sum_duplicates(*args): """ csr_sum_duplicates(int n_row, int n_col, int Ap, int Aj, signed char Ax) Modified: branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools_wrap.cxx =================================================================== --- branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-01-05 08:16:25 UTC (rev 3786) @@ -77001,6 +77001,1213 @@ } +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + signed char *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_BYTE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (signed char*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned char *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_UBYTE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned char*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + short *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_SHORT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (short*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned short *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_USHORT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned short*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + int *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_INT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (int*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned int *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_UINT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned int*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + long long *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_LONGLONG); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (long long*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned long long *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_ULONGLONG); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned long long*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + float *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_FLOAT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (float*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + double *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_DOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (double*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + long double *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_LONGDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (long double*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_cfloat_wrapper *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CFLOAT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_cfloat_wrapper*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_cdouble_wrapper *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_cdouble_wrapper*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_clongdouble_wrapper *arg5 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *temp3 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *temp5 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOO:csr_eliminate_zeros",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_eliminate_zeros" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_eliminate_zeros" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + temp3 = obj_to_array_no_conversion(obj2,PyArray_INT); + if (!temp3 || !require_contiguous(temp3) || !require_native(temp3)) SWIG_fail; + arg3 = (int*) array_data(temp3); + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (int*) array_data(temp4); + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CLONGDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_clongdouble_wrapper*) array_data(temp5); + } + csr_eliminate_zeros(arg1,arg2,arg3,arg4,arg5); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_eliminate_zeros(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[6]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 5); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_1(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_2(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_3(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_4(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_5(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_6(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_7(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_8(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_9(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_10(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_11(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_12(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_13(self, args); + } + } + } + } + } + } + if (argc == 5) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_eliminate_zeros__SWIG_14(self, args); + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'csr_eliminate_zeros'.\n Possible C/C++ prototypes are:\n"" csr_eliminate_zeros<(int,signed char)>(int const,int const,int [],int [],signed char [])\n"" csr_eliminate_zeros<(int,unsigned char)>(int const,int const,int [],int [],unsigned char [])\n"" csr_eliminate_zeros<(int,short)>(int const,int const,int [],int [],short [])\n"" csr_eliminate_zeros<(int,unsigned short)>(int const,int const,int [],int [],unsigned short [])\n"" csr_eliminate_zeros<(int,int)>(int const,int const,int [],int [],int [])\n"" csr_eliminate_zeros<(int,unsigned int)>(int const,int const,int [],int [],unsigned int [])\n"" csr_eliminate_zeros<(int,long long)>(int const,int const,int [],int [],long long [])\n"" csr_eliminate_zeros<(int,unsigned long long)>(int const,int const,int [],int [],unsigned long long [])\n"" csr_eliminate_zeros<(int,float)>(int const,int const,int [],int [],float [])\n"" csr_eliminate_zeros<(int,double)>(int const,int const,int [],int [],double [])\n"" csr_eliminate_zeros<(int,long double)>(int const,int const,int [],int [],long double [])\n"" csr_eliminate_zeros<(int,npy_cfloat_wrapper)>(int const,int const,int [],int [],npy_cfloat_wrapper [])\n"" csr_eliminate_zeros<(int,npy_cdouble_wrapper)>(int const,int const,int [],int [],npy_cdouble_wrapper [])\n"" csr_eliminate_zeros<(int,npy_clongdouble_wrapper)>(int const,int const,int [],int [],npy_clongdouble_wrapper [])\n"); + return NULL; +} + + SWIGINTERN PyObject *_wrap_csr_sum_duplicates__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int arg1 ; @@ -82221,6 +83428,22 @@ "csr_sort_indices(int n_row, int Ap, int Aj, npy_cdouble_wrapper Ax)\n" "csr_sort_indices(int n_row, int Ap, int Aj, npy_clongdouble_wrapper Ax)\n" ""}, + { (char *)"csr_eliminate_zeros", _wrap_csr_eliminate_zeros, METH_VARARGS, (char *)"\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, signed char Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned char Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, short Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned short Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, int Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned int Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, long long Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, unsigned long long Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, float Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, double Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, long double Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_cfloat_wrapper Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_cdouble_wrapper Ax)\n" + "csr_eliminate_zeros(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax)\n" + ""}, { (char *)"csr_sum_duplicates", _wrap_csr_sum_duplicates, METH_VARARGS, (char *)"\n" "csr_sum_duplicates(int n_row, int n_col, int Ap, int Aj, signed char Ax)\n" "csr_sum_duplicates(int n_row, int n_col, int Ap, int Aj, unsigned char Ax)\n" Modified: branches/testing_cleanup/scipy/sparse/tests/test_base.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_base.py 2008-01-05 07:04:22 UTC (rev 3785) +++ branches/testing_cleanup/scipy/sparse/tests/test_base.py 2008-01-05 08:16:25 UTC (rev 3786) @@ -15,7 +15,7 @@ import numpy from numpy import arange, zeros, array, dot, ones, matrix, asmatrix, \ - asarray, vstack, ndarray, kron + asarray, vstack, ndarray, kron, transpose import random from scipy.testing import * @@ -812,6 +812,17 @@ assert_array_equal(asp.indices,[1, 2, 7, 4, 5]) assert_array_equal(asp.todense(),bsp.todense()) + def test_eliminate_zeros(self): + data = array( [1, 0, 0, 0, 2, 0, 3, 0] ) + indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) + indptr = array( [0, 3, 8] ) + asp = csr_matrix( (data, indices, indptr), shape=(2,10) ) + bsp = asp.copy() + asp.eliminate_zeros( ) + assert_array_equal(asp.nnz, 3) + assert_array_equal(asp.data,[1, 2, 3]) + assert_array_equal(asp.todense(),bsp.todense()) + def test_get_submatrix(self): a = csr_matrix( array([[1,2,3,4],[1,2,3,5],[0,2,0,1]]) ) i0 = slice( 0, 2 ) @@ -875,6 +886,17 @@ csc = csc_matrix((data, indices, indptr)) assert_array_equal(csc.shape,(6,3)) + def test_eliminate_zeros(self): + data = array( [1, 0, 0, 0, 2, 0, 3, 0] ) + indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) + indptr = array( [0, 3, 8] ) + asp = csc_matrix( (data, indices, indptr), shape=(10,2) ) + bsp = asp.copy() + asp.eliminate_zeros( ) + assert_array_equal(asp.nnz, 3) + assert_array_equal(asp.data,[1, 2, 3]) + assert_array_equal(asp.todense(),bsp.todense()) + def test_sort_indices(self): data = arange( 5 ) row = array( [7, 2, 1, 5, 4] ) @@ -1260,6 +1282,16 @@ A = kron( [[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]] ) assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A) + def check_eliminate_zeros(self): + data = kron([1, 0, 0, 0, 2, 0, 3, 0], [[1,1],[1,1]]).T + data = data.reshape(-1,2,2) + indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) + indptr = array( [0, 3, 8] ) + asp = bsr_matrix( (data, indices, indptr), shape=(4,20) ) + bsp = asp.copy() + asp.eliminate_zeros() + assert_array_equal(asp.nnz, 3*4) + assert_array_equal(asp.todense(),bsp.todense()) if __name__ == "__main__": From scipy-svn at scipy.org Sun Jan 6 20:42:25 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 6 Jan 2008 19:42:25 -0600 (CST) Subject: [Scipy-svn] r3787 - trunk/scipy/sparse Message-ID: <20080107014225.49A8639C098@new.scipy.org> Author: wnbell Date: 2008-01-06 19:42:20 -0600 (Sun, 06 Jan 2008) New Revision: 3787 Modified: trunk/scipy/sparse/compressed.py Log: fixed typo Modified: trunk/scipy/sparse/compressed.py =================================================================== --- trunk/scipy/sparse/compressed.py 2008-01-05 08:16:25 UTC (rev 3786) +++ trunk/scipy/sparse/compressed.py 2008-01-07 01:42:20 UTC (rev 3787) @@ -590,7 +590,7 @@ """ #first check to see if result was cached - if not hasattr(self,'_has_sorted_indices'): + if not hasattr(self,'__has_sorted_indices'): fn = sparsetools.csr_has_sorted_indices self.__has_sorted_indices = \ fn( len(self.indptr) - 1, self.indptr, self.indices) From scipy-svn at scipy.org Mon Jan 7 02:20:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 01:20:27 -0600 (CST) Subject: [Scipy-svn] r3788 - branches Message-ID: <20080107072027.9E33139C0E0@new.scipy.org> Author: jarrod.millman Date: 2008-01-07 01:20:24 -0600 (Mon, 07 Jan 2008) New Revision: 3788 Removed: branches/weave_cleanup/ Log: changes merged in r3736 From scipy-svn at scipy.org Mon Jan 7 02:21:21 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 01:21:21 -0600 (CST) Subject: [Scipy-svn] r3789 - branches Message-ID: <20080107072121.CE5D639C0E0@new.scipy.org> Author: jarrod.millman Date: 2008-01-07 01:21:19 -0600 (Mon, 07 Jan 2008) New Revision: 3789 Removed: branches/ndimage_segmenter/ Log: code already in trunk From scipy-svn at scipy.org Mon Jan 7 02:22:21 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 01:22:21 -0600 (CST) Subject: [Scipy-svn] r3790 - branches Message-ID: <20080107072221.692E839C0E0@new.scipy.org> Author: jarrod.millman Date: 2008-01-07 01:22:19 -0600 (Mon, 07 Jan 2008) New Revision: 3790 Removed: branches/kiva_window_branch/ Log: old code From scipy-svn at scipy.org Mon Jan 7 02:23:25 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 01:23:25 -0600 (CST) Subject: [Scipy-svn] r3791 - branches Message-ID: <20080107072325.0154639C334@new.scipy.org> Author: jarrod.millman Date: 2008-01-07 01:23:23 -0600 (Mon, 07 Jan 2008) New Revision: 3791 Removed: branches/enthought/ Log: old code From scipy-svn at scipy.org Mon Jan 7 14:33:08 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 13:33:08 -0600 (CST) Subject: [Scipy-svn] r3792 - trunk/scipy/sandbox/timeseries Message-ID: <20080107193308.45C1C39C112@new.scipy.org> Author: dhuard Date: 2008-01-07 13:33:00 -0600 (Mon, 07 Jan 2008) New Revision: 3792 Modified: trunk/scipy/sandbox/timeseries/trecords.py Log: Fixed an error in docstring of fromtextfile (datescol instead of dates_column). Modified: trunk/scipy/sandbox/timeseries/trecords.py =================================================================== --- trunk/scipy/sandbox/timeseries/trecords.py 2008-01-07 07:23:23 UTC (rev 3791) +++ trunk/scipy/sandbox/timeseries/trecords.py 2008-01-07 19:33:00 UTC (rev 3792) @@ -427,7 +427,7 @@ Alphanumeric character used to mark the start of a comment. - `missingchar` : String *['']* String indicating missing data, and used to create the masks. - - `datescol` : Integer *[None]* + - `dates_column` : Integer *[None]* Position of the columns storing dates. If None, a position will be estimated from the variable names. - `varnames` : Sequence *[None]* From scipy-svn at scipy.org Mon Jan 7 16:41:23 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 15:41:23 -0600 (CST) Subject: [Scipy-svn] r3793 - trunk/scipy/sandbox/multigrid Message-ID: <20080107214123.D489FC7C062@new.scipy.org> Author: wnbell Date: 2008-01-07 15:41:21 -0600 (Mon, 07 Jan 2008) New Revision: 3793 Modified: trunk/scipy/sandbox/multigrid/simple_test.py Log: modified multigrid test Modified: trunk/scipy/sandbox/multigrid/simple_test.py =================================================================== --- trunk/scipy/sandbox/multigrid/simple_test.py 2008-01-07 19:33:00 UTC (rev 3792) +++ trunk/scipy/sandbox/multigrid/simple_test.py 2008-01-07 21:41:21 UTC (rev 3793) @@ -1,8 +1,17 @@ -from multilevel import * from scipy import * +from scipy.sandbox.multigrid.sa import * +from scipy.sandbox.multigrid import * +from scipy.sandbox.multigrid.utils import * +from time import clock -A = poisson_problem2D(200) -rs_solver = ruge_stuben_solver(A) +A = poisson_problem2D(500) + +start = clock() +sa = smoothed_aggregation_solver(A) +print "constructed solver in %s seconds" % (clock() - start) + b = rand(A.shape[0]) -x,residuals = rs_solver.solve(b,return_residuals=True) +start = clock() +x,residuals = sa.solve(b,return_residuals=True) +print "solved in %s seconds" % (clock() - start) print 'residuals',residuals From scipy-svn at scipy.org Mon Jan 7 19:00:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 18:00:16 -0600 (CST) Subject: [Scipy-svn] r3794 - in branches/testing_cleanup/scipy: io io/tests testing Message-ID: <20080108000016.EF17C39C190@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-07 18:00:03 -0600 (Mon, 07 Jan 2008) New Revision: 3794 Added: branches/testing_cleanup/scipy/testing/nosetester.py branches/testing_cleanup/scipy/testing/nulltester.py branches/testing_cleanup/scipy/testing/pkgtester.py Removed: branches/testing_cleanup/scipy/io/tests/test_datasource.py Modified: branches/testing_cleanup/scipy/io/__init__.py branches/testing_cleanup/scipy/testing/__init__.py Log: First pass at module level nose tests Modified: branches/testing_cleanup/scipy/io/__init__.py =================================================================== --- branches/testing_cleanup/scipy/io/__init__.py 2008-01-07 21:41:21 UTC (rev 3793) +++ branches/testing_cleanup/scipy/io/__init__.py 2008-01-08 00:00:03 UTC (rev 3794) @@ -84,5 +84,6 @@ from mmio import mminfo, mmread, mmwrite __all__ = filter(lambda s:not s.startswith('_'),dir()) -from scipy.testing.moduletest import test_func -test = test_func +from scipy.testing.pkgtester import Tester +t = Tester() +test = Tester().test Deleted: branches/testing_cleanup/scipy/io/tests/test_datasource.py =================================================================== --- branches/testing_cleanup/scipy/io/tests/test_datasource.py 2008-01-07 21:41:21 UTC (rev 3793) +++ branches/testing_cleanup/scipy/io/tests/test_datasource.py 2008-01-08 00:00:03 UTC (rev 3794) @@ -1,251 +0,0 @@ -import os -import sys -import struct -import bz2 -import gzip -from tempfile import mkdtemp, mkstemp, NamedTemporaryFile -from shutil import rmtree -from urlparse import urlparse - -from scipy.testing import * - -# HACK: import the src datasource -# Until datasource is robust enough to include in scipy.io package -sys.path.insert(0, os.path.abspath('..')) -import scipy.io.datasource as datasource -del sys.path[0] - -def urlopen_stub(url, data=None): - '''Stub to replace urlopen for testing.''' - if url == valid_httpurl(): - tmpfile = NamedTemporaryFile(prefix='urltmp_') - return tmpfile - else: - raise datasource.URLError('Name or service not known') - -# Rebind urlopen during testing. For a 'real' test, uncomment the rebinding -# below. -datasource.urlopen = urlopen_stub - -# A valid website for more robust testing -http_path = 'http://www.google.com/' -http_file = 'index.html' - -http_fakepath = 'http://fake.abc.web/site/' -http_fakefile = 'fake.txt' - -magic_line = 'three is the magic number' - - -# Utility functions used by many TestCases -def valid_textfile(filedir): - # Generate and return a valid temporary file. - fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir, text=True) - os.close(fd) - return path - -def invalid_textfile(filedir): - # Generate and return an invalid filename. - fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir) - os.close(fd) - os.remove(path) - return path - -def valid_httpurl(): - return http_path+http_file - -def invalid_httpurl(): - return http_fakepath+http_fakefile - -def valid_baseurl(): - return http_path - -def invalid_baseurl(): - return http_fakepath - -def valid_httpfile(): - return http_file - -def invalid_httpfile(): - return http_fakefile - -class TestDataSourceOpen(TestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.ds = datasource.DataSource(self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.ds - - def test_ValidHTTP(self): - assert self.ds.open(valid_httpurl()) - - def test_InvalidHTTP(self): - self.assertRaises(IOError, self.ds.open, invalid_httpurl()) - - def test_ValidFile(self): - local_file = valid_textfile(self.tmpdir) - assert self.ds.open(local_file) - - def test_InvalidFile(self): - invalid_file = invalid_textfile(self.tmpdir) - self.assertRaises(IOError, self.ds.open, invalid_file) - - def test_ValidGzipFile(self): - # Test datasource's internal file_opener for Gzip files. - filepath = os.path.join(self.tmpdir, 'foobar.txt.gz') - fp = gzip.open(filepath, 'w') - fp.write(magic_line) - fp.close() - fp = self.ds.open(filepath) - result = fp.readline() - fp.close() - self.assertEqual(magic_line, result) - - def test_ValidBz2File(self): - # Test datasource's internal file_opener for BZip2 files. - filepath = os.path.join(self.tmpdir, 'foobar.txt.bz2') - fp = bz2.BZ2File(filepath, 'w') - fp.write(magic_line) - fp.close() - fp = self.ds.open(filepath) - result = fp.readline() - fp.close() - self.assertEqual(magic_line, result) - - -class TestDataSourceExists(TestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.ds = datasource.DataSource(self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.ds - - def test_ValidHTTP(self): - assert self.ds.exists(valid_httpurl()) - - def test_InvalidHTTP(self): - self.assertEqual(self.ds.exists(invalid_httpurl()), False) - - def test_ValidFile(self): - # Test valid file in destpath - tmpfile = valid_textfile(self.tmpdir) - assert self.ds.exists(tmpfile) - # Test valid local file not in destpath - localdir = mkdtemp() - tmpfile = valid_textfile(localdir) - assert self.ds.exists(tmpfile) - rmtree(localdir) - - def test_InvalidFile(self): - tmpfile = invalid_textfile(self.tmpdir) - self.assertEqual(self.ds.exists(tmpfile), False) - - -class TestDataSourceAbspath(TestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.ds = datasource.DataSource(self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.ds - - def test_ValidHTTP(self): - scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl()) - local_path = os.path.join(self.tmpdir, netloc, upath.strip(os.sep)) - self.assertEqual(local_path, self.ds.abspath(valid_httpurl())) - - def test_ValidFile(self): - tmpfile = valid_textfile(self.tmpdir) - tmpfilename = os.path.split(tmpfile)[-1] - # Test with filename only - self.assertEqual(tmpfile, self.ds.abspath(os.path.split(tmpfile)[-1])) - # Test filename with complete path - self.assertEqual(tmpfile, self.ds.abspath(tmpfile)) - - def test_InvalidHTTP(self): - scheme, netloc, upath, pms, qry, frg = urlparse(invalid_httpurl()) - invalidhttp = os.path.join(self.tmpdir, netloc, upath.strip(os.sep)) - self.assertNotEqual(invalidhttp, self.ds.abspath(valid_httpurl())) - - def test_InvalidFile(self): - invalidfile = valid_textfile(self.tmpdir) - tmpfile = valid_textfile(self.tmpdir) - tmpfilename = os.path.split(tmpfile)[-1] - # Test with filename only - self.assertNotEqual(invalidfile, self.ds.abspath(tmpfilename)) - # Test filename with complete path - self.assertNotEqual(invalidfile, self.ds.abspath(tmpfile)) - - -class TestRespositoryAbspath(TestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.repos = datasource.Repository(valid_baseurl(), self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.repos - - def test_ValidHTTP(self): - scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl()) - local_path = os.path.join(self.repos._destpath, netloc, \ - upath.strip(os.sep)) - filepath = self.repos.abspath(valid_httpfile()) - self.assertEqual(local_path, filepath) - - -class TestRepositoryExists(TestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.repos = datasource.Repository(valid_baseurl(), self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.repos - - def test_ValidFile(self): - # Create local temp file - tmpfile = valid_textfile(self.tmpdir) - assert self.repos.exists(tmpfile) - - def test_InvalidFile(self): - tmpfile = invalid_textfile(self.tmpdir) - self.assertEqual(self.repos.exists(tmpfile), False) - - def test_RemoveHTTPFile(self): - assert self.repos.exists(valid_httpurl()) - - def test_CachedHTTPFile(self): - localfile = valid_httpurl() - # Create a locally cached temp file with an URL based - # directory structure. This is similar to what Repository.open - # would do. - scheme, netloc, upath, pms, qry, frg = urlparse(localfile) - local_path = os.path.join(self.repos._destpath, netloc) - os.mkdir(local_path, 0700) - tmpfile = valid_textfile(local_path) - assert self.repos.exists(tmpfile) - - -class TestOpenFunc(TestCase): - def setUp(self): - self.tmpdir = mkdtemp() - - def tearDown(self): - rmtree(self.tmpdir) - - def test_DataSourceOpen(self): - local_file = valid_textfile(self.tmpdir) - # Test case where destpath is passed in - assert datasource.open(local_file, destpath=self.tmpdir) - # Test case where default destpath is used - assert datasource.open(local_file) - - -if __name__ == "__main__": - unittest.main() Modified: branches/testing_cleanup/scipy/testing/__init__.py =================================================================== --- branches/testing_cleanup/scipy/testing/__init__.py 2008-01-07 21:41:21 UTC (rev 3793) +++ branches/testing_cleanup/scipy/testing/__init__.py 2008-01-08 00:00:03 UTC (rev 3794) @@ -8,7 +8,11 @@ import unittest from unittest import TestCase -import nose +try: + import nose +except ImportError: + print 'Need nose testing framework installed for scipy tests' + raise import decorators as dec from numpy.testing.utils import * Added: branches/testing_cleanup/scipy/testing/nosetester.py =================================================================== --- branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-07 21:41:21 UTC (rev 3793) +++ branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-08 00:00:03 UTC (rev 3794) @@ -0,0 +1,55 @@ +''' Nose tester object ''' +import os +import sys + +import nose + +class NoseTester(object): + """ Scipy nose tests site manager. + + Usage: NoseTester().test() + + is package path, package name or its module object. + """ + def __init__(self, package=None): + if package is None: + f = sys._getframe(1) + package = f.f_locals.get('__file__',f.f_globals.get('__file__',None)) + assert package is not None + self.package_path = os.path.dirname(package) + else: + self._process_package(package) + + def _process_package(self, package): + ''' Package can be module, path, or package name ''' + try: + pfile = package.__file__ + except AttributeError: + pass + else: + self.package_path = os.path.dirname(pfile) + return + if os.path.isabs(package): + self.package_path = package + return + if package.find(os.path.sep) == -1: + # Try scipy package name + import scipy + scipy.pkgload(package) + try: + module = getattr(scipy, package) + except AttributeError: + pass + else: + self.package_path = os.path.dirname(module.__file__) + return + # Default to relative path + self.package_path = os.path.abspath(package) + return + + def test(self, labels=None, *args, **kwargs): + if labels is None: + labels = [] + argv = ['', self.package_path] + nose.run(argv=argv) + Added: branches/testing_cleanup/scipy/testing/nulltester.py =================================================================== --- branches/testing_cleanup/scipy/testing/nulltester.py 2008-01-07 21:41:21 UTC (rev 3793) +++ branches/testing_cleanup/scipy/testing/nulltester.py 2008-01-08 00:00:03 UTC (rev 3794) @@ -0,0 +1,8 @@ +''' Null tester (when nose not importable ''' + +class NullTester(object): + def __init__(self, *args, **kwargs): + pass + def test(self, labels=None, *args, **kwargs): + raise ImportError, 'Need nose testing on path for tests' + Added: branches/testing_cleanup/scipy/testing/pkgtester.py =================================================================== --- branches/testing_cleanup/scipy/testing/pkgtester.py 2008-01-07 21:41:21 UTC (rev 3793) +++ branches/testing_cleanup/scipy/testing/pkgtester.py 2008-01-08 00:00:03 UTC (rev 3794) @@ -0,0 +1,7 @@ +''' Define test function for scipy package ''' +try: + import nose + from scipy.testing.nosetester import NoseTester as Tester +except ImportError: + from scipy.testing.nulltester import NullTester as Tester + From scipy-svn at scipy.org Mon Jan 7 19:11:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 18:11:16 -0600 (CST) Subject: [Scipy-svn] r3795 - in branches/testing_cleanup: . scipy/sandbox/multigrid scipy/sandbox/timeseries scipy/sparse Message-ID: <20080108001116.7D4CF39C1F2@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-07 18:11:08 -0600 (Mon, 07 Jan 2008) New Revision: 3795 Modified: branches/testing_cleanup/ branches/testing_cleanup/scipy/sandbox/multigrid/simple_test.py branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py branches/testing_cleanup/scipy/sparse/compressed.py Log: Merged revisions 3787,3792-3793 via svnmerge from http://svn.scipy.org/svn/scipy/trunk ........ r3787 | wnbell | 2008-01-06 17:42:20 -0800 (Sun, 06 Jan 2008) | 2 lines fixed typo ........ r3792 | dhuard | 2008-01-07 11:33:00 -0800 (Mon, 07 Jan 2008) | 1 line Fixed an error in docstring of fromtextfile (datescol instead of dates_column). ........ r3793 | wnbell | 2008-01-07 13:41:21 -0800 (Mon, 07 Jan 2008) | 2 lines modified multigrid test ........ Property changes on: branches/testing_cleanup ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3785 + /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3794 Modified: branches/testing_cleanup/scipy/sandbox/multigrid/simple_test.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/simple_test.py 2008-01-08 00:00:03 UTC (rev 3794) +++ branches/testing_cleanup/scipy/sandbox/multigrid/simple_test.py 2008-01-08 00:11:08 UTC (rev 3795) @@ -1,8 +1,17 @@ -from multilevel import * from scipy import * +from scipy.sandbox.multigrid.sa import * +from scipy.sandbox.multigrid import * +from scipy.sandbox.multigrid.utils import * +from time import clock -A = poisson_problem2D(200) -rs_solver = ruge_stuben_solver(A) +A = poisson_problem2D(500) + +start = clock() +sa = smoothed_aggregation_solver(A) +print "constructed solver in %s seconds" % (clock() - start) + b = rand(A.shape[0]) -x,residuals = rs_solver.solve(b,return_residuals=True) +start = clock() +x,residuals = sa.solve(b,return_residuals=True) +print "solved in %s seconds" % (clock() - start) print 'residuals',residuals Modified: branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py 2008-01-08 00:00:03 UTC (rev 3794) +++ branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py 2008-01-08 00:11:08 UTC (rev 3795) @@ -28,13 +28,15 @@ import scipy.sandbox.maskedarray as MA #MaskedArray = MA.MaskedArray -from scipy.sandbox.maskedarray.core import MaskedArray, MAError, default_fill_value, \ - masked_print_option, masked, nomask, getmask, getmaskarray, make_mask,\ - make_mask_none, mask_or, masked_array, filled +from scipy.sandbox.maskedarray.core import MaskedArray, MAError, \ + default_fill_value, masked_print_option, masked, nomask, \ + getmask, getmaskarray, make_mask,\ + make_mask_none, mask_or, masked_array, filled import scipy.sandbox.maskedarray.mrecords as MR -from scipy.sandbox.maskedarray.mrecords import _checknames, _guessvartypes, openfile,\ - MaskedRecords, fromrecords as mrecfromrecords +from scipy.sandbox.maskedarray.mrecords import _checknames, \ + _guessvartypes, openfile, MaskedRecords, \ + fromrecords as mrecfromrecords from tseries import TimeSeries, time_series, _getdatalength from dates import Date, DateArray, date_array @@ -425,7 +427,7 @@ Alphanumeric character used to mark the start of a comment. - `missingchar` : String *['']* String indicating missing data, and used to create the masks. - - `datescol` : Integer *[None]* + - `dates_column` : Integer *[None]* Position of the columns storing dates. If None, a position will be estimated from the variable names. - `varnames` : Sequence *[None]* Modified: branches/testing_cleanup/scipy/sparse/compressed.py =================================================================== --- branches/testing_cleanup/scipy/sparse/compressed.py 2008-01-08 00:00:03 UTC (rev 3794) +++ branches/testing_cleanup/scipy/sparse/compressed.py 2008-01-08 00:11:08 UTC (rev 3795) @@ -588,7 +588,7 @@ """ #first check to see if result was cached - if not hasattr(self,'_has_sorted_indices'): + if not hasattr(self,'__has_sorted_indices'): fn = sparsetools.csr_has_sorted_indices self.__has_sorted_indices = \ fn( len(self.indptr) - 1, self.indptr, self.indices) From scipy-svn at scipy.org Mon Jan 7 20:26:56 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 19:26:56 -0600 (CST) Subject: [Scipy-svn] r3796 - in branches/testing_cleanup/scipy: cluster fftpack integrate interpolate io lib lib/blas lib/lapack linalg linsolve linsolve/umfpack maxentropy misc odr optimize sandbox/cdavid sandbox/lobpcg sandbox/multigrid sandbox/rbf sandbox/spline signal sparse special stats stats/models testing weave Message-ID: <20080108012656.BF26139C33A@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-07 19:26:20 -0600 (Mon, 07 Jan 2008) New Revision: 3796 Modified: branches/testing_cleanup/scipy/cluster/__init__.py branches/testing_cleanup/scipy/fftpack/__init__.py branches/testing_cleanup/scipy/integrate/__init__.py branches/testing_cleanup/scipy/interpolate/__init__.py branches/testing_cleanup/scipy/io/__init__.py branches/testing_cleanup/scipy/lib/__init__.py branches/testing_cleanup/scipy/lib/blas/__init__.py branches/testing_cleanup/scipy/lib/lapack/__init__.py branches/testing_cleanup/scipy/linalg/__init__.py branches/testing_cleanup/scipy/linsolve/__init__.py branches/testing_cleanup/scipy/linsolve/umfpack/__init__.py branches/testing_cleanup/scipy/maxentropy/__init__.py branches/testing_cleanup/scipy/misc/__init__.py branches/testing_cleanup/scipy/odr/__init__.py branches/testing_cleanup/scipy/optimize/__init__.py branches/testing_cleanup/scipy/sandbox/cdavid/__init__.py branches/testing_cleanup/scipy/sandbox/lobpcg/__init__.py branches/testing_cleanup/scipy/sandbox/multigrid/__init__.py branches/testing_cleanup/scipy/sandbox/rbf/__init__.py branches/testing_cleanup/scipy/sandbox/spline/__init__.py branches/testing_cleanup/scipy/signal/__init__.py branches/testing_cleanup/scipy/sparse/__init__.py branches/testing_cleanup/scipy/special/__init__.py branches/testing_cleanup/scipy/stats/__init__.py branches/testing_cleanup/scipy/stats/models/__init__.py branches/testing_cleanup/scipy/testing/decorators.py branches/testing_cleanup/scipy/testing/nosetester.py branches/testing_cleanup/scipy/weave/__init__.py Log: Module level tests and API started Modified: branches/testing_cleanup/scipy/cluster/__init__.py =================================================================== --- branches/testing_cleanup/scipy/cluster/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/cluster/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -7,5 +7,5 @@ __all__ = ['vq'] import vq -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/fftpack/__init__.py =================================================================== --- branches/testing_cleanup/scipy/fftpack/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/fftpack/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -17,5 +17,5 @@ del k, register_func -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/integrate/__init__.py =================================================================== --- branches/testing_cleanup/scipy/integrate/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/integrate/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -12,5 +12,5 @@ from ode import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/interpolate/__init__.py =================================================================== --- branches/testing_cleanup/scipy/interpolate/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/interpolate/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -11,5 +11,5 @@ from fitpack2 import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/io/__init__.py =================================================================== --- branches/testing_cleanup/scipy/io/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/io/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -85,5 +85,4 @@ __all__ = filter(lambda s:not s.startswith('_'),dir()) from scipy.testing.pkgtester import Tester -t = Tester() test = Tester().test Modified: branches/testing_cleanup/scipy/lib/__init__.py =================================================================== --- branches/testing_cleanup/scipy/lib/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/lib/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -1,5 +1,5 @@ from info import __doc__, __all__ -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/lib/blas/__init__.py =================================================================== --- branches/testing_cleanup/scipy/lib/blas/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/lib/blas/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -58,5 +58,5 @@ funcs.append(func) return tuple(funcs) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/lib/lapack/__init__.py =================================================================== --- branches/testing_cleanup/scipy/lib/lapack/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/lib/lapack/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -90,5 +90,5 @@ func_code = %(func_name)s.func_code ''' -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/linalg/__init__.py =================================================================== --- branches/testing_cleanup/scipy/linalg/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/linalg/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -28,5 +28,5 @@ del k, register_func -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/linsolve/__init__.py =================================================================== --- branches/testing_cleanup/scipy/linsolve/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/linsolve/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -9,5 +9,5 @@ from linsolve import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/linsolve/umfpack/__init__.py =================================================================== --- branches/testing_cleanup/scipy/linsolve/umfpack/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/linsolve/umfpack/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -3,5 +3,5 @@ from umfpack import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/maxentropy/__init__.py =================================================================== --- branches/testing_cleanup/scipy/maxentropy/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/maxentropy/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -8,5 +8,5 @@ from info import __doc__ from maxentropy import * -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/misc/__init__.py =================================================================== --- branches/testing_cleanup/scipy/misc/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/misc/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -20,5 +20,5 @@ __all__ += common.__all__ -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/odr/__init__.py =================================================================== --- branches/testing_cleanup/scipy/odr/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/odr/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -21,6 +21,6 @@ __all__ = ['odr', 'odr_error', 'odr_stop', 'Data', 'RealData', 'Model', 'Output', 'ODR', 'odrpack'] -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test #### EOF ####################################################################### Modified: branches/testing_cleanup/scipy/optimize/__init__.py =================================================================== --- branches/testing_cleanup/scipy/optimize/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/optimize/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -16,5 +16,5 @@ from slsqp import fmin_slsqp __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/sandbox/cdavid/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/cdavid/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/sandbox/cdavid/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -5,5 +5,5 @@ from autocorr import autocorr_oneside_nofft, autocorr_fft from segmentaxis import segment_axis -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/sandbox/lobpcg/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/lobpcg/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/sandbox/lobpcg/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -7,5 +7,5 @@ from lobpcg import * -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/sandbox/multigrid/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/sandbox/multigrid/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -5,5 +5,5 @@ from multilevel import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/sandbox/rbf/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/rbf/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/sandbox/rbf/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -7,5 +7,5 @@ from rbf import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/sandbox/spline/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/spline/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/sandbox/spline/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -10,5 +10,5 @@ from spline import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/signal/__init__.py =================================================================== --- branches/testing_cleanup/scipy/signal/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/signal/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -13,5 +13,5 @@ from wavelets import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/sparse/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sparse/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/sparse/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -15,5 +15,5 @@ from spfuncs import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/special/__init__.py =================================================================== --- branches/testing_cleanup/scipy/special/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/special/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -19,5 +19,5 @@ register_func('i0',i0) del register_func -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/stats/__init__.py =================================================================== --- branches/testing_cleanup/scipy/stats/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/stats/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -11,5 +11,5 @@ from kde import gaussian_kde __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/stats/models/__init__.py =================================================================== --- branches/testing_cleanup/scipy/stats/models/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/stats/models/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -16,5 +16,5 @@ __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/testing/decorators.py =================================================================== --- branches/testing_cleanup/scipy/testing/decorators.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/testing/decorators.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -1,5 +1,8 @@ """Decorators for labeling test objects.""" +''' String expression which is true for all undecorated tests ''' +undecorated_def = 'not slow' + def slow(t): """Labels a test as 'slow'. Modified: branches/testing_cleanup/scipy/testing/nosetester.py =================================================================== --- branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -4,6 +4,8 @@ import nose +from scipy.testing.decorators import undecorated_def + class NoseTester(object): """ Scipy nose tests site manager. @@ -14,7 +16,8 @@ def __init__(self, package=None): if package is None: f = sys._getframe(1) - package = f.f_locals.get('__file__',f.f_globals.get('__file__',None)) + package = f.f_locals.get('__file__', + f.f_globals.get('__file__',None)) assert package is not None self.package_path = os.path.dirname(package) else: @@ -47,9 +50,14 @@ self.package_path = os.path.abspath(package) return - def test(self, labels=None, *args, **kwargs): + def test(self, labels=None, verbose=0, extra_argv=None): if labels is None: - labels = [] - argv = ['', self.package_path] + labels = undecorated_def + argv = ['', self.package_path, '-s'] + if labels not in ('', 'all'): + argv += ['-A', labels] + argv += ['--verbosity', str(verbose)] + if extra_argv is not None: + argv+= extra_argv nose.run(argv=argv) Modified: branches/testing_cleanup/scipy/weave/__init__.py =================================================================== --- branches/testing_cleanup/scipy/weave/__init__.py 2008-01-08 00:11:08 UTC (rev 3795) +++ branches/testing_cleanup/scipy/weave/__init__.py 2008-01-08 01:26:20 UTC (rev 3796) @@ -18,5 +18,5 @@ except: pass -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test From scipy-svn at scipy.org Mon Jan 7 23:13:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 7 Jan 2008 22:13:02 -0600 (CST) Subject: [Scipy-svn] r3797 - trunk/scipy/stats Message-ID: <20080108041302.6672A39C09C@new.scipy.org> Author: dhuard Date: 2008-01-07 22:12:38 -0600 (Mon, 07 Jan 2008) New Revision: 3797 Modified: trunk/scipy/stats/distributions.py Log: Fixed ticket 422 related to the generic computation of moments. Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-01-08 01:26:20 UTC (rev 3796) +++ trunk/scipy/stats/distributions.py 2008-01-08 04:12:38 UTC (rev 3797) @@ -303,15 +303,17 @@ self.vecentropy = sgf(self._entropy,otypes='d') self.veccdf = sgf(self._cdf_single_call,otypes='d') self.expandarr = 1 - if momtype == 0: - self.generic_moment = sgf(self._mom0_sc,otypes='d') - else: - self.generic_moment = sgf(self._mom1_sc,otypes='d') cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2) + if momtype == 0: + self.generic_moment = sgf(self._mom0_sc,otypes='d') + else: + self.generic_moment = sgf(self._mom1_sc,otypes='d') + self.generic_moment.nin = self.numargs+1 # Because of the *args argument + # of _mom0_sc, vectorize cannot count the number of arguments correctly. if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " From scipy-svn at scipy.org Tue Jan 8 01:19:24 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 00:19:24 -0600 (CST) Subject: [Scipy-svn] r3798 - in trunk/scipy/sandbox/multigrid: . multigridtools tests Message-ID: <20080108061924.6360F39C2F0@new.scipy.org> Author: wnbell Date: 2008-01-08 00:19:19 -0600 (Tue, 08 Jan 2008) New Revision: 3798 Modified: trunk/scipy/sandbox/multigrid/multigridtools/multigridtools.i trunk/scipy/sandbox/multigrid/multigridtools/multigridtools.py trunk/scipy/sandbox/multigrid/multigridtools/multigridtools_wrap.cxx trunk/scipy/sandbox/multigrid/multigridtools/relaxation.h trunk/scipy/sandbox/multigrid/relaxation.py trunk/scipy/sandbox/multigrid/tests/test_relaxation.py Log: added BSR gauss seidel method Modified: trunk/scipy/sandbox/multigrid/multigridtools/multigridtools.i =================================================================== --- trunk/scipy/sandbox/multigrid/multigridtools/multigridtools.i 2008-01-08 04:12:38 UTC (rev 3797) +++ trunk/scipy/sandbox/multigrid/multigridtools/multigridtools.i 2008-01-08 06:19:19 UTC (rev 3798) @@ -170,6 +170,7 @@ INSTANTIATE_BOTH(rs_strong_connections) INSTANTIATE_BOTH(rs_interpolation) INSTANTIATE_BOTH(sa_strong_connections) +INSTANTIATE_BOTH(block_gauss_seidel) INSTANTIATE_BOTH(gauss_seidel) INSTANTIATE_BOTH(jacobi) Modified: trunk/scipy/sandbox/multigrid/multigridtools/multigridtools.py =================================================================== --- trunk/scipy/sandbox/multigrid/multigridtools/multigridtools.py 2008-01-08 04:12:38 UTC (rev 3797) +++ trunk/scipy/sandbox/multigrid/multigridtools/multigridtools.py 2008-01-08 06:19:19 UTC (rev 3798) @@ -90,23 +90,32 @@ """ return _multigridtools.sa_strong_connections(*args) +def block_gauss_seidel(*args): + """ + block_gauss_seidel(int Ap, int Aj, float Ax, float x, float b, int row_start, + int row_stop, int row_step, int blocksize) + block_gauss_seidel(int Ap, int Aj, double Ax, double x, double b, int row_start, + int row_stop, int row_step, int blocksize) + """ + return _multigridtools.block_gauss_seidel(*args) + def gauss_seidel(*args): """ - gauss_seidel(int n_row, int Ap, int Aj, float Ax, float x, float b, - int row_start, int row_stop, int row_step) - gauss_seidel(int n_row, int Ap, int Aj, double Ax, double x, double b, - int row_start, int row_stop, int row_step) + gauss_seidel(int Ap, int Aj, float Ax, float x, float b, int row_start, + int row_stop, int row_step) + gauss_seidel(int Ap, int Aj, double Ax, double x, double b, int row_start, + int row_stop, int row_step) """ return _multigridtools.gauss_seidel(*args) def jacobi(*args): """ - jacobi(int n_row, int Ap, int Aj, float Ax, float x, float b, - float temp, int row_start, int row_stop, - int row_step, float omega) - jacobi(int n_row, int Ap, int Aj, double Ax, double x, double b, - double temp, int row_start, int row_stop, - int row_step, double omega) + jacobi(int Ap, int Aj, float Ax, float x, float b, float temp, + int row_start, int row_stop, int row_step, + float omega) + jacobi(int Ap, int Aj, double Ax, double x, double b, double temp, + int row_start, int row_stop, int row_step, + double omega) """ return _multigridtools.jacobi(*args) Modified: trunk/scipy/sandbox/multigrid/multigridtools/multigridtools_wrap.cxx =================================================================== --- trunk/scipy/sandbox/multigrid/multigridtools/multigridtools_wrap.cxx 2008-01-08 04:12:38 UTC (rev 3797) +++ trunk/scipy/sandbox/multigrid/multigridtools/multigridtools_wrap.cxx 2008-01-08 06:19:19 UTC (rev 3798) @@ -4457,28 +4457,28 @@ } -SWIGINTERN PyObject *_wrap_gauss_seidel__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { +SWIGINTERN PyObject *_wrap_block_gauss_seidel__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - int arg1 ; + int *arg1 ; int *arg2 ; - int *arg3 ; + float *arg3 ; float *arg4 ; float *arg5 ; - float *arg6 ; + int arg6 ; int arg7 ; int arg8 ; int arg9 ; - int val1 ; - int ecode1 = 0 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; PyArrayObject *array2 = NULL ; int is_new_object2 ; PyArrayObject *array3 = NULL ; int is_new_object3 ; - PyArrayObject *array4 = NULL ; - int is_new_object4 ; - PyArrayObject *temp5 = NULL ; - PyArrayObject *array6 = NULL ; - int is_new_object6 ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + int val6 ; + int ecode6 = 0 ; int val7 ; int ecode7 = 0 ; int val8 ; @@ -4495,16 +4495,21 @@ PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; - if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "gauss_seidel" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:block_gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) SWIG_fail; { npy_intp size[1] = { -1 }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; @@ -4515,106 +4520,101 @@ npy_intp size[1] = { -1 }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_FLOAT, &is_new_object3); if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - arg3 = (int*) array3->data; + arg3 = (float*) array3->data; } { - npy_intp size[1] = { - -1 - }; - array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_FLOAT, &is_new_object4); - if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) - || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; - - arg4 = (float*) array4->data; + temp4 = obj_to_array_no_conversion(obj3,PyArray_FLOAT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (float*) array_data(temp4); } { - temp5 = obj_to_array_no_conversion(obj4,PyArray_FLOAT); - if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; - arg5 = (float*) array_data(temp5); - } - { npy_intp size[1] = { -1 }; - array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_FLOAT, &is_new_object6); - if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) - || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_FLOAT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; - arg6 = (float*) array6->data; + arg5 = (float*) array5->data; } + ecode6 = SWIG_AsVal_int(obj5, &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "block_gauss_seidel" "', argument " "6"" of type '" "int""'"); + } + arg6 = static_cast< int >(val6); ecode7 = SWIG_AsVal_int(obj6, &val7); if (!SWIG_IsOK(ecode7)) { - SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "gauss_seidel" "', argument " "7"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "block_gauss_seidel" "', argument " "7"" of type '" "int""'"); } arg7 = static_cast< int >(val7); ecode8 = SWIG_AsVal_int(obj7, &val8); if (!SWIG_IsOK(ecode8)) { - SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "gauss_seidel" "', argument " "8"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "block_gauss_seidel" "', argument " "8"" of type '" "int""'"); } arg8 = static_cast< int >(val8); ecode9 = SWIG_AsVal_int(obj8, &val9); if (!SWIG_IsOK(ecode9)) { - SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "gauss_seidel" "', argument " "9"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "block_gauss_seidel" "', argument " "9"" of type '" "int""'"); } arg9 = static_cast< int >(val9); - gauss_seidel(arg1,(int const (*))arg2,(int const (*))arg3,(float const (*))arg4,arg5,(float const (*))arg6,arg7,arg8,arg9); + block_gauss_seidel((int const (*))arg1,(int const (*))arg2,(float const (*))arg3,arg4,(float const (*))arg5,arg6,arg7,arg8,arg9); resultobj = SWIG_Py_Void(); { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return resultobj; fail: { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return NULL; } -SWIGINTERN PyObject *_wrap_gauss_seidel__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { +SWIGINTERN PyObject *_wrap_block_gauss_seidel__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - int arg1 ; + int *arg1 ; int *arg2 ; - int *arg3 ; + double *arg3 ; double *arg4 ; double *arg5 ; - double *arg6 ; + int arg6 ; int arg7 ; int arg8 ; int arg9 ; - int val1 ; - int ecode1 = 0 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; PyArrayObject *array2 = NULL ; int is_new_object2 ; PyArrayObject *array3 = NULL ; int is_new_object3 ; - PyArrayObject *array4 = NULL ; - int is_new_object4 ; - PyArrayObject *temp5 = NULL ; - PyArrayObject *array6 = NULL ; - int is_new_object6 ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + int val6 ; + int ecode6 = 0 ; int val7 ; int ecode7 = 0 ; int val8 ; @@ -4631,16 +4631,21 @@ PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; - if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "gauss_seidel" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:block_gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) SWIG_fail; { npy_intp size[1] = { -1 }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; @@ -4651,85 +4656,80 @@ npy_intp size[1] = { -1 }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_DOUBLE, &is_new_object3); if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - arg3 = (int*) array3->data; + arg3 = (double*) array3->data; } { - npy_intp size[1] = { - -1 - }; - array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_DOUBLE, &is_new_object4); - if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) - || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; - - arg4 = (double*) array4->data; + temp4 = obj_to_array_no_conversion(obj3,PyArray_DOUBLE); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (double*) array_data(temp4); } { - temp5 = obj_to_array_no_conversion(obj4,PyArray_DOUBLE); - if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; - arg5 = (double*) array_data(temp5); - } - { npy_intp size[1] = { -1 }; - array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_DOUBLE, &is_new_object6); - if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) - || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_DOUBLE, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; - arg6 = (double*) array6->data; + arg5 = (double*) array5->data; } + ecode6 = SWIG_AsVal_int(obj5, &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "block_gauss_seidel" "', argument " "6"" of type '" "int""'"); + } + arg6 = static_cast< int >(val6); ecode7 = SWIG_AsVal_int(obj6, &val7); if (!SWIG_IsOK(ecode7)) { - SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "gauss_seidel" "', argument " "7"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "block_gauss_seidel" "', argument " "7"" of type '" "int""'"); } arg7 = static_cast< int >(val7); ecode8 = SWIG_AsVal_int(obj7, &val8); if (!SWIG_IsOK(ecode8)) { - SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "gauss_seidel" "', argument " "8"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "block_gauss_seidel" "', argument " "8"" of type '" "int""'"); } arg8 = static_cast< int >(val8); ecode9 = SWIG_AsVal_int(obj8, &val9); if (!SWIG_IsOK(ecode9)) { - SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "gauss_seidel" "', argument " "9"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "block_gauss_seidel" "', argument " "9"" of type '" "int""'"); } arg9 = static_cast< int >(val9); - gauss_seidel(arg1,(int const (*))arg2,(int const (*))arg3,(double const (*))arg4,arg5,(double const (*))arg6,arg7,arg8,arg9); + block_gauss_seidel((int const (*))arg1,(int const (*))arg2,(double const (*))arg3,arg4,(double const (*))arg5,arg6,arg7,arg8,arg9); resultobj = SWIG_Py_Void(); { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return resultobj; fail: { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return NULL; } -SWIGINTERN PyObject *_wrap_gauss_seidel(PyObject *self, PyObject *args) { +SWIGINTERN PyObject *_wrap_block_gauss_seidel(PyObject *self, PyObject *args) { int argc; PyObject *argv[10]; int ii; @@ -4742,8 +4742,7 @@ if (argc == 9) { int _v; { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; } if (_v) { { @@ -4751,7 +4750,7 @@ } if (_v) { { - _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_FLOAT)) ? 1 : 0; } if (_v) { { @@ -4763,7 +4762,8 @@ } if (_v) { { - _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_FLOAT)) ? 1 : 0; + int res = SWIG_AsVal_int(argv[5], NULL); + _v = SWIG_CheckState(res); } if (_v) { { @@ -4781,7 +4781,7 @@ _v = SWIG_CheckState(res); } if (_v) { - return _wrap_gauss_seidel__SWIG_1(self, args); + return _wrap_block_gauss_seidel__SWIG_1(self, args); } } } @@ -4795,8 +4795,7 @@ if (argc == 9) { int _v; { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; } if (_v) { { @@ -4804,7 +4803,7 @@ } if (_v) { { - _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_DOUBLE)) ? 1 : 0; } if (_v) { { @@ -4816,7 +4815,8 @@ } if (_v) { { - _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_DOUBLE)) ? 1 : 0; + int res = SWIG_AsVal_int(argv[5], NULL); + _v = SWIG_CheckState(res); } if (_v) { { @@ -4834,7 +4834,7 @@ _v = SWIG_CheckState(res); } if (_v) { - return _wrap_gauss_seidel__SWIG_2(self, args); + return _wrap_block_gauss_seidel__SWIG_2(self, args); } } } @@ -4847,44 +4847,406 @@ } fail: - SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'gauss_seidel'.\n Possible C/C++ prototypes are:\n"" gauss_seidel<(int,float)>(int const,int const [],int const [],float const [],float [],float const [],int const,int const,int const)\n"" gauss_seidel<(int,double)>(int const,int const [],int const [],double const [],double [],double const [],int const,int const,int const)\n"); + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'block_gauss_seidel'.\n Possible C/C++ prototypes are:\n"" block_gauss_seidel<(int,float)>(int const [],int const [],float const [],float [],float const [],int const,int const,int const,int const)\n"" block_gauss_seidel<(int,double)>(int const [],int const [],double const [],double [],double const [],int const,int const,int const,int const)\n"); return NULL; } +SWIGINTERN PyObject *_wrap_gauss_seidel__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int *arg1 ; + int *arg2 ; + float *arg3 ; + float *arg4 ; + float *arg5 ; + int arg6 ; + int arg7 ; + int arg8 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; + PyArrayObject *array2 = NULL ; + int is_new_object2 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + int val6 ; + int ecode6 = 0 ; + int val7 ; + int ecode7 = 0 ; + int val8 ; + int ecode8 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + { + npy_intp size[1] = { + -1 + }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; + array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); + if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) + || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; + + arg2 = (int*) array2->data; + } + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_FLOAT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (float*) array3->data; + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_FLOAT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (float*) array_data(temp4); + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_FLOAT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (float*) array5->data; + } + ecode6 = SWIG_AsVal_int(obj5, &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "gauss_seidel" "', argument " "6"" of type '" "int""'"); + } + arg6 = static_cast< int >(val6); + ecode7 = SWIG_AsVal_int(obj6, &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "gauss_seidel" "', argument " "7"" of type '" "int""'"); + } + arg7 = static_cast< int >(val7); + ecode8 = SWIG_AsVal_int(obj7, &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "gauss_seidel" "', argument " "8"" of type '" "int""'"); + } + arg8 = static_cast< int >(val8); + gauss_seidel((int const (*))arg1,(int const (*))arg2,(float const (*))arg3,arg4,(float const (*))arg5,arg6,arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { + if (is_new_object2 && array2) Py_DECREF(array2); + } + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + return resultobj; +fail: + { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { + if (is_new_object2 && array2) Py_DECREF(array2); + } + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_gauss_seidel__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int *arg1 ; + int *arg2 ; + double *arg3 ; + double *arg4 ; + double *arg5 ; + int arg6 ; + int arg7 ; + int arg8 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; + PyArrayObject *array2 = NULL ; + int is_new_object2 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + int val6 ; + int ecode6 = 0 ; + int val7 ; + int ecode7 = 0 ; + int val8 ; + int ecode8 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + { + npy_intp size[1] = { + -1 + }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; + array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); + if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) + || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; + + arg2 = (int*) array2->data; + } + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_DOUBLE, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (double*) array3->data; + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_DOUBLE); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (double*) array_data(temp4); + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_DOUBLE, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (double*) array5->data; + } + ecode6 = SWIG_AsVal_int(obj5, &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "gauss_seidel" "', argument " "6"" of type '" "int""'"); + } + arg6 = static_cast< int >(val6); + ecode7 = SWIG_AsVal_int(obj6, &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "gauss_seidel" "', argument " "7"" of type '" "int""'"); + } + arg7 = static_cast< int >(val7); + ecode8 = SWIG_AsVal_int(obj7, &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "gauss_seidel" "', argument " "8"" of type '" "int""'"); + } + arg8 = static_cast< int >(val8); + gauss_seidel((int const (*))arg1,(int const (*))arg2,(double const (*))arg3,arg4,(double const (*))arg5,arg6,arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { + if (is_new_object2 && array2) Py_DECREF(array2); + } + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + return resultobj; +fail: + { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { + if (is_new_object2 && array2) Py_DECREF(array2); + } + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_gauss_seidel(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[9]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 8); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 8) { + int _v; + { + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[1]) && PyArray_CanCastSafely(PyArray_TYPE(argv[1]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[5], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[6], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[7], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + return _wrap_gauss_seidel__SWIG_1(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[1]) && PyArray_CanCastSafely(PyArray_TYPE(argv[1]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[5], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[6], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[7], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + return _wrap_gauss_seidel__SWIG_2(self, args); + } + } + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'gauss_seidel'.\n Possible C/C++ prototypes are:\n"" gauss_seidel<(int,float)>(int const [],int const [],float const [],float [],float const [],int const,int const,int const)\n"" gauss_seidel<(int,double)>(int const [],int const [],double const [],double [],double const [],int const,int const,int const)\n"); + return NULL; +} + + SWIGINTERN PyObject *_wrap_jacobi__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - int arg1 ; + int *arg1 ; int *arg2 ; - int *arg3 ; + float *arg3 ; float *arg4 ; float *arg5 ; float *arg6 ; - float *arg7 ; + int arg7 ; int arg8 ; int arg9 ; - int arg10 ; - float arg11 ; - int val1 ; - int ecode1 = 0 ; + float arg10 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; PyArrayObject *array2 = NULL ; int is_new_object2 ; PyArrayObject *array3 = NULL ; int is_new_object3 ; - PyArrayObject *array4 = NULL ; - int is_new_object4 ; - PyArrayObject *temp5 = NULL ; - PyArrayObject *array6 = NULL ; - int is_new_object6 ; - PyArrayObject *temp7 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *temp6 = NULL ; + int val7 ; + int ecode7 = 0 ; int val8 ; int ecode8 = 0 ; int val9 ; int ecode9 = 0 ; - int val10 ; + float val10 ; int ecode10 = 0 ; - float val11 ; - int ecode11 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; @@ -4895,18 +5257,22 @@ PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; PyObject * obj9 = 0 ; - PyObject * obj10 = 0 ; - if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOOO:jacobi",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9,&obj10)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "jacobi" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:jacobi",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; { npy_intp size[1] = { -1 }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; @@ -4917,42 +5283,37 @@ npy_intp size[1] = { -1 }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_FLOAT, &is_new_object3); if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - arg3 = (int*) array3->data; + arg3 = (float*) array3->data; } { - npy_intp size[1] = { - -1 - }; - array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_FLOAT, &is_new_object4); - if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) - || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; - - arg4 = (float*) array4->data; + temp4 = obj_to_array_no_conversion(obj3,PyArray_FLOAT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (float*) array_data(temp4); } { - temp5 = obj_to_array_no_conversion(obj4,PyArray_FLOAT); - if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; - arg5 = (float*) array_data(temp5); - } - { npy_intp size[1] = { -1 }; - array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_FLOAT, &is_new_object6); - if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) - || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_FLOAT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; - arg6 = (float*) array6->data; + arg5 = (float*) array5->data; } { - temp7 = obj_to_array_no_conversion(obj6,PyArray_FLOAT); - if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; - arg7 = (float*) array_data(temp7); + temp6 = obj_to_array_no_conversion(obj5,PyArray_FLOAT); + if (!temp6 || !require_contiguous(temp6) || !require_native(temp6)) SWIG_fail; + arg6 = (float*) array_data(temp6); } + ecode7 = SWIG_AsVal_int(obj6, &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "jacobi" "', argument " "7"" of type '" "int""'"); + } + arg7 = static_cast< int >(val7); ecode8 = SWIG_AsVal_int(obj7, &val8); if (!SWIG_IsOK(ecode8)) { SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "jacobi" "', argument " "8"" of type '" "int""'"); @@ -4963,81 +5324,73 @@ SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "jacobi" "', argument " "9"" of type '" "int""'"); } arg9 = static_cast< int >(val9); - ecode10 = SWIG_AsVal_int(obj9, &val10); + ecode10 = SWIG_AsVal_float(obj9, &val10); if (!SWIG_IsOK(ecode10)) { - SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "jacobi" "', argument " "10"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "jacobi" "', argument " "10"" of type '" "float""'"); } - arg10 = static_cast< int >(val10); - ecode11 = SWIG_AsVal_float(obj10, &val11); - if (!SWIG_IsOK(ecode11)) { - SWIG_exception_fail(SWIG_ArgError(ecode11), "in method '" "jacobi" "', argument " "11"" of type '" "float""'"); - } - arg11 = static_cast< float >(val11); - jacobi(arg1,(int const (*))arg2,(int const (*))arg3,(float const (*))arg4,arg5,(float const (*))arg6,arg7,arg8,arg9,arg10,arg11); + arg10 = static_cast< float >(val10); + jacobi((int const (*))arg1,(int const (*))arg2,(float const (*))arg3,arg4,(float const (*))arg5,arg6,arg7,arg8,arg9,arg10); resultobj = SWIG_Py_Void(); { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return resultobj; fail: { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return NULL; } SWIGINTERN PyObject *_wrap_jacobi__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - int arg1 ; + int *arg1 ; int *arg2 ; - int *arg3 ; + double *arg3 ; double *arg4 ; double *arg5 ; double *arg6 ; - double *arg7 ; + int arg7 ; int arg8 ; int arg9 ; - int arg10 ; - double arg11 ; - int val1 ; - int ecode1 = 0 ; + double arg10 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; PyArrayObject *array2 = NULL ; int is_new_object2 ; PyArrayObject *array3 = NULL ; int is_new_object3 ; - PyArrayObject *array4 = NULL ; - int is_new_object4 ; - PyArrayObject *temp5 = NULL ; - PyArrayObject *array6 = NULL ; - int is_new_object6 ; - PyArrayObject *temp7 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *temp6 = NULL ; + int val7 ; + int ecode7 = 0 ; int val8 ; int ecode8 = 0 ; int val9 ; int ecode9 = 0 ; - int val10 ; + double val10 ; int ecode10 = 0 ; - double val11 ; - int ecode11 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; @@ -5048,18 +5401,22 @@ PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; PyObject * obj9 = 0 ; - PyObject * obj10 = 0 ; - if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOOO:jacobi",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9,&obj10)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "jacobi" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:jacobi",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; { npy_intp size[1] = { -1 }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; @@ -5070,42 +5427,37 @@ npy_intp size[1] = { -1 }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_DOUBLE, &is_new_object3); if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - arg3 = (int*) array3->data; + arg3 = (double*) array3->data; } { - npy_intp size[1] = { - -1 - }; - array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_DOUBLE, &is_new_object4); - if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) - || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; - - arg4 = (double*) array4->data; + temp4 = obj_to_array_no_conversion(obj3,PyArray_DOUBLE); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (double*) array_data(temp4); } { - temp5 = obj_to_array_no_conversion(obj4,PyArray_DOUBLE); - if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; - arg5 = (double*) array_data(temp5); - } - { npy_intp size[1] = { -1 }; - array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_DOUBLE, &is_new_object6); - if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) - || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_DOUBLE, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; - arg6 = (double*) array6->data; + arg5 = (double*) array5->data; } { - temp7 = obj_to_array_no_conversion(obj6,PyArray_DOUBLE); - if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; - arg7 = (double*) array_data(temp7); + temp6 = obj_to_array_no_conversion(obj5,PyArray_DOUBLE); + if (!temp6 || !require_contiguous(temp6) || !require_native(temp6)) SWIG_fail; + arg6 = (double*) array_data(temp6); } + ecode7 = SWIG_AsVal_int(obj6, &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "jacobi" "', argument " "7"" of type '" "int""'"); + } + arg7 = static_cast< int >(val7); ecode8 = SWIG_AsVal_int(obj7, &val8); if (!SWIG_IsOK(ecode8)) { SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "jacobi" "', argument " "8"" of type '" "int""'"); @@ -5116,63 +5468,57 @@ SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "jacobi" "', argument " "9"" of type '" "int""'"); } arg9 = static_cast< int >(val9); - ecode10 = SWIG_AsVal_int(obj9, &val10); + ecode10 = SWIG_AsVal_double(obj9, &val10); if (!SWIG_IsOK(ecode10)) { - SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "jacobi" "', argument " "10"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "jacobi" "', argument " "10"" of type '" "double""'"); } - arg10 = static_cast< int >(val10); - ecode11 = SWIG_AsVal_double(obj10, &val11); - if (!SWIG_IsOK(ecode11)) { - SWIG_exception_fail(SWIG_ArgError(ecode11), "in method '" "jacobi" "', argument " "11"" of type '" "double""'"); - } - arg11 = static_cast< double >(val11); - jacobi(arg1,(int const (*))arg2,(int const (*))arg3,(double const (*))arg4,arg5,(double const (*))arg6,arg7,arg8,arg9,arg10,arg11); + arg10 = static_cast< double >(val10); + jacobi((int const (*))arg1,(int const (*))arg2,(double const (*))arg3,arg4,(double const (*))arg5,arg6,arg7,arg8,arg9,arg10); resultobj = SWIG_Py_Void(); { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return resultobj; fail: { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return NULL; } SWIGINTERN PyObject *_wrap_jacobi(PyObject *self, PyObject *args) { int argc; - PyObject *argv[12]; + PyObject *argv[11]; int ii; if (!PyTuple_Check(args)) SWIG_fail; argc = (int)PyObject_Length(args); - for (ii = 0; (ii < argc) && (ii < 11); ii++) { + for (ii = 0; (ii < argc) && (ii < 10); ii++) { argv[ii] = PyTuple_GET_ITEM(args,ii); } - if (argc == 11) { + if (argc == 10) { int _v; { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; } if (_v) { { @@ -5180,7 +5526,7 @@ } if (_v) { { - _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_FLOAT)) ? 1 : 0; } if (_v) { { @@ -5196,7 +5542,8 @@ } if (_v) { { - _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_FLOAT)) ? 1 : 0; + int res = SWIG_AsVal_int(argv[6], NULL); + _v = SWIG_CheckState(res); } if (_v) { { @@ -5210,17 +5557,11 @@ } if (_v) { { - int res = SWIG_AsVal_int(argv[9], NULL); + int res = SWIG_AsVal_float(argv[9], NULL); _v = SWIG_CheckState(res); } if (_v) { - { - int res = SWIG_AsVal_float(argv[10], NULL); - _v = SWIG_CheckState(res); - } - if (_v) { - return _wrap_jacobi__SWIG_1(self, args); - } + return _wrap_jacobi__SWIG_1(self, args); } } } @@ -5232,11 +5573,10 @@ } } } - if (argc == 11) { + if (argc == 10) { int _v; { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; } if (_v) { { @@ -5244,7 +5584,7 @@ } if (_v) { { - _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_DOUBLE)) ? 1 : 0; } if (_v) { { @@ -5260,7 +5600,8 @@ } if (_v) { { - _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_DOUBLE)) ? 1 : 0; + int res = SWIG_AsVal_int(argv[6], NULL); + _v = SWIG_CheckState(res); } if (_v) { { @@ -5274,17 +5615,11 @@ } if (_v) { { - int res = SWIG_AsVal_int(argv[9], NULL); + int res = SWIG_AsVal_double(argv[9], NULL); _v = SWIG_CheckState(res); } if (_v) { - { - int res = SWIG_AsVal_double(argv[10], NULL); - _v = SWIG_CheckState(res); - } - if (_v) { - return _wrap_jacobi__SWIG_2(self, args); - } + return _wrap_jacobi__SWIG_2(self, args); } } } @@ -5298,7 +5633,7 @@ } fail: - SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'jacobi'.\n Possible C/C++ prototypes are:\n"" jacobi<(int,float)>(int const,int const [],int const [],float const [],float [],float const [],float [],int const,int const,int const,float const)\n"" jacobi<(int,double)>(int const,int const [],int const [],double const [],double [],double const [],double [],int const,int const,int const,double const)\n"); + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'jacobi'.\n Possible C/C++ prototypes are:\n"" jacobi<(int,float)>(int const [],int const [],float const [],float [],float const [],float [],int const,int const,int const,float const)\n"" jacobi<(int,double)>(int const [],int const [],double const [],double [],double const [],double [],int const,int const,int const,double const)\n"); return NULL; } @@ -5329,19 +5664,25 @@ " std::vector<(int)> Sp, std::vector<(int)> Sj, \n" " std::vector<(double)> Sx)\n" ""}, + { (char *)"block_gauss_seidel", _wrap_block_gauss_seidel, METH_VARARGS, (char *)"\n" + "block_gauss_seidel(int Ap, int Aj, float Ax, float x, float b, int row_start, \n" + " int row_stop, int row_step, int blocksize)\n" + "block_gauss_seidel(int Ap, int Aj, double Ax, double x, double b, int row_start, \n" + " int row_stop, int row_step, int blocksize)\n" + ""}, { (char *)"gauss_seidel", _wrap_gauss_seidel, METH_VARARGS, (char *)"\n" - "gauss_seidel(int n_row, int Ap, int Aj, float Ax, float x, float b, \n" - " int row_start, int row_stop, int row_step)\n" - "gauss_seidel(int n_row, int Ap, int Aj, double Ax, double x, double b, \n" - " int row_start, int row_stop, int row_step)\n" + "gauss_seidel(int Ap, int Aj, float Ax, float x, float b, int row_start, \n" + " int row_stop, int row_step)\n" + "gauss_seidel(int Ap, int Aj, double Ax, double x, double b, int row_start, \n" + " int row_stop, int row_step)\n" ""}, { (char *)"jacobi", _wrap_jacobi, METH_VARARGS, (char *)"\n" - "jacobi(int n_row, int Ap, int Aj, float Ax, float x, float b, \n" - " float temp, int row_start, int row_stop, \n" - " int row_step, float omega)\n" - "jacobi(int n_row, int Ap, int Aj, double Ax, double x, double b, \n" - " double temp, int row_start, int row_stop, \n" - " int row_step, double omega)\n" + "jacobi(int Ap, int Aj, float Ax, float x, float b, float temp, \n" + " int row_start, int row_stop, int row_step, \n" + " float omega)\n" + "jacobi(int Ap, int Aj, double Ax, double x, double b, double temp, \n" + " int row_start, int row_stop, int row_step, \n" + " double omega)\n" ""}, { NULL, NULL, 0, NULL } }; Modified: trunk/scipy/sandbox/multigrid/multigridtools/relaxation.h =================================================================== --- trunk/scipy/sandbox/multigrid/multigridtools/relaxation.h 2008-01-08 04:12:38 UTC (rev 3797) +++ trunk/scipy/sandbox/multigrid/multigridtools/relaxation.h 2008-01-08 06:19:19 UTC (rev 3798) @@ -5,8 +5,7 @@ #include template -void gauss_seidel(const I n_row, - const I Ap[], +void gauss_seidel(const I Ap[], const I Aj[], const T Ax[], T x[], @@ -36,9 +35,59 @@ } } + template -void jacobi(const I n_row, - const I Ap[], +void block_gauss_seidel(const I Ap[], + const I Aj[], + const T Ax[], + T x[], + const T b[], + const I row_start, + const I row_stop, + const I row_step, + const I blocksize) +{ + const I B2 = blocksize * blocksize; + + for(I i = row_start; i != row_stop; i += row_step) { + I start = Ap[i]; + I end = Ap[i+1]; + + for(I bi = 0; bi < blocksize; bi++){ + T rsum = 0; + T diag = 0; + + for(I jj = start; jj < end; jj++){ + I j = Aj[jj]; + const T * block_row = Ax + B2*jj + blocksize*bi; + const T * block_x = x + blocksize * j; + + if (i == j){ + //diagonal block + diag = block_row[bi]; + for(I bj = 0; bj < bi; bj++){ + rsum += block_row[bj] * block_x[bj]; + } + for(I bj = bi+1; bj < blocksize; bj++){ + rsum += block_row[bj] * block_x[bj]; + } + } else { + for(I bj = 0; bj < blocksize; bj++){ + rsum += block_row[bj] * block_x[bj]; + } + } + } + + //TODO raise error? inform user? + if (diag != 0){ + x[blocksize*i + bi] = (b[blocksize*i + bi] - rsum)/diag; + } + } + } +} + +template +void jacobi(const I Ap[], const I Aj[], const T Ax[], T x[], @@ -49,7 +98,9 @@ const I row_step, const T omega) { - std::copy(x,x+n_row,temp); + for(I i = row_start; i != row_stop; i += row_step) { + temp[i] = x[i]; + } for(I i = row_start; i != row_stop; i += row_step) { I start = Ap[i]; Modified: trunk/scipy/sandbox/multigrid/relaxation.py =================================================================== --- trunk/scipy/sandbox/multigrid/relaxation.py 2008-01-08 04:12:38 UTC (rev 3797) +++ trunk/scipy/sandbox/multigrid/relaxation.py 2008-01-08 06:19:19 UTC (rev 3798) @@ -1,7 +1,30 @@ +from warnings import warn + +from numpy import empty_like, asarray, arange, ravel + import multigridtools -from numpy import empty_like, asarray +from scipy.sparse import isspmatrix_csr, isspmatrix_csc, isspmatrix_bsr, \ + csr_matrix, coo_matrix, bsr_matrix, SparseEfficiencyWarning +#def split_ldu(A): +# """ +# Return the lower triangle, diagonal, and upper triangular portions of a matrix. +# """ +# if isspmatrix_csr(A) or isspmatrix_csc(A): +# coo = A.tocoo(copy=False) +# elif isspmatrix_bsr(A): +# M,N = A.shape +# R,C = A.blocksize +# data = arange(len(A.indices),dtype='intc') +# proxy = csr_matrix((data,A.indices,A.indptr),shape=(M/R,N/C)) +# L,D,U = split_ldu(proxy) +# L = bsr_matrix((A.data[L.data],L.indices,L.indptr),shape=A.shape) +# U = bsr_matrix((A.data[U.data],U.indices,U.indptr),shape=A.shape) +# D = A.data[D] + + + def sor(A,x,b,omega,iterations=1,sweep='forward'): """ Perform SOR iteration on the linear system Ax=b @@ -30,37 +53,58 @@ sweep - direction of sweep: 'forward' (default), 'backward', or 'symmetric' """ - x = asarray(x).reshape(-1) - b = asarray(b).reshape(-1) + #TODO replace pointwise BSR with block BSR + x = x.reshape(-1) #TODO warn if not inplace + b = ravel(b) + + if isspmatrix_csr(A): + pass + elif isspmatrix_bsr(A): + R,C = A.blocksize + if R != C: + raise ValueError,'BSR blocks must be square' + else: + warn('implicit conversion to CSR',SparseEfficiencyWarning) + A = csr_matrix(A) + if A.shape[0] != A.shape[1]: - raise ValueError,'expected symmetric matrix' + raise ValueError,'expected square matrix' if A.shape[1] != len(x) or len(x) != len(b): raise ValueError,'unexpected number of unknowns' + + if sweep == 'forward': row_start,row_stop,row_step = 0,len(x),1 - for iter in xrange(iterations): - multigridtools.gauss_seidel(A.shape[0], - A.indptr, A.indices, A.data, - x, b, - row_start, row_stop, row_step) elif sweep == 'backward': - row_start,row_stop,row_step = len(x)-1,-1,-1 - for iter in xrange(iterations): - multigridtools.gauss_seidel(A.shape[0], - A.indptr, A.indices, A.data, - x, b, - row_start, row_stop, row_step) + row_start,row_stop,row_step = len(x)-1,-1,-1 elif sweep == 'symmetric': for iter in xrange(iterations): gauss_seidel(A,x,b,iterations=1,sweep='forward') gauss_seidel(A,x,b,iterations=1,sweep='backward') + return else: raise ValueError,'valid sweep directions are \'forward\', \'backward\', and \'symmetric\'' + if isspmatrix_csr(A): + for iter in xrange(iterations): + multigridtools.gauss_seidel(A.indptr, A.indices, A.data, + x, b, + row_start, row_stop, row_step) + else: + blocksize = A.blocksize[0] + row_start = row_start/blocksize + row_stop = row_stop/blocksize + for iter in xrange(iterations): + multigridtools.block_gauss_seidel(A.indptr, A.indices, ravel(A.data), + x, b, + row_start, row_stop, row_step, + blocksize) + + def jacobi(A,x,b,iterations=1,omega=1.0): """ Perform Jacobi iteration on the linear system Ax=b @@ -89,8 +133,7 @@ temp = empty_like(x) for iter in xrange(iterations): - multigridtools.jacobi(A.shape[0], - A.indptr, A.indices, A.data, + multigridtools.jacobi(A.indptr, A.indices, A.data, x, b, temp, row_start, row_stop, row_step, omega) Modified: trunk/scipy/sandbox/multigrid/tests/test_relaxation.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-08 04:12:38 UTC (rev 3797) +++ trunk/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-08 06:19:19 UTC (rev 3798) @@ -2,7 +2,7 @@ import numpy import scipy -from scipy import arange,ones,zeros,array,allclose +from scipy import arange,ones,zeros,array,allclose,zeros_like from scipy.sparse import spdiags @@ -15,7 +15,7 @@ class TestRelaxation(NumpyTestCase): def check_polynomial(self): N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x0 = arange(N).astype(numpy.float64) x = x0.copy() b = zeros(N) @@ -39,87 +39,105 @@ def check_jacobi(self): N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) jacobi(A,x,b) assert_almost_equal(x,array([0])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = zeros(N) b = arange(N).astype(numpy.float64) jacobi(A,x,b) assert_almost_equal(x,array([0.0,0.5,1.0])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) jacobi(A,x,b) assert_almost_equal(x,array([0.5,1.0,0.5])) N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = array([10]) jacobi(A,x,b) assert_almost_equal(x,array([5])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = array([10,20,30]) jacobi(A,x,b) assert_almost_equal(x,array([5.5,11.0,15.5])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) x_copy = x.copy() b = array([10,20,30]) jacobi(A,x,b,omega=1.0/3.0) assert_almost_equal(x,2.0/3.0*x_copy + 1.0/3.0*array([5.5,11.0,15.5])) + def check_gauss_seidel_bsr(self): + cases = [] - def check_gauss_seidel(self): + for N in [1,2,3,4,5,6,10]: + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).tocsr() + + divisors = [ n for n in range(1,N+1) if N % n == 0 ] + + x_csr = arange(N).astype(numpy.float64) + b = x_csr**2 + gauss_seidel(A,x_csr,b) + + for D in divisors: + B = A.tobsr(blocksize=(D,D)) + x_bsr = arange(N).astype(numpy.float64) + gauss_seidel(B,x_bsr,b) + assert_almost_equal(x_bsr,x_csr) + + + def check_gauss_seidel_csr(self): N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) gauss_seidel(A,x,b) assert_almost_equal(x,array([0])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) gauss_seidel(A,x,b) assert_almost_equal(x,array([1.0/2.0,5.0/4.0,5.0/8.0])) N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) gauss_seidel(A,x,b,sweep='backward') assert_almost_equal(x,array([0])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) gauss_seidel(A,x,b,sweep='backward') assert_almost_equal(x,array([1.0/8.0,1.0/4.0,1.0/2.0])) N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = array([10]) gauss_seidel(A,x,b) assert_almost_equal(x,array([5])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = array([10,20,30]) gauss_seidel(A,x,b) @@ -128,7 +146,7 @@ #forward and backward passes should give same result with x=ones(N),b=zeros(N) N = 100 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = ones(N) b = zeros(N) gauss_seidel(A,x,b,iterations=200,sweep='forward') From scipy-svn at scipy.org Tue Jan 8 05:16:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 04:16:26 -0600 (CST) Subject: [Scipy-svn] r3799 - in branches/testing_cleanup/scipy: . cluster/tests fftpack/tests lib/lapack/tests linalg/tests ndimage optimize/tests sparse/tests stats stats/tests testing Message-ID: <20080108101626.6B63539C37F@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-08 04:16:05 -0600 (Tue, 08 Jan 2008) New Revision: 3799 Added: branches/testing_cleanup/scipy/sparse/tests/test_spfuncs.py Modified: branches/testing_cleanup/scipy/__init__.py branches/testing_cleanup/scipy/cluster/tests/test_vq.py branches/testing_cleanup/scipy/fftpack/tests/test_basic.py branches/testing_cleanup/scipy/fftpack/tests/test_pseudo_diffs.py branches/testing_cleanup/scipy/lib/lapack/tests/esv_tests.py branches/testing_cleanup/scipy/lib/lapack/tests/gesv_tests.py branches/testing_cleanup/scipy/linalg/tests/test_basic.py branches/testing_cleanup/scipy/linalg/tests/test_decomp.py branches/testing_cleanup/scipy/ndimage/__init__.py branches/testing_cleanup/scipy/optimize/tests/test_cobyla.py branches/testing_cleanup/scipy/optimize/tests/test_zeros.py branches/testing_cleanup/scipy/sparse/tests/test_base.py branches/testing_cleanup/scipy/sparse/tests/test_construct.py branches/testing_cleanup/scipy/sparse/tests/test_sparse.py branches/testing_cleanup/scipy/stats/info.py branches/testing_cleanup/scipy/stats/morestats.py branches/testing_cleanup/scipy/stats/tests/test_distributions.py branches/testing_cleanup/scipy/stats/tests/test_morestats.py branches/testing_cleanup/scipy/testing/decorators.py branches/testing_cleanup/scipy/testing/nosetester.py branches/testing_cleanup/scipy/testing/pkgtester.py Log: Module level tests working, change in interface for binomial test in stats to prevent running under nose test default Modified: branches/testing_cleanup/scipy/__init__.py =================================================================== --- branches/testing_cleanup/scipy/__init__.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/__init__.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -62,14 +62,9 @@ """ __doc__ += pkgload.get_pkgdocs() +from testing.pkgtester import Tester +test = Tester().test -def test(level=1, verbosity=1): - """ Run Scipy tests suite with level and verbosity.""" - from numpy.testing import NumpyTest - import scipy - scipy.pkgload() - return NumpyTest(scipy).test(level, verbosity) - __doc__ += """ Utility tools Modified: branches/testing_cleanup/scipy/cluster/tests/test_vq.py =================================================================== --- branches/testing_cleanup/scipy/cluster/tests/test_vq.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/cluster/tests/test_vq.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -40,19 +40,19 @@ LABEL1 = N.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1]) class TestVq(TestCase): - def test_py_vq(self, level=1): + def test_py_vq(self): initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() label1 = py_vq(X, initc)[0] assert_array_equal(label1, LABEL1) - def test_py_vq2(self, level=1): + def test_py_vq2(self): initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() label1 = py_vq2(X, initc)[0] assert_array_equal(label1, LABEL1) - def test_vq(self, level=1): + def test_vq(self): initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() if TESTC: @@ -62,7 +62,7 @@ else: print "== not testing C imp of vq ==" - #def test_py_vq_1d(self, level=1): + #def test_py_vq_1d(self): # """Test special rank 1 vq algo, python implementation.""" # data = X[:, 0] # initc = data[:3] @@ -72,7 +72,7 @@ # assert_array_equal(a, ta) # assert_array_equal(b, tb) - def test_vq_1d(self, level=1): + def test_vq_1d(self): """Test special rank 1 vq algo, python implementation.""" data = X[:, 0] initc = data[:3] @@ -86,14 +86,14 @@ print "== not testing C imp of vq (rank 1) ==" class TestKMean(TestCase): - def test_kmeans_simple(self, level=1): + def test_kmeans_simple(self): initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() code1 = kmeans(X, code, iter = 1)[0] assert_array_almost_equal(code1, CODET2) - def test_kmeans_lost_cluster(self, level=1): + def test_kmeans_lost_cluster(self): """This will cause kmean to have a cluster with no points.""" data = N.fromfile(open(DATAFILE1), sep = ", ") data = data.reshape((200, 2)) @@ -109,7 +109,7 @@ except ClusterError, e: print "exception raised as expected: " + str(e) - def test_kmeans2_simple(self, level=1): + def test_kmeans2_simple(self): """Testing simple call to kmeans2 and its results.""" initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() @@ -119,7 +119,7 @@ assert_array_almost_equal(code1, CODET1) assert_array_almost_equal(code2, CODET2) - def test_kmeans2_rank1(self, level=1): + def test_kmeans2_rank1(self): """Testing simple call to kmeans2 with rank 1 data.""" data = N.fromfile(open(DATAFILE1), sep = ", ") data = data.reshape((200, 2)) Modified: branches/testing_cleanup/scipy/fftpack/tests/test_basic.py =================================================================== --- branches/testing_cleanup/scipy/fftpack/tests/test_basic.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/fftpack/tests/test_basic.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -6,9 +6,9 @@ Build fftpack: python setup_fftpack.py build Run tests if scipy is installed: - python -c 'import scipy;scipy.fftpack.test()' + python -c 'import scipy;scipy.fftpack.test()' Run tests if fftpack is not installed: - python tests/test_basic.py [] + python tests/test_basic.py """ import sys from scipy.testing import * @@ -124,7 +124,8 @@ y = fftpack.zrfft(x) assert_array_almost_equal(y,y2) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import fft as numpy_fft print print ' Fast Fourier Transform' @@ -150,11 +151,11 @@ if size > 500: y = fft(x) else: y = direct_dft(x) assert_array_almost_equal(fft(x),y) - print '|%8.2f' % self.measure('fft(x)',repeat), + print '|%8.2f' % measure('fft(x)',repeat), sys.stdout.flush() assert_array_almost_equal(numpy_fft(x),y) - print '|%8.2f' % self.measure('numpy_fft(x)',repeat), + print '|%8.2f' % measure('numpy_fft(x)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -199,7 +200,8 @@ assert_array_almost_equal (ifft(fft(x)),x) assert_array_almost_equal (fft(ifft(x)),x) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import ifft as numpy_ifft print print ' Inverse Fast Fourier Transform' @@ -225,11 +227,11 @@ if size > 500: y = ifft(x) else: y = direct_idft(x) assert_array_almost_equal(ifft(x),y) - print '|%8.2f' % self.measure('ifft(x)',repeat), + print '|%8.2f' % measure('ifft(x)',repeat), sys.stdout.flush() assert_array_almost_equal(numpy_ifft(x),y) - print '|%8.2f' % self.measure('numpy_ifft(x)',repeat), + print '|%8.2f' % measure('numpy_ifft(x)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -262,7 +264,8 @@ y = fftpack.drfft(x) assert_array_almost_equal(y,y1) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import rfft as numpy_rfft print print 'Fast Fourier Transform (real data)' @@ -281,10 +284,10 @@ sys.stdout.flush() x = random([size]).astype(double) - print '|%8.2f' % self.measure('rfft(x)',repeat), + print '|%8.2f' % measure('rfft(x)',repeat), sys.stdout.flush() - print '|%8.2f' % self.measure('numpy_rfft(x)',repeat), + print '|%8.2f' % measure('numpy_rfft(x)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -327,7 +330,8 @@ assert_array_almost_equal (irfft(rfft(x)),x) assert_array_almost_equal (rfft(irfft(x)),x) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import irfft as numpy_irfft print @@ -355,11 +359,11 @@ x1[-1] = x[-1] y = irfft(x) - print '|%8.2f' % self.measure('irfft(x)',repeat), + print '|%8.2f' % measure('irfft(x)',repeat), sys.stdout.flush() assert_array_almost_equal(numpy_irfft(x1,size),y) - print '|%8.2f' % self.measure('numpy_irfft(x1,size)',repeat), + print '|%8.2f' % measure('numpy_irfft(x1,size)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -493,7 +497,8 @@ assert_array_almost_equal (y,swapaxes(\ fftn(swapaxes(large_x1,-1,-2)),-1,-2)) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import fftn as numpy_fftn print print ' Multi-dimensional Fast Fourier Transform' @@ -516,11 +521,11 @@ #if size > 500: y = fftn(x) #else: y = direct_dft(x) assert_array_almost_equal(fftn(x),y) - print '|%8.2f' % self.measure('fftn(x)',repeat), + print '|%8.2f' % measure('fftn(x)',repeat), sys.stdout.flush() assert_array_almost_equal(numpy_fftn(x),y) - print '|%8.2f' % self.measure('numpy_fftn(x)',repeat), + print '|%8.2f' % measure('numpy_fftn(x)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) Modified: branches/testing_cleanup/scipy/fftpack/tests/test_pseudo_diffs.py =================================================================== --- branches/testing_cleanup/scipy/fftpack/tests/test_pseudo_diffs.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/fftpack/tests/test_pseudo_diffs.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -184,7 +184,8 @@ assert_array_almost_equal(diff(diff(f,k),-k),f) assert_array_almost_equal(diff(diff(f,-k),k),f) - def bench_random(self,level=5): + @dec.bench + def test_random(self): print print 'Differentiation of periodic functions' print '=====================================' @@ -207,9 +208,9 @@ f = sin(x)*cos(4*x) assert_array_almost_equal(diff(f,1),direct_diff(f,1)) assert_array_almost_equal(diff(f,2),direct_diff(f,2)) - print '| %9.2f' % self.measure('diff(f,3)',repeat), + print '| %9.2f' % measure('diff(f,3)',repeat), sys.stdout.flush() - print '| %9.2f' % self.measure('direct_diff(f,3)',repeat), + print '| %9.2f' % measure('direct_diff(f,3)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -247,7 +248,8 @@ assert_array_almost_equal(itilbert(tilbert(f,h),h),f) assert_array_almost_equal(tilbert(itilbert(f,h),h),f) - def bench_random(self,level=5): + @dec.bench + def test_random(self): print print ' Tilbert transform of periodic functions' print '=========================================' @@ -269,9 +271,9 @@ else: f = sin(x)*cos(4*x) assert_array_almost_equal(tilbert(f,1),direct_tilbert(f,1)) - print '| %9.2f' % self.measure('tilbert(f,1)',repeat), + print '| %9.2f' % measure('tilbert(f,1)',repeat), sys.stdout.flush() - print '| %9.2f' % self.measure('direct_tilbert(f,1)',repeat), + print '| %9.2f' % measure('direct_tilbert(f,1)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -330,7 +332,8 @@ assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f) assert_array_almost_equal(hilbert(ihilbert(f)),f) - def bench_random(self,level=5): + @dec.bench + def test_random(self): print print ' Hilbert transform of periodic functions' print '=========================================' @@ -352,9 +355,9 @@ else: f = sin(x)*cos(4*x) assert_array_almost_equal(hilbert(f),direct_hilbert(f)) - print '| %9.2f' % self.measure('hilbert(f)',repeat), + print '| %9.2f' % measure('hilbert(f)',repeat), sys.stdout.flush() - print '| %9.2f' % self.measure('direct_hilbert(f)',repeat), + print '| %9.2f' % measure('direct_hilbert(f)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -395,7 +398,8 @@ assert_array_almost_equal(shift(sin(x),pi),-sin(x)) assert_array_almost_equal(shift(sin(x),pi/2),cos(x)) - def bench_random(self,level=5): + @dec.bench + def test_random(self): print print ' Shifting periodic functions' print '==============================' @@ -421,9 +425,9 @@ sf = sin(x+a)*cos(4*(x+a)) assert_array_almost_equal(direct_shift(f,1),sf) assert_array_almost_equal(shift(f,1),sf) - print '| %9.2f' % self.measure('shift(f,a)',repeat), + print '| %9.2f' % measure('shift(f,a)',repeat), sys.stdout.flush() - print '| %9.2f' % self.measure('direct_shift(f,a)',repeat), + print '| %9.2f' % measure('direct_shift(f,a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) Modified: branches/testing_cleanup/scipy/lib/lapack/tests/esv_tests.py =================================================================== --- branches/testing_cleanup/scipy/lib/lapack/tests/esv_tests.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/lib/lapack/tests/esv_tests.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -4,7 +4,7 @@ class _test_ev(object): - def check_syev(self,level=1,sym='sy',suffix=''): + def check_syev(self,sym='sy',suffix=''): a = [[1,2,3],[2,2,3],[3,3,6]] exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] f = getattr(self.lapack,sym+'ev'+suffix) @@ -20,7 +20,7 @@ #def check_heevd(self): self.check_syev(sym='he',suffix='d') -## def check_heev_complex(self,level=1,suffix=''): +## def check_heev_complex(self,suffix=''): ## a= [[1,2-2j,3+7j],[2+2j,2,3],[3-7j,3,5]] ## exact_w=[-6.305141710654834,2.797880950890922,11.50726075976392] ## f = getattr(self.lapack,'heev'+suffix) @@ -32,7 +32,7 @@ #def check_heevd_complex(self): self.check_heev_complex(suffix='d') - def check_syevr(self,level=1,sym='sy'): + def check_syevr(self,sym='sy'): a = [[1,2,3],[2,2,3],[3,3,6]] exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] f = getattr(self.lapack,sym+'evr') @@ -42,7 +42,7 @@ for i in range(3): assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i]) -## def check_heevr_complex(self,level=1): +## def check_heevr_complex(self): ## a= [[1,2-2j,3+7j],[2+2j,2,3],[3-7j,3,5]] ## exact_w=[-6.305141710654834,2.797880950890922,11.50726075976392] ## f = self.lapack.heevr @@ -54,7 +54,7 @@ ## def check_heevr(self): self.check_syevr(sym='he') - def check_syevr_irange(self,level=1,sym='sy',irange=[0,2]): + def check_syevr_irange(self,sym='sy',irange=[0,2]): a = [[1,2,3],[2,2,3],[3,3,6]] exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] f = getattr(self.lapack,sym+'evr') @@ -79,7 +79,7 @@ ## def check_heevr_irange_high(self): self.check_syevr_irange(sym='he',irange=[1,2]) - def check_syevr_vrange(self,level=1,sym='sy',vrange=None): + def check_syevr_vrange(self,sym='sy',vrange=None): a = [[1,2,3],[2,2,3],[3,3,6]] exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] if vrange is None: Modified: branches/testing_cleanup/scipy/lib/lapack/tests/gesv_tests.py =================================================================== --- branches/testing_cleanup/scipy/lib/lapack/tests/gesv_tests.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/lib/lapack/tests/gesv_tests.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -4,7 +4,7 @@ class _test_gev(object): - def check_sygv(self,level=1,sym='sy',suffix='',itype=1): + def check_sygv(self,sym='sy',suffix='',itype=1): a = [[1,2,3],[2,2,3],[3,3,6]] b = [[10,-1,1],[-1,8,-2],[1,-2,6]] f = getattr(self.lapack,sym+'gv'+suffix) Modified: branches/testing_cleanup/scipy/linalg/tests/test_basic.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_basic.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/linalg/tests/test_basic.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -14,9 +14,9 @@ Build linalg: python setup_linalg.py build Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' + python -c 'import scipy;scipy.linalg.test()' Run tests if linalg is not installed: - python tests/test_basic.py [] + python tests/test_basic.py """ import numpy @@ -153,7 +153,8 @@ x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.dot(a,x),b) - def bench_random(self,level=5): + @dec.bench + def test_bench_random(self): import numpy.linalg as linalg basic_solve = linalg.solve print @@ -174,19 +175,19 @@ for i in range(size): a[i,i] = 10*(.1+a[i,i]) b = random([size]) - print '| %6.2f ' % self.measure('solve(a,b)',repeat), + print '| %6.2f ' % measure('solve(a,b)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_solve(a,b)',repeat), + print '| %6.2f ' % measure('basic_solve(a,b)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] - print '| %6.2f ' % self.measure('solve(a,b)',repeat), + print '| %6.2f ' % measure('solve(a,b)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_solve(a,b)',repeat), + print '| %6.2f ' % measure('basic_solve(a,b)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -226,7 +227,8 @@ assert_array_almost_equal(numpy.dot(a,a_inv), numpy.identity(n)) - def bench_random(self,level=5): + @dec.bench + def test_bench_random(self): import numpy.linalg as linalg basic_inv = linalg.inv print @@ -245,19 +247,19 @@ # large diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i]) - print '| %6.2f ' % self.measure('inv(a)',repeat), + print '| %6.2f ' % measure('inv(a)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_inv(a)',repeat), + print '| %6.2f ' % measure('basic_inv(a)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] - print '| %6.2f ' % self.measure('inv(a)',repeat), + print '| %6.2f ' % measure('inv(a)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_inv(a)',repeat), + print '| %6.2f ' % measure('basic_inv(a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -295,7 +297,8 @@ d2 = basic_det(a) assert_almost_equal(d1,d2) - def bench_random(self,level=5): + @dec.bench + def test_bench_random(self): import numpy.linalg as linalg basic_det = linalg.det print @@ -312,19 +315,19 @@ a = random([size,size]) - print '| %6.2f ' % self.measure('det(a)',repeat), + print '| %6.2f ' % measure('det(a)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_det(a)',repeat), + print '| %6.2f ' % measure('basic_det(a)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] - print '| %6.2f ' % self.measure('det(a)',repeat), + print '| %6.2f ' % measure('det(a)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_det(a)',repeat), + print '| %6.2f ' % measure('basic_det(a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) Modified: branches/testing_cleanup/scipy/linalg/tests/test_decomp.py =================================================================== --- branches/testing_cleanup/scipy/linalg/tests/test_decomp.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/linalg/tests/test_decomp.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -9,9 +9,9 @@ Build linalg: python setup_linalg.py build Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' + python -c 'import scipy;scipy.linalg.test()' Run tests if linalg is not installed: - python tests/test_decomp.py [] + python tests/test_decomp.py """ import sys @@ -59,7 +59,8 @@ (9+1j-sqrt(92+6j))/2] assert_array_almost_equal(w,exact_w) - def bench_random(self,level=5): + @dec.bench + def test_bench_random(self): import numpy.linalg as linalg Numeric_eigvals = linalg.eigvals print @@ -76,7 +77,7 @@ a = random([size,size]) - print '| %6.2f ' % self.measure('eigvals(a)',repeat), + print '| %6.2f ' % measure('eigvals(a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) Modified: branches/testing_cleanup/scipy/ndimage/__init__.py =================================================================== --- branches/testing_cleanup/scipy/ndimage/__init__.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/ndimage/__init__.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -37,3 +37,6 @@ from info import __doc__ __version__ = '2.0' + +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: branches/testing_cleanup/scipy/optimize/tests/test_cobyla.py =================================================================== --- branches/testing_cleanup/scipy/optimize/tests/test_cobyla.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/optimize/tests/test_cobyla.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -5,7 +5,7 @@ from scipy.optimize import cobyla as co class TestCobyla(TestCase): - def test_simple(self, level=1): + def test_simple(self): function = lambda x: x[0]**2 + abs(x[1])**3 con1 = lambda x: x[0]**2 + x[1]**2 - 25 Modified: branches/testing_cleanup/scipy/optimize/tests/test_zeros.py =================================================================== --- branches/testing_cleanup/scipy/optimize/tests/test_zeros.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/optimize/tests/test_zeros.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -69,7 +69,8 @@ def test_brenth(self): self.run_check(cc.brenth, 'brenth') - def bench_run(self,level=5): + @dec.bench + def test_run(self): a = .5 b = sqrt(3) repeat = 2000 @@ -84,7 +85,7 @@ for j in range(len(methods)) : meth = methods[j] try: - t = self.measure("meth(func,a,b)",repeat) + t = measure("meth(func,a,b)",repeat) except: print '%s : failed'%mstrings[j] else: Modified: branches/testing_cleanup/scipy/sparse/tests/test_base.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_base.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/sparse/tests/test_base.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -8,9 +8,9 @@ Build sparse: python setup.py build Run tests if scipy is installed: - python -c 'import scipy;scipy.sparse.test()' + python -c 'import scipy;scipy.sparse.test()' Run tests if sparse is not installed: - python tests/test_sparse.py [] + python tests/test_sparse.py """ import numpy @@ -1282,7 +1282,7 @@ A = kron( [[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]] ) assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A) - def check_eliminate_zeros(self): + def test_eliminate_zeros(self): data = kron([1, 0, 0, 0, 2, 0, 3, 0], [[1,1],[1,1]]).T data = data.reshape(-1,2,2) indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) Modified: branches/testing_cleanup/scipy/sparse/tests/test_construct.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_construct.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/sparse/tests/test_construct.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -11,7 +11,7 @@ #TODO check whether format=XXX is respected class TestConstructUtils(TestCase): - def check_spdiags(self): + def test_spdiags(self): diags1 = array( [[ 1, 2, 3, 4, 5]] ) diags2 = array( [[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9,10]] ) Modified: branches/testing_cleanup/scipy/sparse/tests/test_sparse.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_sparse.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/sparse/tests/test_sparse.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -46,7 +46,8 @@ class TestSparseTools(TestCase): """Simple benchmarks for sparse matrix module""" - def bench_arithmetic(self): + @dec.bench + def test_arithmetic(self): matrices = [] #matrices.append( ('A','Identity', spidentity(500**2,format='csr')) ) matrices.append( ('A','Poisson5pt', poisson2d(500,format='csr')) ) @@ -93,8 +94,8 @@ print fmt % (format,operation,msec_per_it) - - def bench_sort(self): + @dec.bench + def test_sort(self): """sort CSR column indices""" matrices = [] matrices.append( ('Rand10', 1e4, 10) ) @@ -127,8 +128,8 @@ print fmt % (A.format,name,shape,A.nnz,1e3*(end-start)/float(iter) ) - - def bench_matvec(self): + @dec.bench + def test_matvec(self): matrices = [] matrices.append(('Identity', spidentity(10**4,format='dia'))) matrices.append(('Identity', spidentity(10**4,format='csr'))) @@ -174,8 +175,9 @@ MFLOPs = (2*A.nnz*iter/(end-start))/float(1e6) print fmt % (A.format,name,shape,A.nnz,MFLOPs) - - def bench_construction(self): + + @dec.bench + def test_construction(self): """build matrices by inserting single values""" matrices = [] matrices.append( ('Empty',csr_matrix((10000,10000))) ) @@ -210,8 +212,8 @@ print fmt % (format,name,shape,A.nnz,(end-start)/float(iter)) - - def bench_conversion(self): + @dec.bench + def test_conversion(self): A = poisson2d(100) formats = ['csr','csc','coo','lil','dok'] Added: branches/testing_cleanup/scipy/sparse/tests/test_spfuncs.py =================================================================== --- branches/testing_cleanup/scipy/sparse/tests/test_spfuncs.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/sparse/tests/test_spfuncs.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -0,0 +1,61 @@ +from numpy import array, kron +from scipy.testing import * + +from scipy.sparse.spfuncs import * +from scipy.sparse import csr_matrix, csc_matrix + +class TestSparseFunctions(TestCase): + def test_estimate_blocksize(self): + + mats = [] + mats.append( [[0,1],[1,0]] ) + mats.append( [[1,1,0],[0,0,1],[1,0,1]] ) + mats.append( [[0],[0],[1]] ) + mats = [array(x) for x in mats] + + blks = [] + blks.append( [[1]] ) + blks.append( [[1,1],[1,1]] ) + blks.append( [[1,1],[0,1]] ) + blks.append( [[1,1,0],[1,0,1],[1,1,1]] ) + blks = [array(x) for x in blks] + + for A in mats: + for B in blks: + X = kron(A,B) + r,c = estimate_blocksize(X) + assert(r >= B.shape[0]) + assert(c >= B.shape[1]) + + def test_count_blocks(self): + def gold(A,bs): + R,C = bs + I,J = A.nonzero() + return len( set( zip(I/R,J/C) ) ) + + mats = [] + mats.append( [[0]] ) + mats.append( [[1]] ) + mats.append( [[1,0]] ) + mats.append( [[1,1]] ) + mats.append( [[0,1],[1,0]] ) + mats.append( [[1,1,0],[0,0,1],[1,0,1]] ) + mats.append( [[0],[0],[1]] ) + + for A in mats: + for B in mats: + X = kron(A,B) + Y = csr_matrix(X) + for R in range(1,6): + for C in range(1,6): + assert_equal(count_blocks(Y,(R,C)),gold(X,(R,C))) + + X = kron([[1,1,0],[0,0,1],[1,0,1]],[[1,1]]) + Y = csc_matrix(X) + assert_equal(count_blocks(X,(1,2)),gold(X,(1,2))) + assert_equal(count_blocks(Y,(1,2)),gold(X,(1,2))) + + +if __name__ == "__main__": + unittests.main() + Modified: branches/testing_cleanup/scipy/stats/info.py =================================================================== --- branches/testing_cleanup/scipy/stats/info.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/stats/info.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -198,7 +198,7 @@ levene -- _ shapiro -- _ anderson -- _ -binom_test -- _ +binom_p -- _ fligner -- _ mood -- _ oneway -- _ Modified: branches/testing_cleanup/scipy/stats/morestats.py =================================================================== --- branches/testing_cleanup/scipy/stats/morestats.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/stats/morestats.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -21,7 +21,7 @@ __all__ = ['find_repeats', 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot', 'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot', - 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene', 'binom_test', + 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene', 'binom_p', 'fligner', 'mood', 'oneway', 'wilcoxon', 'pdf_moments', 'pdf_fromgamma', 'pdfapprox', 'circmean', 'circvar', 'circstd', @@ -769,7 +769,7 @@ pval = distributions.f.sf(W,k-1,Ntot-k) # 1 - cdf return W, pval -def binom_test(x,n=None,p=0.5): +def binom_p(x,n=None,p=0.5): """An exact (two-sided) test of the null hypothesis that the probability of success in a Bernoulli experiment is p. Modified: branches/testing_cleanup/scipy/stats/tests/test_distributions.py =================================================================== --- branches/testing_cleanup/scipy/stats/tests/test_distributions.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/stats/tests/test_distributions.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -2,7 +2,6 @@ """ - from scipy.testing import * @@ -10,9 +9,6 @@ from numpy import typecodes, array import scipy.stats as stats - -import types - def kolmogorov_check(diststr,args=(),N=20,significance=0.01): qtest = stats.ksoneisf(significance,N) cdf = eval('stats.'+diststr+'.cdf') @@ -41,9 +37,9 @@ # check function for test generator def check_distribution(dist, args, alpha): - D,pval = stats.kstest(dist,'',args=args, N=30) + D,pval = stats.kstest(dist,'', args=args, N=30) if (pval < alpha): - D,pval = stats.kstest(dit,'',args=args, N=30) + D,pval = stats.kstest(dist,'',args=args, N=30) #if (pval < alpha): # D,pval = stats.kstest(dist,'',args=args, N=30) assert (pval > alpha), "D = " + str(D) + "; pval = " + str(pval) + \ @@ -69,7 +65,7 @@ args = tuple(vals) else: args = tuple(1.0+rand(nargs)) - yield check_distribution, dist, args, alpha\ + yield check_distribution, dist, args, alpha class TestRandInt(TestCase): def test_rvs(self): Modified: branches/testing_cleanup/scipy/stats/tests/test_morestats.py =================================================================== --- branches/testing_cleanup/scipy/stats/tests/test_morestats.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/stats/tests/test_morestats.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -94,13 +94,13 @@ assert_almost_equal(W,1.7059176930008939,7) assert_almost_equal(pval,0.0990829755522,7) -class TestBinomTest(TestCase): +class TestBinomP(TestCase): def test_data(self): - pval = stats.binom_test(100,250) + pval = stats.binom_p(100,250) assert_almost_equal(pval,0.0018833009350757682,11) - pval = stats.binom_test(201,405) + pval = stats.binom_p(201,405) assert_almost_equal(pval,0.92085205962670713,11) - pval = stats.binom_test([682,243],p=3.0/4) + pval = stats.binom_p([682,243],p=3.0/4) assert_almost_equal(pval,0.38249155957481695,11) class TestFindRepeats(TestCase): Modified: branches/testing_cleanup/scipy/testing/decorators.py =================================================================== --- branches/testing_cleanup/scipy/testing/decorators.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/testing/decorators.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -1,8 +1,5 @@ """Decorators for labeling test objects.""" -''' String expression which is true for all undecorated tests ''' -undecorated_def = 'not slow' - def slow(t): """Labels a test as 'slow'. @@ -14,3 +11,11 @@ t.slow = True return t +def bench(t): + ''' Labels a test as a benchmark. + + Benchmark tests are often slow, and intended to test timings + between different algorithms rather than validity of the result. ''' + + t.bench = True + return t Modified: branches/testing_cleanup/scipy/testing/nosetester.py =================================================================== --- branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -4,10 +4,8 @@ import nose -from scipy.testing.decorators import undecorated_def - class NoseTester(object): - """ Scipy nose tests site manager. + """ Scipy nose tests suite manager. Usage: NoseTester().test() @@ -16,12 +14,11 @@ def __init__(self, package=None): if package is None: f = sys._getframe(1) - package = f.f_locals.get('__file__', - f.f_globals.get('__file__',None)) + package = f.f_locals.get('__file__', None) assert package is not None self.package_path = os.path.dirname(package) else: - self._process_package(package) + self.package_path = self._process_package(package) def _process_package(self, package): ''' Package can be module, path, or package name ''' @@ -30,11 +27,9 @@ except AttributeError: pass else: - self.package_path = os.path.dirname(pfile) - return + return os.path.dirname(pfile) if os.path.isabs(package): - self.package_path = package - return + return package if package.find(os.path.sep) == -1: # Try scipy package name import scipy @@ -50,14 +45,30 @@ self.package_path = os.path.abspath(package) return - def test(self, labels=None, verbose=0, extra_argv=None): - if labels is None: - labels = undecorated_def - argv = ['', self.package_path, '-s'] - if labels not in ('', 'all'): + def test(self, labels='fast', verbose=1, doctests=False, extra_argv=None): + ''' Module testing function + + labels - identifies tests to run. This can be a string to + pass to the nostests executable with the '-a' + option, or one of several special values. + Special values are: + 'fast' - the default - which corresponds to + nosetests -a option of 'not slow and not bench'. + None or '' - run all tests and benchmarks + + verbose - verbosity value 1-10 + doctests - if True, run doctests in module + extra_argv - list with any extra args to pass to nosetest + ''' + argv = ['scipy module test', self.package_path, '-s'] + if labels: + if labels == 'fast': + labels = 'not slow and not bench' argv += ['-A', labels] argv += ['--verbosity', str(verbose)] - if extra_argv is not None: + if doctests: + argv+=['--with-doctest'] + if extra_argv: argv+= extra_argv nose.run(argv=argv) Modified: branches/testing_cleanup/scipy/testing/pkgtester.py =================================================================== --- branches/testing_cleanup/scipy/testing/pkgtester.py 2008-01-08 06:19:19 UTC (rev 3798) +++ branches/testing_cleanup/scipy/testing/pkgtester.py 2008-01-08 10:16:05 UTC (rev 3799) @@ -1,7 +1,8 @@ ''' Define test function for scipy package ''' try: import nose - from scipy.testing.nosetester import NoseTester as Tester except ImportError: from scipy.testing.nulltester import NullTester as Tester +else: + from scipy.testing.nosetester import NoseTester as Tester From scipy-svn at scipy.org Tue Jan 8 14:15:48 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 13:15:48 -0600 (CST) Subject: [Scipy-svn] r3800 - in branches/testing_cleanup: . scipy/sandbox/multigrid scipy/sandbox/multigrid/multigridtools scipy/sandbox/multigrid/tests scipy/stats Message-ID: <20080108191548.CB26939C17A@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-08 13:15:40 -0600 (Tue, 08 Jan 2008) New Revision: 3800 Modified: branches/testing_cleanup/ branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools.i branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools.py branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools_wrap.cxx branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/relaxation.h branches/testing_cleanup/scipy/sandbox/multigrid/relaxation.py branches/testing_cleanup/scipy/sandbox/multigrid/tests/test_relaxation.py branches/testing_cleanup/scipy/stats/distributions.py Log: Merged revisions 3797-3798 via svnmerge from http://svn.scipy.org/svn/scipy/trunk ........ r3797 | dhuard | 2008-01-07 20:12:38 -0800 (Mon, 07 Jan 2008) | 1 line Fixed ticket 422 related to the generic computation of moments. ........ r3798 | wnbell | 2008-01-07 22:19:19 -0800 (Mon, 07 Jan 2008) | 2 lines added BSR gauss seidel method ........ Property changes on: branches/testing_cleanup ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3794 + /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3799 Modified: branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools.i =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools.i 2008-01-08 10:16:05 UTC (rev 3799) +++ branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools.i 2008-01-08 19:15:40 UTC (rev 3800) @@ -170,6 +170,7 @@ INSTANTIATE_BOTH(rs_strong_connections) INSTANTIATE_BOTH(rs_interpolation) INSTANTIATE_BOTH(sa_strong_connections) +INSTANTIATE_BOTH(block_gauss_seidel) INSTANTIATE_BOTH(gauss_seidel) INSTANTIATE_BOTH(jacobi) Modified: branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools.py 2008-01-08 10:16:05 UTC (rev 3799) +++ branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools.py 2008-01-08 19:15:40 UTC (rev 3800) @@ -90,23 +90,32 @@ """ return _multigridtools.sa_strong_connections(*args) +def block_gauss_seidel(*args): + """ + block_gauss_seidel(int Ap, int Aj, float Ax, float x, float b, int row_start, + int row_stop, int row_step, int blocksize) + block_gauss_seidel(int Ap, int Aj, double Ax, double x, double b, int row_start, + int row_stop, int row_step, int blocksize) + """ + return _multigridtools.block_gauss_seidel(*args) + def gauss_seidel(*args): """ - gauss_seidel(int n_row, int Ap, int Aj, float Ax, float x, float b, - int row_start, int row_stop, int row_step) - gauss_seidel(int n_row, int Ap, int Aj, double Ax, double x, double b, - int row_start, int row_stop, int row_step) + gauss_seidel(int Ap, int Aj, float Ax, float x, float b, int row_start, + int row_stop, int row_step) + gauss_seidel(int Ap, int Aj, double Ax, double x, double b, int row_start, + int row_stop, int row_step) """ return _multigridtools.gauss_seidel(*args) def jacobi(*args): """ - jacobi(int n_row, int Ap, int Aj, float Ax, float x, float b, - float temp, int row_start, int row_stop, - int row_step, float omega) - jacobi(int n_row, int Ap, int Aj, double Ax, double x, double b, - double temp, int row_start, int row_stop, - int row_step, double omega) + jacobi(int Ap, int Aj, float Ax, float x, float b, float temp, + int row_start, int row_stop, int row_step, + float omega) + jacobi(int Ap, int Aj, double Ax, double x, double b, double temp, + int row_start, int row_stop, int row_step, + double omega) """ return _multigridtools.jacobi(*args) Modified: branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools_wrap.cxx =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools_wrap.cxx 2008-01-08 10:16:05 UTC (rev 3799) +++ branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/multigridtools_wrap.cxx 2008-01-08 19:15:40 UTC (rev 3800) @@ -4457,28 +4457,28 @@ } -SWIGINTERN PyObject *_wrap_gauss_seidel__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { +SWIGINTERN PyObject *_wrap_block_gauss_seidel__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - int arg1 ; + int *arg1 ; int *arg2 ; - int *arg3 ; + float *arg3 ; float *arg4 ; float *arg5 ; - float *arg6 ; + int arg6 ; int arg7 ; int arg8 ; int arg9 ; - int val1 ; - int ecode1 = 0 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; PyArrayObject *array2 = NULL ; int is_new_object2 ; PyArrayObject *array3 = NULL ; int is_new_object3 ; - PyArrayObject *array4 = NULL ; - int is_new_object4 ; - PyArrayObject *temp5 = NULL ; - PyArrayObject *array6 = NULL ; - int is_new_object6 ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + int val6 ; + int ecode6 = 0 ; int val7 ; int ecode7 = 0 ; int val8 ; @@ -4495,16 +4495,21 @@ PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; - if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "gauss_seidel" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:block_gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) SWIG_fail; { npy_intp size[1] = { -1 }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; @@ -4515,106 +4520,101 @@ npy_intp size[1] = { -1 }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_FLOAT, &is_new_object3); if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - arg3 = (int*) array3->data; + arg3 = (float*) array3->data; } { - npy_intp size[1] = { - -1 - }; - array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_FLOAT, &is_new_object4); - if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) - || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; - - arg4 = (float*) array4->data; + temp4 = obj_to_array_no_conversion(obj3,PyArray_FLOAT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (float*) array_data(temp4); } { - temp5 = obj_to_array_no_conversion(obj4,PyArray_FLOAT); - if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; - arg5 = (float*) array_data(temp5); - } - { npy_intp size[1] = { -1 }; - array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_FLOAT, &is_new_object6); - if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) - || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_FLOAT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; - arg6 = (float*) array6->data; + arg5 = (float*) array5->data; } + ecode6 = SWIG_AsVal_int(obj5, &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "block_gauss_seidel" "', argument " "6"" of type '" "int""'"); + } + arg6 = static_cast< int >(val6); ecode7 = SWIG_AsVal_int(obj6, &val7); if (!SWIG_IsOK(ecode7)) { - SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "gauss_seidel" "', argument " "7"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "block_gauss_seidel" "', argument " "7"" of type '" "int""'"); } arg7 = static_cast< int >(val7); ecode8 = SWIG_AsVal_int(obj7, &val8); if (!SWIG_IsOK(ecode8)) { - SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "gauss_seidel" "', argument " "8"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "block_gauss_seidel" "', argument " "8"" of type '" "int""'"); } arg8 = static_cast< int >(val8); ecode9 = SWIG_AsVal_int(obj8, &val9); if (!SWIG_IsOK(ecode9)) { - SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "gauss_seidel" "', argument " "9"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "block_gauss_seidel" "', argument " "9"" of type '" "int""'"); } arg9 = static_cast< int >(val9); - gauss_seidel(arg1,(int const (*))arg2,(int const (*))arg3,(float const (*))arg4,arg5,(float const (*))arg6,arg7,arg8,arg9); + block_gauss_seidel((int const (*))arg1,(int const (*))arg2,(float const (*))arg3,arg4,(float const (*))arg5,arg6,arg7,arg8,arg9); resultobj = SWIG_Py_Void(); { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return resultobj; fail: { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return NULL; } -SWIGINTERN PyObject *_wrap_gauss_seidel__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { +SWIGINTERN PyObject *_wrap_block_gauss_seidel__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - int arg1 ; + int *arg1 ; int *arg2 ; - int *arg3 ; + double *arg3 ; double *arg4 ; double *arg5 ; - double *arg6 ; + int arg6 ; int arg7 ; int arg8 ; int arg9 ; - int val1 ; - int ecode1 = 0 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; PyArrayObject *array2 = NULL ; int is_new_object2 ; PyArrayObject *array3 = NULL ; int is_new_object3 ; - PyArrayObject *array4 = NULL ; - int is_new_object4 ; - PyArrayObject *temp5 = NULL ; - PyArrayObject *array6 = NULL ; - int is_new_object6 ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + int val6 ; + int ecode6 = 0 ; int val7 ; int ecode7 = 0 ; int val8 ; @@ -4631,16 +4631,21 @@ PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; - if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "gauss_seidel" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:block_gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) SWIG_fail; { npy_intp size[1] = { -1 }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; @@ -4651,85 +4656,80 @@ npy_intp size[1] = { -1 }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_DOUBLE, &is_new_object3); if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - arg3 = (int*) array3->data; + arg3 = (double*) array3->data; } { - npy_intp size[1] = { - -1 - }; - array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_DOUBLE, &is_new_object4); - if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) - || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; - - arg4 = (double*) array4->data; + temp4 = obj_to_array_no_conversion(obj3,PyArray_DOUBLE); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (double*) array_data(temp4); } { - temp5 = obj_to_array_no_conversion(obj4,PyArray_DOUBLE); - if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; - arg5 = (double*) array_data(temp5); - } - { npy_intp size[1] = { -1 }; - array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_DOUBLE, &is_new_object6); - if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) - || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_DOUBLE, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; - arg6 = (double*) array6->data; + arg5 = (double*) array5->data; } + ecode6 = SWIG_AsVal_int(obj5, &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "block_gauss_seidel" "', argument " "6"" of type '" "int""'"); + } + arg6 = static_cast< int >(val6); ecode7 = SWIG_AsVal_int(obj6, &val7); if (!SWIG_IsOK(ecode7)) { - SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "gauss_seidel" "', argument " "7"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "block_gauss_seidel" "', argument " "7"" of type '" "int""'"); } arg7 = static_cast< int >(val7); ecode8 = SWIG_AsVal_int(obj7, &val8); if (!SWIG_IsOK(ecode8)) { - SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "gauss_seidel" "', argument " "8"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "block_gauss_seidel" "', argument " "8"" of type '" "int""'"); } arg8 = static_cast< int >(val8); ecode9 = SWIG_AsVal_int(obj8, &val9); if (!SWIG_IsOK(ecode9)) { - SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "gauss_seidel" "', argument " "9"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "block_gauss_seidel" "', argument " "9"" of type '" "int""'"); } arg9 = static_cast< int >(val9); - gauss_seidel(arg1,(int const (*))arg2,(int const (*))arg3,(double const (*))arg4,arg5,(double const (*))arg6,arg7,arg8,arg9); + block_gauss_seidel((int const (*))arg1,(int const (*))arg2,(double const (*))arg3,arg4,(double const (*))arg5,arg6,arg7,arg8,arg9); resultobj = SWIG_Py_Void(); { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return resultobj; fail: { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return NULL; } -SWIGINTERN PyObject *_wrap_gauss_seidel(PyObject *self, PyObject *args) { +SWIGINTERN PyObject *_wrap_block_gauss_seidel(PyObject *self, PyObject *args) { int argc; PyObject *argv[10]; int ii; @@ -4742,8 +4742,7 @@ if (argc == 9) { int _v; { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; } if (_v) { { @@ -4751,7 +4750,7 @@ } if (_v) { { - _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_FLOAT)) ? 1 : 0; } if (_v) { { @@ -4763,7 +4762,8 @@ } if (_v) { { - _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_FLOAT)) ? 1 : 0; + int res = SWIG_AsVal_int(argv[5], NULL); + _v = SWIG_CheckState(res); } if (_v) { { @@ -4781,7 +4781,7 @@ _v = SWIG_CheckState(res); } if (_v) { - return _wrap_gauss_seidel__SWIG_1(self, args); + return _wrap_block_gauss_seidel__SWIG_1(self, args); } } } @@ -4795,8 +4795,7 @@ if (argc == 9) { int _v; { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; } if (_v) { { @@ -4804,7 +4803,7 @@ } if (_v) { { - _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_DOUBLE)) ? 1 : 0; } if (_v) { { @@ -4816,7 +4815,8 @@ } if (_v) { { - _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_DOUBLE)) ? 1 : 0; + int res = SWIG_AsVal_int(argv[5], NULL); + _v = SWIG_CheckState(res); } if (_v) { { @@ -4834,7 +4834,7 @@ _v = SWIG_CheckState(res); } if (_v) { - return _wrap_gauss_seidel__SWIG_2(self, args); + return _wrap_block_gauss_seidel__SWIG_2(self, args); } } } @@ -4847,44 +4847,406 @@ } fail: - SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'gauss_seidel'.\n Possible C/C++ prototypes are:\n"" gauss_seidel<(int,float)>(int const,int const [],int const [],float const [],float [],float const [],int const,int const,int const)\n"" gauss_seidel<(int,double)>(int const,int const [],int const [],double const [],double [],double const [],int const,int const,int const)\n"); + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'block_gauss_seidel'.\n Possible C/C++ prototypes are:\n"" block_gauss_seidel<(int,float)>(int const [],int const [],float const [],float [],float const [],int const,int const,int const,int const)\n"" block_gauss_seidel<(int,double)>(int const [],int const [],double const [],double [],double const [],int const,int const,int const,int const)\n"); return NULL; } +SWIGINTERN PyObject *_wrap_gauss_seidel__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int *arg1 ; + int *arg2 ; + float *arg3 ; + float *arg4 ; + float *arg5 ; + int arg6 ; + int arg7 ; + int arg8 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; + PyArrayObject *array2 = NULL ; + int is_new_object2 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + int val6 ; + int ecode6 = 0 ; + int val7 ; + int ecode7 = 0 ; + int val8 ; + int ecode8 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + { + npy_intp size[1] = { + -1 + }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; + array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); + if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) + || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; + + arg2 = (int*) array2->data; + } + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_FLOAT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (float*) array3->data; + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_FLOAT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (float*) array_data(temp4); + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_FLOAT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (float*) array5->data; + } + ecode6 = SWIG_AsVal_int(obj5, &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "gauss_seidel" "', argument " "6"" of type '" "int""'"); + } + arg6 = static_cast< int >(val6); + ecode7 = SWIG_AsVal_int(obj6, &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "gauss_seidel" "', argument " "7"" of type '" "int""'"); + } + arg7 = static_cast< int >(val7); + ecode8 = SWIG_AsVal_int(obj7, &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "gauss_seidel" "', argument " "8"" of type '" "int""'"); + } + arg8 = static_cast< int >(val8); + gauss_seidel((int const (*))arg1,(int const (*))arg2,(float const (*))arg3,arg4,(float const (*))arg5,arg6,arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { + if (is_new_object2 && array2) Py_DECREF(array2); + } + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + return resultobj; +fail: + { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { + if (is_new_object2 && array2) Py_DECREF(array2); + } + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_gauss_seidel__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int *arg1 ; + int *arg2 ; + double *arg3 ; + double *arg4 ; + double *arg5 ; + int arg6 ; + int arg7 ; + int arg8 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; + PyArrayObject *array2 = NULL ; + int is_new_object2 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + int val6 ; + int ecode6 = 0 ; + int val7 ; + int ecode7 = 0 ; + int val8 ; + int ecode8 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:gauss_seidel",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + { + npy_intp size[1] = { + -1 + }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; + array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); + if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) + || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; + + arg2 = (int*) array2->data; + } + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_DOUBLE, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (double*) array3->data; + } + { + temp4 = obj_to_array_no_conversion(obj3,PyArray_DOUBLE); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (double*) array_data(temp4); + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_DOUBLE, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (double*) array5->data; + } + ecode6 = SWIG_AsVal_int(obj5, &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "gauss_seidel" "', argument " "6"" of type '" "int""'"); + } + arg6 = static_cast< int >(val6); + ecode7 = SWIG_AsVal_int(obj6, &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "gauss_seidel" "', argument " "7"" of type '" "int""'"); + } + arg7 = static_cast< int >(val7); + ecode8 = SWIG_AsVal_int(obj7, &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "gauss_seidel" "', argument " "8"" of type '" "int""'"); + } + arg8 = static_cast< int >(val8); + gauss_seidel((int const (*))arg1,(int const (*))arg2,(double const (*))arg3,arg4,(double const (*))arg5,arg6,arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { + if (is_new_object2 && array2) Py_DECREF(array2); + } + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + return resultobj; +fail: + { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { + if (is_new_object2 && array2) Py_DECREF(array2); + } + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_gauss_seidel(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[9]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 8); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 8) { + int _v; + { + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[1]) && PyArray_CanCastSafely(PyArray_TYPE(argv[1]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[5], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[6], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[7], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + return _wrap_gauss_seidel__SWIG_1(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[1]) && PyArray_CanCastSafely(PyArray_TYPE(argv[1]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[5], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[6], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[7], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + return _wrap_gauss_seidel__SWIG_2(self, args); + } + } + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'gauss_seidel'.\n Possible C/C++ prototypes are:\n"" gauss_seidel<(int,float)>(int const [],int const [],float const [],float [],float const [],int const,int const,int const)\n"" gauss_seidel<(int,double)>(int const [],int const [],double const [],double [],double const [],int const,int const,int const)\n"); + return NULL; +} + + SWIGINTERN PyObject *_wrap_jacobi__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - int arg1 ; + int *arg1 ; int *arg2 ; - int *arg3 ; + float *arg3 ; float *arg4 ; float *arg5 ; float *arg6 ; - float *arg7 ; + int arg7 ; int arg8 ; int arg9 ; - int arg10 ; - float arg11 ; - int val1 ; - int ecode1 = 0 ; + float arg10 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; PyArrayObject *array2 = NULL ; int is_new_object2 ; PyArrayObject *array3 = NULL ; int is_new_object3 ; - PyArrayObject *array4 = NULL ; - int is_new_object4 ; - PyArrayObject *temp5 = NULL ; - PyArrayObject *array6 = NULL ; - int is_new_object6 ; - PyArrayObject *temp7 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *temp6 = NULL ; + int val7 ; + int ecode7 = 0 ; int val8 ; int ecode8 = 0 ; int val9 ; int ecode9 = 0 ; - int val10 ; + float val10 ; int ecode10 = 0 ; - float val11 ; - int ecode11 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; @@ -4895,18 +5257,22 @@ PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; PyObject * obj9 = 0 ; - PyObject * obj10 = 0 ; - if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOOO:jacobi",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9,&obj10)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "jacobi" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:jacobi",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; { npy_intp size[1] = { -1 }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; @@ -4917,42 +5283,37 @@ npy_intp size[1] = { -1 }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_FLOAT, &is_new_object3); if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - arg3 = (int*) array3->data; + arg3 = (float*) array3->data; } { - npy_intp size[1] = { - -1 - }; - array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_FLOAT, &is_new_object4); - if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) - || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; - - arg4 = (float*) array4->data; + temp4 = obj_to_array_no_conversion(obj3,PyArray_FLOAT); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (float*) array_data(temp4); } { - temp5 = obj_to_array_no_conversion(obj4,PyArray_FLOAT); - if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; - arg5 = (float*) array_data(temp5); - } - { npy_intp size[1] = { -1 }; - array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_FLOAT, &is_new_object6); - if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) - || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_FLOAT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; - arg6 = (float*) array6->data; + arg5 = (float*) array5->data; } { - temp7 = obj_to_array_no_conversion(obj6,PyArray_FLOAT); - if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; - arg7 = (float*) array_data(temp7); + temp6 = obj_to_array_no_conversion(obj5,PyArray_FLOAT); + if (!temp6 || !require_contiguous(temp6) || !require_native(temp6)) SWIG_fail; + arg6 = (float*) array_data(temp6); } + ecode7 = SWIG_AsVal_int(obj6, &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "jacobi" "', argument " "7"" of type '" "int""'"); + } + arg7 = static_cast< int >(val7); ecode8 = SWIG_AsVal_int(obj7, &val8); if (!SWIG_IsOK(ecode8)) { SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "jacobi" "', argument " "8"" of type '" "int""'"); @@ -4963,81 +5324,73 @@ SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "jacobi" "', argument " "9"" of type '" "int""'"); } arg9 = static_cast< int >(val9); - ecode10 = SWIG_AsVal_int(obj9, &val10); + ecode10 = SWIG_AsVal_float(obj9, &val10); if (!SWIG_IsOK(ecode10)) { - SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "jacobi" "', argument " "10"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "jacobi" "', argument " "10"" of type '" "float""'"); } - arg10 = static_cast< int >(val10); - ecode11 = SWIG_AsVal_float(obj10, &val11); - if (!SWIG_IsOK(ecode11)) { - SWIG_exception_fail(SWIG_ArgError(ecode11), "in method '" "jacobi" "', argument " "11"" of type '" "float""'"); - } - arg11 = static_cast< float >(val11); - jacobi(arg1,(int const (*))arg2,(int const (*))arg3,(float const (*))arg4,arg5,(float const (*))arg6,arg7,arg8,arg9,arg10,arg11); + arg10 = static_cast< float >(val10); + jacobi((int const (*))arg1,(int const (*))arg2,(float const (*))arg3,arg4,(float const (*))arg5,arg6,arg7,arg8,arg9,arg10); resultobj = SWIG_Py_Void(); { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return resultobj; fail: { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return NULL; } SWIGINTERN PyObject *_wrap_jacobi__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; - int arg1 ; + int *arg1 ; int *arg2 ; - int *arg3 ; + double *arg3 ; double *arg4 ; double *arg5 ; double *arg6 ; - double *arg7 ; + int arg7 ; int arg8 ; int arg9 ; - int arg10 ; - double arg11 ; - int val1 ; - int ecode1 = 0 ; + double arg10 ; + PyArrayObject *array1 = NULL ; + int is_new_object1 ; PyArrayObject *array2 = NULL ; int is_new_object2 ; PyArrayObject *array3 = NULL ; int is_new_object3 ; - PyArrayObject *array4 = NULL ; - int is_new_object4 ; - PyArrayObject *temp5 = NULL ; - PyArrayObject *array6 = NULL ; - int is_new_object6 ; - PyArrayObject *temp7 = NULL ; + PyArrayObject *temp4 = NULL ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *temp6 = NULL ; + int val7 ; + int ecode7 = 0 ; int val8 ; int ecode8 = 0 ; int val9 ; int ecode9 = 0 ; - int val10 ; + double val10 ; int ecode10 = 0 ; - double val11 ; - int ecode11 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; @@ -5048,18 +5401,22 @@ PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; PyObject * obj9 = 0 ; - PyObject * obj10 = 0 ; - if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOOO:jacobi",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9,&obj10)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "jacobi" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:jacobi",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; { npy_intp size[1] = { -1 }; + array1 = obj_to_array_contiguous_allow_conversion(obj0, PyArray_INT, &is_new_object1); + if (!array1 || !require_dimensions(array1,1) || !require_size(array1,size,1) + || !require_contiguous(array1) || !require_native(array1)) SWIG_fail; + + arg1 = (int*) array1->data; + } + { + npy_intp size[1] = { + -1 + }; array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; @@ -5070,42 +5427,37 @@ npy_intp size[1] = { -1 }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_DOUBLE, &is_new_object3); if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - arg3 = (int*) array3->data; + arg3 = (double*) array3->data; } { - npy_intp size[1] = { - -1 - }; - array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_DOUBLE, &is_new_object4); - if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) - || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; - - arg4 = (double*) array4->data; + temp4 = obj_to_array_no_conversion(obj3,PyArray_DOUBLE); + if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; + arg4 = (double*) array_data(temp4); } { - temp5 = obj_to_array_no_conversion(obj4,PyArray_DOUBLE); - if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; - arg5 = (double*) array_data(temp5); - } - { npy_intp size[1] = { -1 }; - array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_DOUBLE, &is_new_object6); - if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) - || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_DOUBLE, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; - arg6 = (double*) array6->data; + arg5 = (double*) array5->data; } { - temp7 = obj_to_array_no_conversion(obj6,PyArray_DOUBLE); - if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; - arg7 = (double*) array_data(temp7); + temp6 = obj_to_array_no_conversion(obj5,PyArray_DOUBLE); + if (!temp6 || !require_contiguous(temp6) || !require_native(temp6)) SWIG_fail; + arg6 = (double*) array_data(temp6); } + ecode7 = SWIG_AsVal_int(obj6, &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "jacobi" "', argument " "7"" of type '" "int""'"); + } + arg7 = static_cast< int >(val7); ecode8 = SWIG_AsVal_int(obj7, &val8); if (!SWIG_IsOK(ecode8)) { SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "jacobi" "', argument " "8"" of type '" "int""'"); @@ -5116,63 +5468,57 @@ SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "jacobi" "', argument " "9"" of type '" "int""'"); } arg9 = static_cast< int >(val9); - ecode10 = SWIG_AsVal_int(obj9, &val10); + ecode10 = SWIG_AsVal_double(obj9, &val10); if (!SWIG_IsOK(ecode10)) { - SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "jacobi" "', argument " "10"" of type '" "int""'"); + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "jacobi" "', argument " "10"" of type '" "double""'"); } - arg10 = static_cast< int >(val10); - ecode11 = SWIG_AsVal_double(obj10, &val11); - if (!SWIG_IsOK(ecode11)) { - SWIG_exception_fail(SWIG_ArgError(ecode11), "in method '" "jacobi" "', argument " "11"" of type '" "double""'"); - } - arg11 = static_cast< double >(val11); - jacobi(arg1,(int const (*))arg2,(int const (*))arg3,(double const (*))arg4,arg5,(double const (*))arg6,arg7,arg8,arg9,arg10,arg11); + arg10 = static_cast< double >(val10); + jacobi((int const (*))arg1,(int const (*))arg2,(double const (*))arg3,arg4,(double const (*))arg5,arg6,arg7,arg8,arg9,arg10); resultobj = SWIG_Py_Void(); { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return resultobj; fail: { + if (is_new_object1 && array1) Py_DECREF(array1); + } + { if (is_new_object2 && array2) Py_DECREF(array2); } { if (is_new_object3 && array3) Py_DECREF(array3); } { - if (is_new_object4 && array4) Py_DECREF(array4); + if (is_new_object5 && array5) Py_DECREF(array5); } - { - if (is_new_object6 && array6) Py_DECREF(array6); - } return NULL; } SWIGINTERN PyObject *_wrap_jacobi(PyObject *self, PyObject *args) { int argc; - PyObject *argv[12]; + PyObject *argv[11]; int ii; if (!PyTuple_Check(args)) SWIG_fail; argc = (int)PyObject_Length(args); - for (ii = 0; (ii < argc) && (ii < 11); ii++) { + for (ii = 0; (ii < argc) && (ii < 10); ii++) { argv[ii] = PyTuple_GET_ITEM(args,ii); } - if (argc == 11) { + if (argc == 10) { int _v; { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; } if (_v) { { @@ -5180,7 +5526,7 @@ } if (_v) { { - _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_FLOAT)) ? 1 : 0; } if (_v) { { @@ -5196,7 +5542,8 @@ } if (_v) { { - _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_FLOAT)) ? 1 : 0; + int res = SWIG_AsVal_int(argv[6], NULL); + _v = SWIG_CheckState(res); } if (_v) { { @@ -5210,17 +5557,11 @@ } if (_v) { { - int res = SWIG_AsVal_int(argv[9], NULL); + int res = SWIG_AsVal_float(argv[9], NULL); _v = SWIG_CheckState(res); } if (_v) { - { - int res = SWIG_AsVal_float(argv[10], NULL); - _v = SWIG_CheckState(res); - } - if (_v) { - return _wrap_jacobi__SWIG_1(self, args); - } + return _wrap_jacobi__SWIG_1(self, args); } } } @@ -5232,11 +5573,10 @@ } } } - if (argc == 11) { + if (argc == 10) { int _v; { - int res = SWIG_AsVal_int(argv[0], NULL); - _v = SWIG_CheckState(res); + _v = (is_array(argv[0]) && PyArray_CanCastSafely(PyArray_TYPE(argv[0]),PyArray_INT)) ? 1 : 0; } if (_v) { { @@ -5244,7 +5584,7 @@ } if (_v) { { - _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_DOUBLE)) ? 1 : 0; } if (_v) { { @@ -5260,7 +5600,8 @@ } if (_v) { { - _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_DOUBLE)) ? 1 : 0; + int res = SWIG_AsVal_int(argv[6], NULL); + _v = SWIG_CheckState(res); } if (_v) { { @@ -5274,17 +5615,11 @@ } if (_v) { { - int res = SWIG_AsVal_int(argv[9], NULL); + int res = SWIG_AsVal_double(argv[9], NULL); _v = SWIG_CheckState(res); } if (_v) { - { - int res = SWIG_AsVal_double(argv[10], NULL); - _v = SWIG_CheckState(res); - } - if (_v) { - return _wrap_jacobi__SWIG_2(self, args); - } + return _wrap_jacobi__SWIG_2(self, args); } } } @@ -5298,7 +5633,7 @@ } fail: - SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'jacobi'.\n Possible C/C++ prototypes are:\n"" jacobi<(int,float)>(int const,int const [],int const [],float const [],float [],float const [],float [],int const,int const,int const,float const)\n"" jacobi<(int,double)>(int const,int const [],int const [],double const [],double [],double const [],double [],int const,int const,int const,double const)\n"); + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'jacobi'.\n Possible C/C++ prototypes are:\n"" jacobi<(int,float)>(int const [],int const [],float const [],float [],float const [],float [],int const,int const,int const,float const)\n"" jacobi<(int,double)>(int const [],int const [],double const [],double [],double const [],double [],int const,int const,int const,double const)\n"); return NULL; } @@ -5329,19 +5664,25 @@ " std::vector<(int)> Sp, std::vector<(int)> Sj, \n" " std::vector<(double)> Sx)\n" ""}, + { (char *)"block_gauss_seidel", _wrap_block_gauss_seidel, METH_VARARGS, (char *)"\n" + "block_gauss_seidel(int Ap, int Aj, float Ax, float x, float b, int row_start, \n" + " int row_stop, int row_step, int blocksize)\n" + "block_gauss_seidel(int Ap, int Aj, double Ax, double x, double b, int row_start, \n" + " int row_stop, int row_step, int blocksize)\n" + ""}, { (char *)"gauss_seidel", _wrap_gauss_seidel, METH_VARARGS, (char *)"\n" - "gauss_seidel(int n_row, int Ap, int Aj, float Ax, float x, float b, \n" - " int row_start, int row_stop, int row_step)\n" - "gauss_seidel(int n_row, int Ap, int Aj, double Ax, double x, double b, \n" - " int row_start, int row_stop, int row_step)\n" + "gauss_seidel(int Ap, int Aj, float Ax, float x, float b, int row_start, \n" + " int row_stop, int row_step)\n" + "gauss_seidel(int Ap, int Aj, double Ax, double x, double b, int row_start, \n" + " int row_stop, int row_step)\n" ""}, { (char *)"jacobi", _wrap_jacobi, METH_VARARGS, (char *)"\n" - "jacobi(int n_row, int Ap, int Aj, float Ax, float x, float b, \n" - " float temp, int row_start, int row_stop, \n" - " int row_step, float omega)\n" - "jacobi(int n_row, int Ap, int Aj, double Ax, double x, double b, \n" - " double temp, int row_start, int row_stop, \n" - " int row_step, double omega)\n" + "jacobi(int Ap, int Aj, float Ax, float x, float b, float temp, \n" + " int row_start, int row_stop, int row_step, \n" + " float omega)\n" + "jacobi(int Ap, int Aj, double Ax, double x, double b, double temp, \n" + " int row_start, int row_stop, int row_step, \n" + " double omega)\n" ""}, { NULL, NULL, 0, NULL } }; Modified: branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/relaxation.h =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/relaxation.h 2008-01-08 10:16:05 UTC (rev 3799) +++ branches/testing_cleanup/scipy/sandbox/multigrid/multigridtools/relaxation.h 2008-01-08 19:15:40 UTC (rev 3800) @@ -5,8 +5,7 @@ #include template -void gauss_seidel(const I n_row, - const I Ap[], +void gauss_seidel(const I Ap[], const I Aj[], const T Ax[], T x[], @@ -36,9 +35,59 @@ } } + template -void jacobi(const I n_row, - const I Ap[], +void block_gauss_seidel(const I Ap[], + const I Aj[], + const T Ax[], + T x[], + const T b[], + const I row_start, + const I row_stop, + const I row_step, + const I blocksize) +{ + const I B2 = blocksize * blocksize; + + for(I i = row_start; i != row_stop; i += row_step) { + I start = Ap[i]; + I end = Ap[i+1]; + + for(I bi = 0; bi < blocksize; bi++){ + T rsum = 0; + T diag = 0; + + for(I jj = start; jj < end; jj++){ + I j = Aj[jj]; + const T * block_row = Ax + B2*jj + blocksize*bi; + const T * block_x = x + blocksize * j; + + if (i == j){ + //diagonal block + diag = block_row[bi]; + for(I bj = 0; bj < bi; bj++){ + rsum += block_row[bj] * block_x[bj]; + } + for(I bj = bi+1; bj < blocksize; bj++){ + rsum += block_row[bj] * block_x[bj]; + } + } else { + for(I bj = 0; bj < blocksize; bj++){ + rsum += block_row[bj] * block_x[bj]; + } + } + } + + //TODO raise error? inform user? + if (diag != 0){ + x[blocksize*i + bi] = (b[blocksize*i + bi] - rsum)/diag; + } + } + } +} + +template +void jacobi(const I Ap[], const I Aj[], const T Ax[], T x[], @@ -49,7 +98,9 @@ const I row_step, const T omega) { - std::copy(x,x+n_row,temp); + for(I i = row_start; i != row_stop; i += row_step) { + temp[i] = x[i]; + } for(I i = row_start; i != row_stop; i += row_step) { I start = Ap[i]; Modified: branches/testing_cleanup/scipy/sandbox/multigrid/relaxation.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/relaxation.py 2008-01-08 10:16:05 UTC (rev 3799) +++ branches/testing_cleanup/scipy/sandbox/multigrid/relaxation.py 2008-01-08 19:15:40 UTC (rev 3800) @@ -1,7 +1,30 @@ +from warnings import warn + +from numpy import empty_like, asarray, arange, ravel + import multigridtools -from numpy import empty_like, asarray +from scipy.sparse import isspmatrix_csr, isspmatrix_csc, isspmatrix_bsr, \ + csr_matrix, coo_matrix, bsr_matrix, SparseEfficiencyWarning +#def split_ldu(A): +# """ +# Return the lower triangle, diagonal, and upper triangular portions of a matrix. +# """ +# if isspmatrix_csr(A) or isspmatrix_csc(A): +# coo = A.tocoo(copy=False) +# elif isspmatrix_bsr(A): +# M,N = A.shape +# R,C = A.blocksize +# data = arange(len(A.indices),dtype='intc') +# proxy = csr_matrix((data,A.indices,A.indptr),shape=(M/R,N/C)) +# L,D,U = split_ldu(proxy) +# L = bsr_matrix((A.data[L.data],L.indices,L.indptr),shape=A.shape) +# U = bsr_matrix((A.data[U.data],U.indices,U.indptr),shape=A.shape) +# D = A.data[D] + + + def sor(A,x,b,omega,iterations=1,sweep='forward'): """ Perform SOR iteration on the linear system Ax=b @@ -30,37 +53,58 @@ sweep - direction of sweep: 'forward' (default), 'backward', or 'symmetric' """ - x = asarray(x).reshape(-1) - b = asarray(b).reshape(-1) + #TODO replace pointwise BSR with block BSR + x = x.reshape(-1) #TODO warn if not inplace + b = ravel(b) + + if isspmatrix_csr(A): + pass + elif isspmatrix_bsr(A): + R,C = A.blocksize + if R != C: + raise ValueError,'BSR blocks must be square' + else: + warn('implicit conversion to CSR',SparseEfficiencyWarning) + A = csr_matrix(A) + if A.shape[0] != A.shape[1]: - raise ValueError,'expected symmetric matrix' + raise ValueError,'expected square matrix' if A.shape[1] != len(x) or len(x) != len(b): raise ValueError,'unexpected number of unknowns' + + if sweep == 'forward': row_start,row_stop,row_step = 0,len(x),1 - for iter in xrange(iterations): - multigridtools.gauss_seidel(A.shape[0], - A.indptr, A.indices, A.data, - x, b, - row_start, row_stop, row_step) elif sweep == 'backward': - row_start,row_stop,row_step = len(x)-1,-1,-1 - for iter in xrange(iterations): - multigridtools.gauss_seidel(A.shape[0], - A.indptr, A.indices, A.data, - x, b, - row_start, row_stop, row_step) + row_start,row_stop,row_step = len(x)-1,-1,-1 elif sweep == 'symmetric': for iter in xrange(iterations): gauss_seidel(A,x,b,iterations=1,sweep='forward') gauss_seidel(A,x,b,iterations=1,sweep='backward') + return else: raise ValueError,'valid sweep directions are \'forward\', \'backward\', and \'symmetric\'' + if isspmatrix_csr(A): + for iter in xrange(iterations): + multigridtools.gauss_seidel(A.indptr, A.indices, A.data, + x, b, + row_start, row_stop, row_step) + else: + blocksize = A.blocksize[0] + row_start = row_start/blocksize + row_stop = row_stop/blocksize + for iter in xrange(iterations): + multigridtools.block_gauss_seidel(A.indptr, A.indices, ravel(A.data), + x, b, + row_start, row_stop, row_step, + blocksize) + + def jacobi(A,x,b,iterations=1,omega=1.0): """ Perform Jacobi iteration on the linear system Ax=b @@ -89,8 +133,7 @@ temp = empty_like(x) for iter in xrange(iterations): - multigridtools.jacobi(A.shape[0], - A.indptr, A.indices, A.data, + multigridtools.jacobi(A.indptr, A.indices, A.data, x, b, temp, row_start, row_stop, row_step, omega) Modified: branches/testing_cleanup/scipy/sandbox/multigrid/tests/test_relaxation.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-08 10:16:05 UTC (rev 3799) +++ branches/testing_cleanup/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-08 19:15:40 UTC (rev 3800) @@ -2,7 +2,7 @@ import numpy import scipy -from scipy import arange,ones,zeros,array,allclose +from scipy import arange,ones,zeros,array,allclose,zeros_like from scipy.sparse import spdiags @@ -15,7 +15,7 @@ class TestRelaxation(TestCase): def test_polynomial(self): N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x0 = arange(N).astype(numpy.float64) x = x0.copy() b = zeros(N) @@ -39,87 +39,105 @@ def test_jacobi(self): N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) jacobi(A,x,b) assert_almost_equal(x,array([0])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = zeros(N) b = arange(N).astype(numpy.float64) jacobi(A,x,b) assert_almost_equal(x,array([0.0,0.5,1.0])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) jacobi(A,x,b) assert_almost_equal(x,array([0.5,1.0,0.5])) N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = array([10]) jacobi(A,x,b) assert_almost_equal(x,array([5])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = array([10,20,30]) jacobi(A,x,b) assert_almost_equal(x,array([5.5,11.0,15.5])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) x_copy = x.copy() b = array([10,20,30]) jacobi(A,x,b,omega=1.0/3.0) assert_almost_equal(x,2.0/3.0*x_copy + 1.0/3.0*array([5.5,11.0,15.5])) + def test_gauss_seidel_bsr(self): + cases = [] - def test_gauss_seidel(self): + for N in [1,2,3,4,5,6,10]: + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).tocsr() + + divisors = [ n for n in range(1,N+1) if N % n == 0 ] + + x_csr = arange(N).astype(numpy.float64) + b = x_csr**2 + gauss_seidel(A,x_csr,b) + + for D in divisors: + B = A.tobsr(blocksize=(D,D)) + x_bsr = arange(N).astype(numpy.float64) + gauss_seidel(B,x_bsr,b) + assert_almost_equal(x_bsr,x_csr) + + + def test_gauss_seidel_csr(self): N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) gauss_seidel(A,x,b) assert_almost_equal(x,array([0])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) gauss_seidel(A,x,b) assert_almost_equal(x,array([1.0/2.0,5.0/4.0,5.0/8.0])) N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) gauss_seidel(A,x,b,sweep='backward') assert_almost_equal(x,array([0])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = zeros(N) gauss_seidel(A,x,b,sweep='backward') assert_almost_equal(x,array([1.0/8.0,1.0/4.0,1.0/2.0])) N = 1 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = array([10]) gauss_seidel(A,x,b) assert_almost_equal(x,array([5])) N = 3 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) b = array([10,20,30]) gauss_seidel(A,x,b) @@ -128,7 +146,7 @@ #forward and backward passes should give same result with x=ones(N),b=zeros(N) N = 100 - A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N).T + A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = ones(N) b = zeros(N) gauss_seidel(A,x,b,iterations=200,sweep='forward') Modified: branches/testing_cleanup/scipy/stats/distributions.py =================================================================== --- branches/testing_cleanup/scipy/stats/distributions.py 2008-01-08 10:16:05 UTC (rev 3799) +++ branches/testing_cleanup/scipy/stats/distributions.py 2008-01-08 19:15:40 UTC (rev 3800) @@ -303,15 +303,17 @@ self.vecentropy = sgf(self._entropy,otypes='d') self.veccdf = sgf(self._cdf_single_call,otypes='d') self.expandarr = 1 - if momtype == 0: - self.generic_moment = sgf(self._mom0_sc,otypes='d') - else: - self.generic_moment = sgf(self._mom1_sc,otypes='d') cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2) + if momtype == 0: + self.generic_moment = sgf(self._mom0_sc,otypes='d') + else: + self.generic_moment = sgf(self._mom1_sc,otypes='d') + self.generic_moment.nin = self.numargs+1 # Because of the *args argument + # of _mom0_sc, vectorize cannot count the number of arguments correctly. if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " From scipy-svn at scipy.org Tue Jan 8 14:37:05 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 13:37:05 -0600 (CST) Subject: [Scipy-svn] r3801 - trunk/scipy/sandbox/timeseries Message-ID: <20080108193705.33C97C7C037@new.scipy.org> Author: dhuard Date: 2008-01-08 13:36:52 -0600 (Tue, 08 Jan 2008) New Revision: 3801 Modified: trunk/scipy/sandbox/timeseries/dates.py trunk/scipy/sandbox/timeseries/trecords.py Log: Fixed bug in fromtextfile Modified: trunk/scipy/sandbox/timeseries/dates.py =================================================================== --- trunk/scipy/sandbox/timeseries/dates.py 2008-01-08 19:15:40 UTC (rev 3800) +++ trunk/scipy/sandbox/timeseries/dates.py 2008-01-08 19:36:52 UTC (rev 3801) @@ -562,6 +562,40 @@ fcode = _c.FR_UND return fcode +def guess_freq_date(dates): + """Tries to estimate the frequency of a sequence of datetime objects.""" + if not type(dates[0]) is dt.datetime: + raise AttributeError, "dates not a sequence of datetime objects." + + sorted_dates = numpy.sort(dates) + ddif = numpy.diff(sorted_dates) + dset = set(ddif) + try: + dset.remove(dt.timedelta(0)) + except: + pass + res = min(dset) + if getattr(res, 'seconds', 0) >= 1: + fcode = _c.FR_SEC + elif getattr(res, 'seconds', 0) >= 60: + fcode = _c.FR_MIN + elif getattr(res, 'seconds', 0) >= 60*60: + fcode = _c.FR_HR + elif getattr(res, 'day', 0) >= 1: + fcode = _c.FR_DAY + elif getattr(res, 'day', 0) >= 7: + fcode = _c.FR_WK + elif getattr(res, 'month', 0) >= 1: + fcode = _c.FR_MTH + elif getattr(res, 'month', 0) >= 3: + fcode = _c.FR_QTR + elif getattr(res, 'year', 0) >= 1: + fcode = _c.FR_ANN + else: + warnings.warn("Unable to estimate the frequency! %s" % res.__str__()) + fcode = _c.FR_UND + return fcode + def _listparser(dlist, freq=None): "Constructs a DateArray from a list." @@ -578,7 +612,10 @@ ords += 1 #...try to guess the frequency if freq is None or freq == _c.FR_UND: - freq = guess_freq(ords) + freq = guess_freq(ords) + if freq == _c.FR_UND: + dtobj = [DateTimeFromString(s) for s in dlist] + freq = guess_freq_date(dtobj) #...construct a list of dates for s in dlist: x = Date(freq, string=s) Modified: trunk/scipy/sandbox/timeseries/trecords.py =================================================================== --- trunk/scipy/sandbox/timeseries/trecords.py 2008-01-08 19:15:40 UTC (rev 3800) +++ trunk/scipy/sandbox/timeseries/trecords.py 2008-01-08 19:36:52 UTC (rev 3801) @@ -494,10 +494,14 @@ # newdates = __getdates(dates=dates, newdates=newdates, length=nvars, freq=None, start_date=None) - return TimeSeriesRecords(_datalist, dates=newdates, dtype=mdescr) + # Sort the datalist according to newdates._unsorted + idx = newdates._unsorted + _sorted_datalist = [a[idx] for a in _datalist] + return TimeSeriesRecords(_sorted_datalist, dates=newdates, dtype=mdescr) + ################################################################################ if __name__ == '__main__': import numpy as N From scipy-svn at scipy.org Tue Jan 8 15:14:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 14:14:20 -0600 (CST) Subject: [Scipy-svn] r3802 - branches Message-ID: <20080108201420.8FBA639C3EB@new.scipy.org> Author: chris.burns Date: 2008-01-08 14:14:01 -0600 (Tue, 08 Jan 2008) New Revision: 3802 Added: branches/ndimage-register/ Log: Create branch for image registration code. Copied: branches/ndimage-register (from rev 3801, trunk/scipy/ndimage) From scipy-svn at scipy.org Tue Jan 8 17:52:23 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 16:52:23 -0600 (CST) Subject: [Scipy-svn] r3803 - in branches/testing_cleanup/scipy: cluster/tests weave/tests Message-ID: <20080108225223.1525A39C115@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-08 16:52:05 -0600 (Tue, 08 Jan 2008) New Revision: 3803 Modified: branches/testing_cleanup/scipy/cluster/tests/test_vq.py branches/testing_cleanup/scipy/weave/tests/test_c_spec.py branches/testing_cleanup/scipy/weave/tests/test_ext_tools.py branches/testing_cleanup/scipy/weave/tests/test_inline_tools.py branches/testing_cleanup/scipy/weave/tests/test_numpy_scalar_spec.py branches/testing_cleanup/scipy/weave/tests/test_scxx_dict.py branches/testing_cleanup/scipy/weave/tests/test_scxx_object.py branches/testing_cleanup/scipy/weave/tests/test_scxx_sequence.py branches/testing_cleanup/scipy/weave/tests/test_size_check.py branches/testing_cleanup/scipy/weave/tests/test_slice_handler.py branches/testing_cleanup/scipy/weave/tests/test_wx_spec.py Log: Moving over weave tests Modified: branches/testing_cleanup/scipy/cluster/tests/test_vq.py =================================================================== --- branches/testing_cleanup/scipy/cluster/tests/test_vq.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/cluster/tests/test_vq.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -131,7 +131,7 @@ code1 = kmeans2(data1, code, iter = 1)[0] code2 = kmeans2(data1, code, iter = 2)[0] - def test_kmeans2_init(self, level = 1): + def test_kmeans2_init(self): """Testing that kmeans2 init methods work.""" data = N.fromfile(open(DATAFILE1), sep = ", ") data = data.reshape((200, 2)) Modified: branches/testing_cleanup/scipy/weave/tests/test_c_spec.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_c_spec.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_c_spec.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -66,19 +66,24 @@ class IntConverter(TestCase): compiler = '' - def test_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): s = c_spec.int_converter() assert( not s.type_match('string') ) - def test_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): s = c_spec.int_converter() assert(s.type_match(5)) - def test_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): s = c_spec.int_converter() assert(not s.type_match(5.)) - def test_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): s = c_spec.int_converter() assert(not s.type_match(5.+1j)) - def test_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'int_var_in' + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -101,7 +106,8 @@ except TypeError: pass - def test_int_return(self,level=5): + @dec.slow + def test_int_return(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -121,19 +127,24 @@ class FloatConverter(TestCase): compiler = '' - def test_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): s = c_spec.float_converter() assert( not s.type_match('string')) - def test_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): s = c_spec.float_converter() assert(not s.type_match(5)) - def test_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): s = c_spec.float_converter() assert(s.type_match(5.)) - def test_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): s = c_spec.float_converter() assert(not s.type_match(5.+1j)) - def test_float_var_in(self,level=5): + @dec.slow + def test_float_var_in(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -157,7 +168,8 @@ pass - def test_float_return(self,level=5): + @dec.slow + def test_float_return(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -176,19 +188,24 @@ class ComplexConverter(TestCase): compiler = '' - def test_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): s = c_spec.complex_converter() assert( not s.type_match('string') ) - def test_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): s = c_spec.complex_converter() assert(not s.type_match(5)) - def test_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): s = c_spec.complex_converter() assert(not s.type_match(5.)) - def test_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): s = c_spec.complex_converter() assert(s.type_match(5.+1j)) - def test_complex_var_in(self,level=5): + @dec.slow + def test_complex_var_in(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -211,7 +228,8 @@ except TypeError: pass - def test_complex_return(self,level=5): + @dec.slow + def test_complex_return(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -234,7 +252,8 @@ class FileConverter(TestCase): compiler = '' - def test_py_to_file(self,level=5): + @dec.slow + def test_py_to_file(self): import tempfile file_name = tempfile.mktemp() file = open(file_name,'w') @@ -245,7 +264,8 @@ file.close() file = open(file_name,'r') assert(file.read() == "hello bob") - def test_file_to_py(self,level=5): + @dec.slow + def test_file_to_py(self): import tempfile file_name = tempfile.mktemp() # not sure I like Py::String as default -- might move to std::sting @@ -275,7 +295,8 @@ class CallableConverter(TestCase): compiler='' - def test_call_function(self,level=5): + @dec.slow + def test_call_function(self): import string func = string.find search_str = "hello world hello" @@ -295,34 +316,43 @@ class SequenceConverter(TestCase): compiler = '' - def test_convert_to_dict(self,level=5): + @dec.slow + def test_convert_to_dict(self): d = {} inline_tools.inline("",['d'],compiler=self.compiler,force=1) - def test_convert_to_list(self,level=5): + @dec.slow + def test_convert_to_list(self): l = [] inline_tools.inline("",['l'],compiler=self.compiler,force=1) - def test_convert_to_string(self,level=5): + @dec.slow + def test_convert_to_string(self): s = 'hello' inline_tools.inline("",['s'],compiler=self.compiler,force=1) - def test_convert_to_tuple(self,level=5): + @dec.slow + def test_convert_to_tuple(self): t = () inline_tools.inline("",['t'],compiler=self.compiler,force=1) class StringConverter(TestCase): compiler = '' - def test_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): s = c_spec.string_converter() assert( s.type_match('string') ) - def test_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): s = c_spec.string_converter() assert(not s.type_match(5)) - def test_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): s = c_spec.string_converter() assert(not s.type_match(5.)) - def test_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): s = c_spec.string_converter() assert(not s.type_match(5.+1j)) - def test_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'string_var_in'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -346,7 +376,8 @@ except TypeError: pass - def test_return(self,level=5): + @dec.slow + def test_return(self): mod_name = 'string_return'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -365,15 +396,18 @@ class ListConverter(TestCase): compiler = '' - def test_type_match_bad(self,level=5): + @dec.slow + def test_type_match_bad(self): s = c_spec.list_converter() objs = [{},(),'',1,1.,1+1j] for i in objs: assert( not s.type_match(i) ) - def test_type_match_good(self,level=5): + @dec.slow + def test_type_match_good(self): s = c_spec.list_converter() assert(s.type_match([])) - def test_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'list_var_in'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -396,7 +430,8 @@ except TypeError: pass - def test_return(self,level=5): + @dec.slow + def test_return(self): mod_name = 'list_return'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -414,7 +449,8 @@ c = test(b) assert( c == ['hello']) - def test_speed(self,level=5): + @dec.slow + def test_speed(self): mod_name = 'list_speed'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -476,15 +512,18 @@ class TupleConverter(TestCase): compiler = '' - def test_type_match_bad(self,level=5): + @dec.slow + def test_type_match_bad(self): s = c_spec.tuple_converter() objs = [{},[],'',1,1.,1+1j] for i in objs: assert( not s.type_match(i) ) - def test_type_match_good(self,level=5): + @dec.slow + def test_type_match_good(self): s = c_spec.tuple_converter() assert(s.type_match((1,))) - def test_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'tuple_var_in'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -507,7 +546,8 @@ except TypeError: pass - def test_return(self,level=5): + @dec.slow + def test_return(self): mod_name = 'tuple_return'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -537,15 +577,18 @@ # so that it can run on its own. compiler='' - def test_type_match_bad(self,level=5): + @dec.slow + def test_type_match_bad(self): s = c_spec.dict_converter() objs = [[],(),'',1,1.,1+1j] for i in objs: assert( not s.type_match(i) ) - def test_type_match_good(self,level=5): + @dec.slow + def test_type_match_good(self): s = c_spec.dict_converter() assert(s.type_match({})) - def test_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'dict_var_in'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -568,7 +611,8 @@ except TypeError: pass - def test_return(self,level=5): + @dec.slow + def test_return(self): mod_name = 'dict_return'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) Modified: branches/testing_cleanup/scipy/weave/tests/test_ext_tools.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_ext_tools.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_ext_tools.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -19,12 +19,14 @@ class TestExtModule(TestCase): #should really do some testing of where modules end up - def test_simple(self,level=5): + @dec.slow + def test_simple(self): """ Simplest possible module """ mod = ext_tools.ext_module('simple_ext_module') mod.compile(location = build_dir) import simple_ext_module - def test_multi_functions(self,level=5): + @dec.slow + def test_multi_functions(self): mod = ext_tools.ext_module('module_multi_function') var_specs = [] code = "" @@ -36,7 +38,8 @@ import module_multi_function module_multi_function.test() module_multi_function.test2() - def test_with_include(self,level=5): + @dec.slow + def test_with_include(self): # decalaring variables a = 2.; @@ -57,7 +60,8 @@ import ext_module_with_include ext_module_with_include.test(a) - def test_string_and_int(self,level=5): + @dec.slow + def test_string_and_int(self): # decalaring variables a = 2;b = 'string' # declare module @@ -73,7 +77,8 @@ c = ext_string_and_int.test(a,b) assert(c == len(b)) - def test_return_tuple(self,level=5): + @dec.slow + def test_return_tuple(self): # decalaring variables a = 2 # declare module @@ -96,7 +101,8 @@ class TestExtFunction(TestCase): #should really do some testing of where modules end up - def test_simple(self,level=5): + @dec.slow + def test_simple(self): """ Simplest possible function """ mod = ext_tools.ext_module('simple_ext_function') var_specs = [] Modified: branches/testing_cleanup/scipy/weave/tests/test_inline_tools.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_inline_tools.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_inline_tools.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -14,7 +14,8 @@ I'd like to benchmark these things somehow. """ - def test_exceptions(self,level=5): + @dec.slow + def test_exceptions(self): a = 3 code = """ if (a < 2) Modified: branches/testing_cleanup/scipy/weave/tests/test_numpy_scalar_spec.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_numpy_scalar_spec.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_numpy_scalar_spec.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -58,16 +58,21 @@ def setUp(self): self.converter = numpy_complex_scalar_converter() - def test_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): assert( not self.converter.type_match('string') ) - def test_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): assert( not self.converter.type_match(5)) - def test_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): assert( not self.converter.type_match(5.)) - def test_type_match_complex128(self,level=5): + @dec.slow + def test_type_match_complex128(self): assert(self.converter.type_match(numpy.complex128(5.+1j))) - def test_complex_var_in(self,level=5): + @dec.slow + def test_complex_var_in(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -90,7 +95,8 @@ except TypeError: pass - def test_complex_return(self,level=5): + @dec.slow + def test_complex_return(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -107,7 +113,8 @@ c = test(b) assert( c == 3.+3j) - def test_inline(self, level=5): + @dec.slow + def test_inline(self): a = numpy.complex128(1+1j) result = inline_tools.inline("return_val=1.0/a;",['a']) assert( result==.5-.5j) Modified: branches/testing_cleanup/scipy/weave/tests/test_scxx_dict.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_scxx_dict.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_scxx_dict.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -15,7 +15,8 @@ # Check that construction from basic types is allowed and have correct # reference counts #------------------------------------------------------------------------ - def test_empty(self,level=5): + @dec.slow + def test_empty(self): # strange int value used to try and make sure refcount is 2. code = """ py::dict val; @@ -27,7 +28,8 @@ class TestDictHasKey(TestCase): - def test_obj(self,level=5): + @dec.slow + def test_obj(self): class Foo: pass key = Foo() @@ -38,7 +40,8 @@ """ res = inline_tools.inline(code,['a','key']) assert res - def test_int(self,level=5): + @dec.slow + def test_int(self): a = {} a[1234] = 12345 code = """ @@ -46,7 +49,8 @@ """ res = inline_tools.inline(code,['a']) assert res - def test_double(self,level=5): + @dec.slow + def test_double(self): a = {} a[1234.] = 12345 code = """ @@ -54,7 +58,8 @@ """ res = inline_tools.inline(code,['a']) assert res - def test_complex(self,level=5): + @dec.slow + def test_complex(self): a = {} a[1+1j] = 12345 key = 1+1j @@ -64,7 +69,8 @@ res = inline_tools.inline(code,['a','key']) assert res - def test_string(self,level=5): + @dec.slow + def test_string(self): a = {} a["b"] = 12345 code = """ @@ -72,7 +78,8 @@ """ res = inline_tools.inline(code,['a']) assert res - def test_std_string(self,level=5): + @dec.slow + def test_std_string(self): a = {} a["b"] = 12345 key_name = "b" @@ -81,7 +88,8 @@ """ res = inline_tools.inline(code,['a','key_name']) assert res - def test_string_fail(self,level=5): + @dec.slow + def test_string_fail(self): a = {} a["b"] = 12345 code = """ @@ -99,10 +107,12 @@ res = inline_tools.inline(code,args) assert res == a['b'] - def test_char(self,level=5): + @dec.slow + def test_char(self): self.generic_get('return_val = a["b"];') - def DOESNT_WORK_check_char_fail(self,level=5): + @dec.slow + def DOESNT_WORK_check_char_fail(self): # We can't through a KeyError for dicts on RHS of # = but not on LHS. Not sure how to deal with this. try: @@ -110,18 +120,21 @@ except KeyError: pass - def test_string(self,level=5): + @dec.slow + def test_string(self): self.generic_get('return_val = a[std::string("b")];') - def test_obj(self,level=5): + @dec.slow + def test_obj(self): code = """ py::object name = "b"; return_val = a[name]; """ self.generic_get(code,['a']) - def DOESNT_WORK_check_obj_fail(self,level=5): + @dec.slow + def DOESNT_WORK_check_obj_fail(self): # We can't through a KeyError for dicts on RHS of # = but not on LHS. Not sure how to deal with this. try: @@ -164,37 +177,47 @@ assert before == after assert before_overwritten == after_overwritten - def test_new_int_int(self,level=5): + @dec.slow + def test_new_int_int(self): key,val = 1234,12345 self.generic_new(key,val) - def test_new_double_int(self,level=5): + @dec.slow + def test_new_double_int(self): key,val = 1234.,12345 self.generic_new(key,val) - def test_new_std_string_int(self,level=5): + @dec.slow + def test_new_std_string_int(self): key,val = "hello",12345 self.generic_new(key,val) - def test_new_complex_int(self,level=5): + @dec.slow + def test_new_complex_int(self): key,val = 1+1j,12345 self.generic_new(key,val) - def test_new_obj_int(self,level=5): + @dec.slow + def test_new_obj_int(self): class Foo: pass key,val = Foo(),12345 self.generic_new(key,val) - def test_overwrite_int_int(self,level=5): + @dec.slow + def test_overwrite_int_int(self): key,val = 1234,12345 self.generic_overwrite(key,val) - def test_overwrite_double_int(self,level=5): + @dec.slow + def test_overwrite_double_int(self): key,val = 1234.,12345 self.generic_overwrite(key,val) - def test_overwrite_std_string_int(self,level=5): + @dec.slow + def test_overwrite_std_string_int(self): key,val = "hello",12345 self.generic_overwrite(key,val) - def test_overwrite_complex_int(self,level=5): + @dec.slow + def test_overwrite_complex_int(self): key,val = 1+1j,12345 self.generic_overwrite(key,val) - def test_overwrite_obj_int(self,level=5): + @dec.slow + def test_overwrite_obj_int(self): class Foo: pass key,val = Foo(),12345 @@ -216,46 +239,56 @@ after = sys.getrefcount(a), sys.getrefcount(key) assert before[0] == after[0] assert before[1] == after[1] + 1 - def test_int(self,level=5): + @dec.slow + def test_int(self): key = 1234 self.generic(key) - def test_double(self,level=5): + @dec.slow + def test_double(self): key = 1234. self.generic(key) - def test_std_string(self,level=5): + @dec.slow + def test_std_string(self): key = "hello" self.generic(key) - def test_complex(self,level=5): + @dec.slow + def test_complex(self): key = 1+1j self.generic(key) - def test_obj(self,level=5): + @dec.slow + def test_obj(self): class Foo: pass key = Foo() self.generic(key) class TestDictOthers(TestCase): - def test_clear(self,level=5): + @dec.slow + def test_clear(self): a = {} a["hello"] = 1 inline_tools.inline("a.clear();",['a']) assert not a - def test_items(self,level=5): + @dec.slow + def test_items(self): a = {} a["hello"] = 1 items = inline_tools.inline("return_val = a.items();",['a']) assert items == a.items() - def test_values(self,level=5): + @dec.slow + def test_values(self): a = {} a["hello"] = 1 values = inline_tools.inline("return_val = a.values();",['a']) assert values == a.values() - def test_keys(self,level=5): + @dec.slow + def test_keys(self): a = {} a["hello"] = 1 keys = inline_tools.inline("return_val = a.keys();",['a']) assert keys == a.keys() - def test_update(self,level=5): + @dec.slow + def test_update(self): a,b = {},{} a["hello"] = 1 b["hello"] = 2 Modified: branches/testing_cleanup/scipy/weave/tests/test_scxx_object.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_scxx_object.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_scxx_object.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -14,7 +14,8 @@ # Check that construction from basic types is allowed and have correct # reference counts #------------------------------------------------------------------------ - def test_int(self,level=5): + @dec.slow + def test_int(self): # strange int value used to try and make sure refcount is 2. code = """ py::object val = 1001; @@ -23,7 +24,8 @@ res = inline_tools.inline(code) assert_equal(sys.getrefcount(res),2) assert_equal(res,1001) - def test_float(self,level=5): + @dec.slow + def test_float(self): code = """ py::object val = (float)1.0; return_val = val; @@ -31,7 +33,8 @@ res = inline_tools.inline(code) assert_equal(sys.getrefcount(res),2) assert_equal(res,1.0) - def test_double(self,level=5): + @dec.slow + def test_double(self): code = """ py::object val = 1.0; return_val = val; @@ -39,7 +42,8 @@ res = inline_tools.inline(code) assert_equal(sys.getrefcount(res),2) assert_equal(res,1.0) - def test_complex(self,level=5): + @dec.slow + def test_complex(self): code = """ std::complex num = std::complex(1.0,1.0); py::object val = num; @@ -48,7 +52,8 @@ res = inline_tools.inline(code) assert_equal(sys.getrefcount(res),2) assert_equal(res,1.0+1.0j) - def test_string(self,level=5): + @dec.slow + def test_string(self): code = """ py::object val = "hello"; return_val = val; @@ -57,7 +62,8 @@ assert_equal(sys.getrefcount(res),2) assert_equal(res,"hello") - def test_std_string(self,level=5): + @dec.slow + def test_std_string(self): code = """ std::string s = std::string("hello"); py::object val = s; @@ -71,14 +77,16 @@ #------------------------------------------------------------------------ # Check the object print protocol. #------------------------------------------------------------------------ - def test_stdout(self,level=5): + @dec.slow + def test_stdout(self): code = """ py::object val = "how now brown cow"; val.print(stdout); """ res = inline_tools.inline(code) # visual check on this one. - def test_stringio(self,level=5): + @dec.slow + def test_stringio(self): import cStringIO file_imposter = cStringIO.StringIO() code = """ @@ -89,7 +97,8 @@ print file_imposter.getvalue() assert_equal(file_imposter.getvalue(),"'how now brown cow'") -## def test_failure(self,level=5): +## @dec.slow +## def test_failure(self): ## code = """ ## FILE* file = 0; ## py::object val = "how now brown cow"; @@ -103,32 +112,37 @@ class TestObjectCast(TestCase): - def test_int_cast(self,level=5): + @dec.slow + def test_int_cast(self): code = """ py::object val = 1; int raw_val = val; """ inline_tools.inline(code) - def test_double_cast(self,level=5): + @dec.slow + def test_double_cast(self): code = """ py::object val = 1.0; double raw_val = val; """ inline_tools.inline(code) - def test_float_cast(self,level=5): + @dec.slow + def test_float_cast(self): code = """ py::object val = 1.0; float raw_val = val; """ inline_tools.inline(code) - def test_complex_cast(self,level=5): + @dec.slow + def test_complex_cast(self): code = """ std::complex num = std::complex(1.0,1.0); py::object val = num; std::complex raw_val = val; """ inline_tools.inline(code) - def test_string_cast(self,level=5): + @dec.slow + def test_string_cast(self): code = """ py::object val = "hello"; std::string raw_val = val; @@ -149,7 +163,8 @@ # return "b" class TestObjectHasattr(TestCase): - def test_string(self,level=5): + @dec.slow + def test_string(self): a = Foo() a.b = 12345 code = """ @@ -157,7 +172,8 @@ """ res = inline_tools.inline(code,['a']) assert res - def test_std_string(self,level=5): + @dec.slow + def test_std_string(self): a = Foo() a.b = 12345 attr_name = "b" @@ -166,7 +182,8 @@ """ res = inline_tools.inline(code,['a','attr_name']) assert res - def test_string_fail(self,level=5): + @dec.slow + def test_string_fail(self): a = Foo() a.b = 12345 code = """ @@ -174,7 +191,8 @@ """ res = inline_tools.inline(code,['a']) assert not res - def test_inline(self,level=5): + @dec.slow + def test_inline(self): """ THIS NEEDS TO MOVE TO THE INLINE TEST SUITE """ a = Foo() @@ -195,7 +213,8 @@ print 'before, after, after2:', before, after, after2 pass - def test_func(self,level=5): + @dec.slow + def test_func(self): a = Foo() a.b = 12345 code = """ @@ -217,32 +236,38 @@ after = sys.getrefcount(a.b) assert_equal(after,before) - def test_char(self,level=5): + @dec.slow + def test_char(self): self.generic_attr('return_val = a.attr("b");') - def test_char_fail(self,level=5): + @dec.slow + def test_char_fail(self): try: self.generic_attr('return_val = a.attr("c");') except AttributeError: pass - def test_string(self,level=5): + @dec.slow + def test_string(self): self.generic_attr('return_val = a.attr(std::string("b"));') - def test_string_fail(self,level=5): + @dec.slow + def test_string_fail(self): try: self.generic_attr('return_val = a.attr(std::string("c"));') except AttributeError: pass - def test_obj(self,level=5): + @dec.slow + def test_obj(self): code = """ py::object name = "b"; return_val = a.attr(name); """ self.generic_attr(code,['a']) - def test_obj_fail(self,level=5): + @dec.slow + def test_obj_fail(self): try: code = """ py::object name = "c"; @@ -252,7 +277,8 @@ except AttributeError: pass - def test_attr_call(self,level=5): + @dec.slow + def test_attr_call(self): a = Foo() res = inline_tools.inline('return_val = a.attr("bar").call();',['a']) first = sys.getrefcount(res) @@ -277,27 +303,34 @@ res = inline_tools.inline(code,args) assert_equal(a.b,desired) - def test_existing_char(self,level=5): + @dec.slow + def test_existing_char(self): self.generic_existing('a.set_attr("b","hello");',"hello") - def test_new_char(self,level=5): + @dec.slow + def test_new_char(self): self.generic_new('a.set_attr("b","hello");',"hello") - def test_existing_string(self,level=5): + @dec.slow + def test_existing_string(self): self.generic_existing('a.set_attr("b",std::string("hello"));',"hello") - def test_new_string(self,level=5): + @dec.slow + def test_new_string(self): self.generic_new('a.set_attr("b",std::string("hello"));',"hello") - def test_existing_object(self,level=5): + @dec.slow + def test_existing_object(self): code = """ py::object obj = "hello"; a.set_attr("b",obj); """ self.generic_existing(code,"hello") - def test_new_object(self,level=5): + @dec.slow + def test_new_object(self): code = """ py::object obj = "hello"; a.set_attr("b",obj); """ self.generic_new(code,"hello") - def test_new_fail(self,level=5): + @dec.slow + def test_new_fail(self): try: code = """ py::object obj = 1; @@ -307,19 +340,24 @@ except: pass - def test_existing_int(self,level=5): + @dec.slow + def test_existing_int(self): self.generic_existing('a.set_attr("b",1);',1) - def test_existing_double(self,level=5): + @dec.slow + def test_existing_double(self): self.generic_existing('a.set_attr("b",1.0);',1.0) - def test_existing_complex(self,level=5): + @dec.slow + def test_existing_complex(self): code = """ std::complex obj = std::complex(1,1); a.set_attr("b",obj); """ self.generic_existing(code,1+1j) - def test_existing_char1(self,level=5): + @dec.slow + def test_existing_char1(self): self.generic_existing('a.set_attr("b","hello");',"hello") - def test_existing_string1(self,level=5): + @dec.slow + def test_existing_string1(self): code = """ std::string obj = std::string("hello"); a.set_attr("b",obj); @@ -334,15 +372,18 @@ res = inline_tools.inline(code,args) assert not hasattr(a,"b") - def test_char(self,level=5): + @dec.slow + def test_char(self): self.generic('a.del("b");') - def test_string(self,level=5): + @dec.slow + def test_string(self): code = """ std::string name = std::string("b"); a.del(name); """ self.generic(code) - def test_object(self,level=5): + @dec.slow + def test_object(self): code = """ py::object name = py::object("b"); a.del(name); @@ -350,11 +391,13 @@ self.generic(code) class TestObjectCmp(TestCase): - def test_equal(self,level=5): + @dec.slow + def test_equal(self): a,b = 1,1 res = inline_tools.inline('return_val = (a == b);',['a','b']) assert_equal(res,(a == b)) - def test_equal_objects(self,level=5): + @dec.slow + def test_equal_objects(self): class Foo: def __init__(self,x): self.x = x @@ -363,47 +406,58 @@ a,b = Foo(1),Foo(2) res = inline_tools.inline('return_val = (a == b);',['a','b']) assert_equal(res,(a == b)) - def test_lt(self,level=5): + @dec.slow + def test_lt(self): a,b = 1,2 res = inline_tools.inline('return_val = (a < b);',['a','b']) assert_equal(res,(a < b)) - def test_gt(self,level=5): + @dec.slow + def test_gt(self): a,b = 1,2 res = inline_tools.inline('return_val = (a > b);',['a','b']) assert_equal(res,(a > b)) - def test_gte(self,level=5): + @dec.slow + def test_gte(self): a,b = 1,2 res = inline_tools.inline('return_val = (a >= b);',['a','b']) assert_equal(res,(a >= b)) - def test_lte(self,level=5): + @dec.slow + def test_lte(self): a,b = 1,2 res = inline_tools.inline('return_val = (a <= b);',['a','b']) assert_equal(res,(a <= b)) - def test_not_equal(self,level=5): + @dec.slow + def test_not_equal(self): a,b = 1,2 res = inline_tools.inline('return_val = (a != b);',['a','b']) assert_equal(res,(a != b)) - def test_int(self,level=5): + @dec.slow + def test_int(self): a = 1 res = inline_tools.inline('return_val = (a == 1);',['a']) assert_equal(res,(a == 1)) - def test_int2(self,level=5): + @dec.slow + def test_int2(self): a = 1 res = inline_tools.inline('return_val = (1 == a);',['a']) assert_equal(res,(a == 1)) - def test_unsigned_long(self,level=5): + @dec.slow + def test_unsigned_long(self): a = 1 res = inline_tools.inline('return_val = (a == (unsigned long)1);',['a']) assert_equal(res,(a == 1)) - def test_double(self,level=5): + @dec.slow + def test_double(self): a = 1 res = inline_tools.inline('return_val = (a == 1.0);',['a']) assert_equal(res,(a == 1.0)) - def test_char(self,level=5): + @dec.slow + def test_char(self): a = "hello" res = inline_tools.inline('return_val = (a == "hello");',['a']) assert_equal(res,(a == "hello")) - def test_std_string(self,level=5): + @dec.slow + def test_std_string(self): a = "hello" code = """ std::string hello = std::string("hello"); @@ -413,7 +467,8 @@ assert_equal(res,(a == "hello")) class TestObjectRepr(TestCase): - def test_repr(self,level=5): + @dec.slow + def test_repr(self): class Foo: def __str__(self): return "str return" @@ -429,7 +484,8 @@ assert_equal(res,"repr return") class TestObjectStr(TestCase): - def test_str(self,level=5): + @dec.slow + def test_str(self): class Foo: def __str__(self): return "str return" @@ -447,7 +503,8 @@ class TestObjectUnicode(TestCase): # This ain't going to win awards for test of the year... - def test_unicode(self,level=5): + @dec.slow + def test_unicode(self): class Foo: def __repr__(self): return "repr return" @@ -463,14 +520,16 @@ assert_equal(res,"unicode") class TestObjectIsCallable(TestCase): - def test_true(self,level=5): + @dec.slow + def test_true(self): class Foo: def __call__(self): return 0 a= Foo() res = inline_tools.inline('return_val = a.is_callable();',['a']) assert res - def test_false(self,level=5): + @dec.slow + def test_false(self): class Foo: pass a= Foo() @@ -478,13 +537,15 @@ assert not res class TestObjectCall(TestCase): - def test_noargs(self,level=5): + @dec.slow + def test_noargs(self): def Foo(): return (1,2,3) res = inline_tools.inline('return_val = Foo.call();',['Foo']) assert_equal(res,(1,2,3)) assert_equal(sys.getrefcount(res),3) # should be 2? - def test_args(self,level=5): + @dec.slow + def test_args(self): def Foo(val1,val2): return (val1,val2) code = """ @@ -496,7 +557,8 @@ res = inline_tools.inline(code,['Foo']) assert_equal(res,(1,"hello")) assert_equal(sys.getrefcount(res),2) - def test_args_kw(self,level=5): + @dec.slow + def test_args_kw(self): def Foo(val1,val2,val3=1): return (val1,val2,val3) code = """ @@ -510,7 +572,8 @@ res = inline_tools.inline(code,['Foo']) assert_equal(res,(1,"hello",3)) assert_equal(sys.getrefcount(res),2) - def test_noargs_with_args(self,level=5): + @dec.slow + def test_noargs_with_args(self): # calling a function that does take args with args # should fail. def Foo(): @@ -534,7 +597,8 @@ assert_equal(second,third) class TestObjectMcall(TestCase): - def test_noargs(self,level=5): + @dec.slow + def test_noargs(self): a = Foo() res = inline_tools.inline('return_val = a.mcall("bar");',['a']) assert_equal(res,"bar results") @@ -544,7 +608,8 @@ assert_equal(res,"bar results") second = sys.getrefcount(res) assert_equal(first,second) - def test_args(self,level=5): + @dec.slow + def test_args(self): a = Foo() code = """ py::tuple args(2); @@ -555,7 +620,8 @@ res = inline_tools.inline(code,['a']) assert_equal(res,(1,"hello")) assert_equal(sys.getrefcount(res),2) - def test_args_kw(self,level=5): + @dec.slow + def test_args_kw(self): a = Foo() code = """ py::tuple args(2); @@ -568,7 +634,8 @@ res = inline_tools.inline(code,['a']) assert_equal(res,(1,"hello",3)) assert_equal(sys.getrefcount(res),2) - def test_std_noargs(self,level=5): + @dec.slow + def test_std_noargs(self): a = Foo() method = "bar" res = inline_tools.inline('return_val = a.mcall(method);',['a','method']) @@ -579,7 +646,8 @@ assert_equal(res,"bar results") second = sys.getrefcount(res) assert_equal(first,second) - def test_std_args(self,level=5): + @dec.slow + def test_std_args(self): a = Foo() method = "bar2" code = """ @@ -591,7 +659,8 @@ res = inline_tools.inline(code,['a','method']) assert_equal(res,(1,"hello")) assert_equal(sys.getrefcount(res),2) - def test_std_args_kw(self,level=5): + @dec.slow + def test_std_args_kw(self): a = Foo() method = "bar3" code = """ @@ -605,7 +674,8 @@ res = inline_tools.inline(code,['a','method']) assert_equal(res,(1,"hello",3)) assert_equal(sys.getrefcount(res),2) - def test_noargs_with_args(self,level=5): + @dec.slow + def test_noargs_with_args(self): # calling a function that does take args with args # should fail. a = Foo() @@ -628,7 +698,8 @@ assert_equal(second,third) class TestObjectHash(TestCase): - def test_hash(self,level=5): + @dec.slow + def test_hash(self): class Foo: def __hash__(self): return 123 @@ -638,19 +709,22 @@ assert_equal(res,123) class TestObjectIsTrue(TestCase): - def test_true(self,level=5): + @dec.slow + def test_true(self): class Foo: pass a= Foo() res = inline_tools.inline('return_val = a.is_true();',['a']) assert_equal(res,1) - def test_false(self,level=5): + @dec.slow + def test_false(self): a= None res = inline_tools.inline('return_val = a.is_true();',['a']) assert_equal(res,0) class TestObjectType(TestCase): - def test_type(self,level=5): + @dec.slow + def test_type(self): class Foo: pass a= Foo() @@ -658,21 +732,24 @@ assert_equal(res,type(a)) class TestObjectSize(TestCase): - def test_size(self,level=5): + @dec.slow + def test_size(self): class Foo: def __len__(self): return 10 a= Foo() res = inline_tools.inline('return_val = a.size();',['a']) assert_equal(res,len(a)) - def test_len(self,level=5): + @dec.slow + def test_len(self): class Foo: def __len__(self): return 10 a= Foo() res = inline_tools.inline('return_val = a.len();',['a']) assert_equal(res,len(a)) - def test_length(self,level=5): + @dec.slow + def test_length(self): class Foo: def __len__(self): return 10 @@ -682,34 +759,40 @@ from UserList import UserList class TestObjectSetItemOpIndex(TestCase): - def test_list_refcount(self,level=5): + @dec.slow + def test_list_refcount(self): a = UserList([1,2,3]) # temporary refcount fix until I understand why it incs by one. inline_tools.inline("a[1] = 1234;",['a']) before1 = sys.getrefcount(a) after1 = sys.getrefcount(a) assert_equal(after1,before1) - def test_set_int(self,level=5): + @dec.slow + def test_set_int(self): a = UserList([1,2,3]) inline_tools.inline("a[1] = 1234;",['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],1234) - def test_set_double(self,level=5): + @dec.slow + def test_set_double(self): a = UserList([1,2,3]) inline_tools.inline("a[1] = 123.0;",['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],123.0) - def test_set_char(self,level=5): + @dec.slow + def test_set_char(self): a = UserList([1,2,3]) inline_tools.inline('a[1] = "bubba";',['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],'bubba') - def test_set_string(self,level=5): + @dec.slow + def test_set_string(self): a = UserList([1,2,3]) inline_tools.inline('a[1] = std::string("sissy");',['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],'sissy') - def test_set_string(self,level=5): + @dec.slow + def test_set_string(self): a = UserList([1,2,3]) inline_tools.inline('a[1] = std::complex(1,1);',['a']) assert_equal(sys.getrefcount(a[1]),2) @@ -717,7 +800,8 @@ from UserDict import UserDict class TestObjectSetItemOpKey(TestCase): - def test_key_refcount(self,level=5): + @dec.slow + def test_key_refcount(self): a = UserDict() code = """ py::object one = 1; @@ -751,7 +835,8 @@ assert_equal(val[0] + 1, val[1]) assert_equal(val[1], val[2]) - def test_set_double_exists(self,level=5): + @dec.slow + def test_set_double_exists(self): a = UserDict() key = 10.0 a[key] = 100.0 @@ -764,27 +849,31 @@ assert_equal(sys.getrefcount(key),5) assert_equal(sys.getrefcount(a[key]),2) assert_equal(a[key],123.0) - def test_set_double_new(self,level=5): + @dec.slow + def test_set_double_new(self): a = UserDict() key = 1.0 inline_tools.inline('a[key] = 123.0;',['a','key']) assert_equal(sys.getrefcount(key),4) # should be 3 assert_equal(sys.getrefcount(a[key]),2) assert_equal(a[key],123.0) - def test_set_complex(self,level=5): + @dec.slow + def test_set_complex(self): a = UserDict() key = 1+1j inline_tools.inline("a[key] = 1234;",['a','key']) assert_equal(sys.getrefcount(key),4) # should be 3 assert_equal(sys.getrefcount(a[key]),2) assert_equal(a[key],1234) - def test_set_char(self,level=5): + @dec.slow + def test_set_char(self): a = UserDict() inline_tools.inline('a["hello"] = 123.0;',['a']) assert_equal(sys.getrefcount(a["hello"]),2) assert_equal(a["hello"],123.0) - def test_set_class(self,level=5): + @dec.slow + def test_set_class(self): a = UserDict() class Foo: def __init__(self,val): @@ -802,7 +891,8 @@ assert_equal(sys.getrefcount(key),4) assert_equal(sys.getrefcount(a[key]),2) assert_equal(a[key],'bubba') - def test_set_from_member(self,level=5): + @dec.slow + def test_set_from_member(self): a = UserDict() a['first'] = 1 a['second'] = 2 @@ -810,7 +900,4 @@ assert_equal(a['first'],a['second']) if __name__ == "__main__": - import sys - if len(sys.argv) == 1: - sys.argv.extend(["--level=5"]) unittest.main() Modified: branches/testing_cleanup/scipy/weave/tests/test_scxx_sequence.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_scxx_sequence.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_scxx_sequence.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -23,7 +23,8 @@ class _TestSequenceBase(TestCase): seq_type = None - def test_conversion(self,level=5): + @dec.slow + def test_conversion(self): a = self.seq_type([1]) before = sys.getrefcount(a) inline_tools.inline(" ",['a']) @@ -35,7 +36,8 @@ #print '2nd,3rd:', before, after assert(after == before) - def test_in(self,level=5): + @dec.slow + def test_in(self): """ Test the "in" method for lists. We'll assume it works for sequences if it works here. """ @@ -87,7 +89,8 @@ res = inline_tools.inline(code,['a']) assert res == 0 - def test_count(self,level=5): + @dec.slow + def test_count(self): """ Test the "count" method for lists. We'll assume it works for sequences if it works hre. """ @@ -121,7 +124,8 @@ res = inline_tools.inline(code,['a']) assert res == 1 - def test_access_speed(self,level=5): + @dec.slow + def test_access_speed(self): N = 1000000 print '%s access -- val = a[i] for N =', (self.seq_type, N) a = self.seq_type([0]) * N @@ -151,7 +155,8 @@ print 'weave:', t2 - t1 # Fails - def test_access_set_speed(self,level=5): + @dec.slow + def test_access_set_speed(self): N = 1000000 print '%s access/set -- b[i] = a[i] for N =', (self.seq_type,N) a = self.seq_type([0]) * N @@ -181,7 +186,8 @@ class TestTuple(_TestSequenceBase): seq_type = tuple - def test_set_item_operator_equal_fail(self,level=5): + @dec.slow + def test_set_item_operator_equal_fail(self): # Tuples should only allow setting of variables # immediately after creation. a = (1,2,3) @@ -189,7 +195,8 @@ inline_tools.inline("a[1] = 1234;",['a']) except TypeError: pass - def test_set_item_operator_equal(self,level=5): + @dec.slow + def test_set_item_operator_equal(self): code = """ py::tuple a(3); a[0] = 1; @@ -202,7 +209,8 @@ # returned value should only have a single refcount assert sys.getrefcount(a) == 2 - def test_set_item_index_error(self,level=5): + @dec.slow + def test_set_item_index_error(self): code = """ py::tuple a(3); a[4] = 1; @@ -213,7 +221,8 @@ assert 0 except IndexError: pass - def test_get_item_operator_index_error(self,level=5): + @dec.slow + def test_get_item_operator_index_error(self): code = """ py::tuple a(3); py::object b = a[4]; // should fail. @@ -226,7 +235,8 @@ class TestList(_TestSequenceBase): seq_type = list - def test_append_passed_item(self,level=5): + @dec.slow + def test_append_passed_item(self): a = [] item = 1 @@ -243,7 +253,8 @@ after2 = sys.getrefcount(item) assert after1 == before1 assert after2 == before2 - def test_append(self,level=5): + @dec.slow + def test_append(self): a = [] # temporary refcount fix until I understand why it incs by one. inline_tools.inline("a.append(1);",['a']) @@ -277,7 +288,8 @@ after1 = sys.getrefcount(a) assert after1 == before1 - def test_insert(self,level=5): + @dec.slow + def test_insert(self): a = [1,2,3] a.insert(1,234) @@ -316,7 +328,8 @@ after1 = sys.getrefcount(a) assert after1 == before1 - def test_set_item_operator_equal(self,level=5): + @dec.slow + def test_set_item_operator_equal(self): a = self.seq_type([1,2,3]) # temporary refcount fix until I understand why it incs by one. inline_tools.inline("a[1] = 1234;",['a']) @@ -348,7 +361,8 @@ after1 = sys.getrefcount(a) assert after1 == before1 - def test_set_item_operator_equal_created(self,level=5): + @dec.slow + def test_set_item_operator_equal_created(self): code = """ py::list a(3); a[0] = 1; @@ -360,7 +374,8 @@ assert a == [1,2,3] # returned value should only have a single refcount assert sys.getrefcount(a) == 2 - def test_set_item_index_error(self,level=5): + @dec.slow + def test_set_item_index_error(self): code = """ py::list a(3); a[4] = 1; @@ -370,7 +385,8 @@ assert 0 except IndexError: pass - def test_get_item_index_error(self,level=5): + @dec.slow + def test_get_item_index_error(self): code = """ py::list a(3); py::object o = a[4]; @@ -381,7 +397,8 @@ except IndexError: pass - def test_string_add_speed(self,level=5): + @dec.slow + def test_string_add_speed(self): N = 1000000 print 'string add -- b[i] = a[i] + "blah" for N =', N a = ["blah"] * N @@ -407,7 +424,8 @@ t2 = time.time() print 'weave:', t2 - t1 assert b == desired - def test_int_add_speed(self,level=5): + @dec.slow + def test_int_add_speed(self): N = 1000000 print 'int add -- b[i] = a[i] + 1 for N =', N a = [0] * N Modified: branches/testing_cleanup/scipy/weave/tests/test_size_check.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_size_check.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_size_check.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -13,7 +13,7 @@ class TestMakeSameLength(TestCase): - def generic_test(self,x,y,desired): + def generic_check(self,x,y,desired): actual = size_check.make_same_length(x,y) desired = desired assert_array_equal(actual,desired) @@ -21,30 +21,30 @@ def test_scalar(self): x,y = (),() desired = empty,empty - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_scalar(self): x,y = (),(1,2) desired = array((1,1)),array((1,2)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_y_scalar(self): x,y = (1,2),() desired = array((1,2)),array((1,1)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_short(self): x,y = (1,2),(1,2,3) desired = array((1,1,2)),array((1,2,3)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_y_short(self): x,y = (1,2,3),(1,2) desired = array((1,2,3)),array((1,1,2)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) class TestBinaryOpSize(TestCase): - def generic_test(self,x,y,desired): + def generic_check(self,x,y,desired): actual = size_check.binary_op_size(x,y) desired = desired assert_array_equal(actual,desired) - def generic_error_test(self,x,y): + def generic_error_check(self,x,y): self.failUnlessRaises(ValueError, size_check.binary_op_size, x, y) def desired_type(self,val): @@ -52,54 +52,54 @@ def test_scalar(self): x,y = (),() desired = self.desired_type(()) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x1(self): x,y = (1,),() desired = self.desired_type((1,)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_y1(self): x,y = (),(1,) desired = self.desired_type((1,)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_y(self): x,y = (5,),(5,) desired = self.desired_type((5,)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_y2(self): x,y = (5,10),(5,10) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_y3(self): x,y = (5,10),(1,10) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_y4(self): x,y = (1,10),(5,10) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_y5(self): x,y = (5,1),(1,10) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_y6(self): x,y = (1,10),(5,1) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_x_y7(self): x,y = (5,4,3,2,1),(3,2,1) desired = self.desired_type((5,4,3,2,1)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) def test_error1(self): x,y = (5,),(4,) - self.generic_error_test(x,y) + self.generic_error_check(x,y) def test_error2(self): x,y = (5,5),(4,5) - self.generic_error_test(x,y) + self.generic_error_check(x,y) class TestDummyArray(TestBinaryOpSize): - def generic_test(self,x,y,desired): + def generic_check(self,x,y,desired): if type(x) is type(()): x = ones(x) if type(y) is type(()): @@ -116,7 +116,7 @@ return size_check.dummy_array(array(val),1) class TestDummyArrayIndexing(TestCase): - def generic_test(self,ary,expr,desired): + def generic_check(self,ary,expr,desired): a = size_check.dummy_array(ary) actual = eval(expr).shape #print desired, actual @@ -124,7 +124,7 @@ def generic_wrap(self,a,expr): desired = array(eval(expr).shape) try: - self.generic_test(a,expr,desired) + self.generic_check(a,expr,desired) except IndexError: if 0 not in desired: msg = '%s raised IndexError in dummy_array, but forms\n' \ @@ -144,7 +144,7 @@ a = arange(10) #print expr ,eval(expr) desired = array(()) - self.generic_test(a,expr,desired) + self.generic_check(a,expr,desired) def test_1d_index_0(self): self.generic_1d_index('a[0]') def test_1d_index_1(self): @@ -302,7 +302,7 @@ pass class TestExpressions(TestCase): - def generic_test(self,expr,desired,**kw): + def generic_check(self,expr,desired,**kw): import parser ast_list = parser.expr(expr).tolist() args = harvest_variables(ast_list) @@ -331,7 +331,7 @@ desired = zeros(()) except: desired = 'failed' - self.generic_test(expr,desired,**kw) + self.generic_check(expr,desired,**kw) def test_generic_1d(self): a = arange(10) expr = 'a[:]' Modified: branches/testing_cleanup/scipy/weave/tests/test_slice_handler.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_slice_handler.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_slice_handler.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -23,7 +23,7 @@ raise AssertionError, msg.getvalue() class TestBuildSliceAtom(TestCase): - def generic_test(self,slice_vars,desired): + def generic_check(self,slice_vars,desired): pos = slice_vars['pos'] ast_list = slice_handler.build_slice_atom(slice_vars,pos) actual = ast_to_string(ast_list) @@ -32,11 +32,11 @@ slice_vars = {'begin':'1', 'end':'2', 'step':'_stp', 'single_index':'_index','pos':0} desired = 'slice(1,2-1)' - self.generic_test(slice_vars,desired) + self.generic_check(slice_vars,desired) class TestSlice(TestCase): - def generic_test(self,suite_string,desired): + def generic_check(self,suite_string,desired): import parser ast_tuple = parser.suite(suite_string).totuple() found, data = find_first_pattern(ast_tuple,indexed_array_pattern) @@ -49,84 +49,84 @@ test ="a[:]" desired = {'begin':'_beg', 'end':'_end', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_begin_2_slice(self): """match slice from a[1:]""" test ="a[1:]" desired = {'begin':'1', 'end':'_end', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_end_2_slice(self): """match slice from a[:2]""" test ="a[:2]" desired = {'begin':'_beg', 'end':'2', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_begin_end_2_slice(self): """match slice from a[1:2]""" test ="a[1:2]" desired = {'begin':'1', 'end':'2', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_empty_3_slice(self): """match slice from a[::]""" test ="a[::]" desired = {'begin':'_beg', 'end':'_end', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_begin_3_slice(self): """match slice from a[1::]""" test ="a[1::]" desired = {'begin':'1', 'end':'_end', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_end_3_slice(self): """match slice from a[:2:]""" test ="a[:2:]" desired = {'begin':'_beg', 'end':'2', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_stp3_slice(self): """match slice from a[::3]""" test ="a[::3]" desired = {'begin':'_beg', 'end':'_end', 'step':'3', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_begin_end_3_slice(self): """match slice from a[1:2:]""" test ="a[1:2:]" desired = {'begin':'1', 'end':'2','step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_begin_step_3_slice(self): """match slice from a[1::3]""" test ="a[1::3]" desired = {'begin':'1', 'end':'_end','step':'3', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_end_step_3_slice(self): """match slice from a[:2:3]""" test ="a[:2:3]" desired = {'begin':'_beg', 'end':'2', 'step':'3', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_begin_end_stp3_slice(self): """match slice from a[1:2:3]""" test ="a[1:2:3]" desired = {'begin':'1', 'end':'2', 'step':'3','single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_expr_3_slice(self): """match slice from a[:1+i+2:]""" test ="a[:1+i+2:]" desired = {'begin':'_beg', 'end':"1+i+2",'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) + self.generic_check(test,desired) def test_single_index(self): """match slice from a[0]""" test ="a[0]" desired = {'begin':'_beg', 'end':"_end",'step':'_stp', 'single_index':'0'} - self.generic_test(test,desired) + self.generic_check(test,desired) def replace_whitespace(in_str): out = in_str.replace(" ","") @@ -135,7 +135,7 @@ return out class TestTransformSlices(TestCase): - def generic_test(self,suite_string,desired): + def generic_check(self,suite_string,desired): import parser ast_list = parser.suite(suite_string).tolist() slice_handler.transform_slices(ast_list) @@ -150,7 +150,7 @@ """transform a[:] to slice notation""" test ="a[:]" desired = 'a[slice(_beg,_end,_stp)]' - self.generic_test(test,desired) + self.generic_check(test,desired) def test_simple_expr(self): """transform a[:,:] = b[:,1:1+2:3] *(c[1-2+i:,:] - c[:,:])""" test ="a[:,:] = b[:,1:1+2:3] *(c[1-2+i:,:] - c[:,:])" @@ -158,7 +158,7 @@ " b[slice(_beg,_end), slice(1,1+2-1,3)] *"\ " (c[slice(1-2+i,_end), slice(_beg,_end)] -"\ " c[slice(_beg,_end), slice(_beg,_end)])" - self.generic_test(test,desired) + self.generic_check(test,desired) if __name__ == "__main__": Modified: branches/testing_cleanup/scipy/weave/tests/test_wx_spec.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_wx_spec.py 2008-01-08 20:14:01 UTC (rev 3802) +++ branches/testing_cleanup/scipy/weave/tests/test_wx_spec.py 2008-01-08 22:52:05 UTC (rev 3803) @@ -10,7 +10,7 @@ from scipy.testing import * -from weave import ext_tools, wx_spec +from scipy.weave import ext_tools, wx_spec import wx @@ -20,26 +20,33 @@ self.app = wx.App() self.s = wx_spec.wx_converter() - def test_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): assert(not self.s.type_match('string') ) - def test_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): assert(not self.s.type_match(5)) - def test_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): assert(not self.s.type_match(5.)) - def test_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): assert(not self.s.type_match(5.+1j)) - def test_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): assert(not self.s.type_match(5.+1j)) - def test_type_match_wxframe(self,level=5): + @dec.slow + def test_type_match_wxframe(self): f=wx.Frame(None,-1,'bob') assert(self.s.type_match(f)) - def test_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod = ext_tools.ext_module('wx_var_in',compiler='') mod.customize.add_header('') mod.customize.add_extra_compile_arg(' '.join(self.s.extra_compile_args)) @@ -69,7 +76,8 @@ except AttributeError: pass - def no_check_var_local(self,level=5): + @dec.slow + def no_check_var_local(self): mod = ext_tools.ext_module('wx_var_local') a = 'string' code = 'a="hello";' @@ -83,7 +91,8 @@ wx_var_local.test(b,q) assert('a' == 'string') - def no_test_no_check_return(self,level=5): + @dec.slow + def no_test_no_check_return(self): mod = ext_tools.ext_module('wx_return') a = 'string' code = """ @@ -99,7 +108,4 @@ assert(c == 'hello') if __name__ == "__main__": - import sys - if len(sys.argv) == 1: - sys.argv.extend(["--level=5"]) - NumpyTest().test(10,10) + unittest.main() From scipy-svn at scipy.org Tue Jan 8 17:55:59 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 16:55:59 -0600 (CST) Subject: [Scipy-svn] r3804 - in branches/testing_cleanup: . scipy/sandbox/timeseries Message-ID: <20080108225559.4598839C0EB@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-08 16:55:53 -0600 (Tue, 08 Jan 2008) New Revision: 3804 Modified: branches/testing_cleanup/ branches/testing_cleanup/scipy/sandbox/timeseries/dates.py branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py Log: Merged revisions 3801 via svnmerge from http://svn.scipy.org/svn/scipy/trunk ........ r3801 | dhuard | 2008-01-08 11:36:52 -0800 (Tue, 08 Jan 2008) | 1 line Fixed bug in fromtextfile ........ Property changes on: branches/testing_cleanup ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3799 + /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3803 Modified: branches/testing_cleanup/scipy/sandbox/timeseries/dates.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/dates.py 2008-01-08 22:52:05 UTC (rev 3803) +++ branches/testing_cleanup/scipy/sandbox/timeseries/dates.py 2008-01-08 22:55:53 UTC (rev 3804) @@ -562,6 +562,40 @@ fcode = _c.FR_UND return fcode +def guess_freq_date(dates): + """Tries to estimate the frequency of a sequence of datetime objects.""" + if not type(dates[0]) is dt.datetime: + raise AttributeError, "dates not a sequence of datetime objects." + + sorted_dates = numpy.sort(dates) + ddif = numpy.diff(sorted_dates) + dset = set(ddif) + try: + dset.remove(dt.timedelta(0)) + except: + pass + res = min(dset) + if getattr(res, 'seconds', 0) >= 1: + fcode = _c.FR_SEC + elif getattr(res, 'seconds', 0) >= 60: + fcode = _c.FR_MIN + elif getattr(res, 'seconds', 0) >= 60*60: + fcode = _c.FR_HR + elif getattr(res, 'day', 0) >= 1: + fcode = _c.FR_DAY + elif getattr(res, 'day', 0) >= 7: + fcode = _c.FR_WK + elif getattr(res, 'month', 0) >= 1: + fcode = _c.FR_MTH + elif getattr(res, 'month', 0) >= 3: + fcode = _c.FR_QTR + elif getattr(res, 'year', 0) >= 1: + fcode = _c.FR_ANN + else: + warnings.warn("Unable to estimate the frequency! %s" % res.__str__()) + fcode = _c.FR_UND + return fcode + def _listparser(dlist, freq=None): "Constructs a DateArray from a list." @@ -578,7 +612,10 @@ ords += 1 #...try to guess the frequency if freq is None or freq == _c.FR_UND: - freq = guess_freq(ords) + freq = guess_freq(ords) + if freq == _c.FR_UND: + dtobj = [DateTimeFromString(s) for s in dlist] + freq = guess_freq_date(dtobj) #...construct a list of dates for s in dlist: x = Date(freq, string=s) Modified: branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py 2008-01-08 22:52:05 UTC (rev 3803) +++ branches/testing_cleanup/scipy/sandbox/timeseries/trecords.py 2008-01-08 22:55:53 UTC (rev 3804) @@ -494,10 +494,14 @@ # newdates = __getdates(dates=dates, newdates=newdates, length=nvars, freq=None, start_date=None) - return TimeSeriesRecords(_datalist, dates=newdates, dtype=mdescr) + # Sort the datalist according to newdates._unsorted + idx = newdates._unsorted + _sorted_datalist = [a[idx] for a in _datalist] + return TimeSeriesRecords(_sorted_datalist, dates=newdates, dtype=mdescr) + ################################################################################ if __name__ == '__main__': import numpy as N From scipy-svn at scipy.org Tue Jan 8 18:50:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 17:50:28 -0600 (CST) Subject: [Scipy-svn] r3805 - in branches/testing_cleanup/scipy: . sandbox/lobpcg/tests sandbox/timeseries/lib/tests testing Message-ID: <20080108235028.C71FD39C3F2@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-08 17:50:11 -0600 (Tue, 08 Jan 2008) New Revision: 3805 Added: branches/testing_cleanup/scipy/testing/setup.py Modified: branches/testing_cleanup/scipy/sandbox/lobpcg/tests/test_lobpcg.py branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_interpolate.py branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py branches/testing_cleanup/scipy/setup.py branches/testing_cleanup/scipy/testing/nosetester.py Log: Cleaning up sandbox, testing setup.py Modified: branches/testing_cleanup/scipy/sandbox/lobpcg/tests/test_lobpcg.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/lobpcg/tests/test_lobpcg.py 2008-01-08 22:55:53 UTC (rev 3804) +++ branches/testing_cleanup/scipy/sandbox/lobpcg/tests/test_lobpcg.py 2008-01-08 23:50:11 UTC (rev 3805) @@ -5,7 +5,7 @@ from pylab import plot, show, legend, xlabel, ylabel set_printoptions(precision=3,linewidth=90) -def test1(n): +def check1(n): L = 1.0 le=L/n rho = 7.85e3 @@ -17,7 +17,7 @@ B = mass*(diag(r_[4.*ones(n-1),2])+diag(ones(n-1),1)+diag(ones(n-1),-1)) return A,B -def test2(n): +def check2(n): x = arange(1,n+1) B = diag(1./x) y = arange(n-1,0,-1) @@ -27,22 +27,22 @@ n = 100 # Dimension -A,B = test1(n) # Fixed-free elastic rod -A,B = test2(n) # Mikota pair acts as a nice test since the eigenvalues are the squares of the integers n, n=1,2,... +def test_1and2(): + A,B = check1(n) # Fixed-free elastic rod + A,B = check2(n) # Mikota pair acts as a nice test since the eigenvalues are the squares of the integers n, n=1,2,... + + m = 20 + V = rand(n,m) + X = linalg.orth(V) + + eigs,vecs = lobpcg.lobpcg(X,A,B) + eigs = sort(eigs) + + w,v=symeig(A,B) -m = 20 -V = rand(n,m) -X = linalg.orth(V) - -eigs,vecs = lobpcg.lobpcg(X,A,B) -eigs = sort(eigs) - -w,v=symeig(A,B) - - -plot(arange(0,len(w[:m])),w[:m],'bx',label='Results by symeig') -plot(arange(0,len(eigs)),eigs,'r+',label='Results by lobpcg') -legend() -xlabel(r'Eigenvalue $i$') -ylabel(r'$\lambda_i$') -show() + plot(arange(0,len(w[:m])),w[:m],'bx',label='Results by symeig') + plot(arange(0,len(eigs)),eigs,'r+',label='Results by lobpcg') + legend() + xlabel(r'Eigenvalue $i$') + ylabel(r'$\lambda_i$') + show() Modified: branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_interpolate.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_interpolate.py 2008-01-08 22:55:53 UTC (rev 3804) +++ branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_interpolate.py 2008-01-08 23:50:11 UTC (rev 3805) @@ -11,20 +11,20 @@ import numpy as N import numpy.core.numeric as numeric -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import * +import scipy.sandbox.maskedarray.testutils +from import scipy.sandbox.maskedarray.testutils import * import maskedarray.core as coremodule from maskedarray.core import MaskedArray, masked from timeseries.lib.interpolate import backward_fill, forward_fill, interp_masked1d -class TestFuncs(NumpyTestCase): +class TestFuncs(TestCase): def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.mask = [1,0,1,0,0,1,1,0,0,0] self.data = numeric.arange(10) self.test_array = masked_array(self.data, mask=self.mask) @@ -61,4 +61,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py 2008-01-08 22:55:53 UTC (rev 3804) +++ branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py 2008-01-08 23:50:11 UTC (rev 3805) @@ -13,7 +13,7 @@ import numpy as N import numpy.core.numeric as numeric -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import NumpyTest, TestCase import maskedarray.testutils from maskedarray.testutils import * @@ -28,10 +28,10 @@ from timeseries.lib import moving_funcs as MF -class TestCMovAverage(NumpyTestCase): +class TestCMovAverage(TestCase): def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.data = numeric.arange(25) self.maskeddata = MaskedArray(self.data) self.maskeddata[10] = masked @@ -84,10 +84,10 @@ -class TestMovFuncs(NumpyTestCase): +class TestMovFuncs(TestCase): def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.data = numeric.arange(25) self.maskeddata = MaskedArray(self.data) self.maskeddata[10] = masked @@ -150,4 +150,4 @@ #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: branches/testing_cleanup/scipy/setup.py =================================================================== --- branches/testing_cleanup/scipy/setup.py 2008-01-08 22:55:53 UTC (rev 3804) +++ branches/testing_cleanup/scipy/setup.py 2008-01-08 23:50:11 UTC (rev 3805) @@ -22,6 +22,7 @@ config.add_subpackage('ndimage') config.add_subpackage('stsci') config.add_subpackage('weave') + config.add_subpackage('testing') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config Modified: branches/testing_cleanup/scipy/testing/nosetester.py =================================================================== --- branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-08 22:55:53 UTC (rev 3804) +++ branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-08 23:50:11 UTC (rev 3805) @@ -49,11 +49,13 @@ ''' Module testing function labels - identifies tests to run. This can be a string to - pass to the nostests executable with the '-a' + pass to the nostests executable with the '-A' option, or one of several special values. Special values are: 'fast' - the default - which corresponds to - nosetests -a option of 'not slow and not bench'. + nosetests -A option of 'not slow and not bench'. + 'full' - fast (as above) and slow tests as in + nosetests -A option of 'not bench'. None or '' - run all tests and benchmarks verbose - verbosity value 1-10 @@ -64,6 +66,8 @@ if labels: if labels == 'fast': labels = 'not slow and not bench' + elif labels == 'full': + labels = 'not bench' argv += ['-A', labels] argv += ['--verbosity', str(verbose)] if doctests: Added: branches/testing_cleanup/scipy/testing/setup.py =================================================================== --- branches/testing_cleanup/scipy/testing/setup.py 2008-01-08 22:55:53 UTC (rev 3804) +++ branches/testing_cleanup/scipy/testing/setup.py 2008-01-08 23:50:11 UTC (rev 3805) @@ -0,0 +1,10 @@ +#!/usr/bin/env python + +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + config = Configuration('testing', parent_package, top_path) + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) From scipy-svn at scipy.org Tue Jan 8 19:54:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 18:54:02 -0600 (CST) Subject: [Scipy-svn] r3806 - trunk/scipy/sandbox/multigrid Message-ID: <20080109005402.EB13A39C031@new.scipy.org> Author: wnbell Date: 2008-01-08 18:53:59 -0600 (Tue, 08 Jan 2008) New Revision: 3806 Modified: trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sandbox/multigrid/sa.py Log: small change to SA Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-08 23:50:11 UTC (rev 3805) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-09 00:53:59 UTC (rev 3806) @@ -88,7 +88,7 @@ *Parameters*: A : {csr_matrix} - NxN matrix in CSR format + NxN matrix in CSR or BSR format B : {None, array_like} : optional Near-nullspace candidates stored in the columns of an NxK array. The default value B=None is equivalent to B=ones((N,1)) @@ -129,10 +129,12 @@ """ + A = A.asfptype() + if B is None: B = ones((A.shape[0],1),dtype=A.dtype) # use constant vector else: - B = asarray(B) + B = asarray(B,dtype=A.dtype) pre,post = None,None #preprocess/postprocess Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-08 23:50:11 UTC (rev 3805) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-09 00:53:59 UTC (rev 3806) @@ -103,8 +103,8 @@ def sa_fit_candidates(AggOp,candidates,tol=1e-10): - #TODO handle non-floating point candidates better - candidates = candidates.astype('float64') + if candidates.dtype != 'float32': + candidates = asarray(candidates,dtype='float64') K = candidates.shape[1] # num candidates From scipy-svn at scipy.org Tue Jan 8 20:08:17 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 19:08:17 -0600 (CST) Subject: [Scipy-svn] r3807 - in branches/testing_cleanup/scipy: testing weave/tests Message-ID: <20080109010817.6723439C031@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-08 19:08:07 -0600 (Tue, 08 Jan 2008) New Revision: 3807 Modified: branches/testing_cleanup/scipy/testing/decorators.py branches/testing_cleanup/scipy/testing/nosetester.py branches/testing_cleanup/scipy/weave/tests/test_catalog.py branches/testing_cleanup/scipy/weave/tests/test_ext_tools.py branches/testing_cleanup/scipy/weave/tests/test_inline_tools.py branches/testing_cleanup/scipy/weave/tests/test_numpy_scalar_spec.py branches/testing_cleanup/scipy/weave/tests/test_scxx_dict.py branches/testing_cleanup/scipy/weave/tests/test_scxx_object.py branches/testing_cleanup/scipy/weave/tests/test_scxx_sequence.py branches/testing_cleanup/scipy/weave/tests/test_size_check.py branches/testing_cleanup/scipy/weave/tests/test_slice_handler.py branches/testing_cleanup/scipy/weave/tests/test_standard_array_spec.py branches/testing_cleanup/scipy/weave/tests/weave_test_utils.py Log: Absolute paths for weave tests, added willfail decorator Modified: branches/testing_cleanup/scipy/testing/decorators.py =================================================================== --- branches/testing_cleanup/scipy/testing/decorators.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/testing/decorators.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -19,3 +19,11 @@ t.bench = True return t + +def willfail(t): + ''' Labels test as known failure + + This label allows the tester to deselect the test in standard cases ''' + t.willfail = True + t.__doc__ += '\n\nThis test will likely fail' + return t Modified: branches/testing_cleanup/scipy/testing/nosetester.py =================================================================== --- branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -5,57 +5,32 @@ import nose class NoseTester(object): - """ Scipy nose tests suite manager. + """ Scipy nose test runner. - Usage: NoseTester().test() + Usage: NoseTester().test() - is package path, package name or its module object. + is package path - None finds calling module path """ - def __init__(self, package=None): - if package is None: + def __init__(self, package_path=None): + if package_path is None: f = sys._getframe(1) - package = f.f_locals.get('__file__', None) - assert package is not None - self.package_path = os.path.dirname(package) - else: - self.package_path = self._process_package(package) - - def _process_package(self, package): - ''' Package can be module, path, or package name ''' - try: - pfile = package.__file__ - except AttributeError: - pass - else: - return os.path.dirname(pfile) - if os.path.isabs(package): - return package - if package.find(os.path.sep) == -1: - # Try scipy package name - import scipy - scipy.pkgload(package) - try: - module = getattr(scipy, package) - except AttributeError: - pass - else: - self.package_path = os.path.dirname(module.__file__) - return - # Default to relative path - self.package_path = os.path.abspath(package) - return - + package_path = f.f_locals.get('__file__', None) + assert package_path is not None + package_path = os.path.dirname(package_path) + self.package_path = package_path + def test(self, labels='fast', verbose=1, doctests=False, extra_argv=None): ''' Module testing function labels - identifies tests to run. This can be a string to - pass to the nostests executable with the '-A' + pass to the nosetests executable with the '-A' option, or one of several special values. Special values are: 'fast' - the default - which corresponds to - nosetests -A option of 'not slow and not bench'. + nosetests -A option of + 'not slow and not bench and not willfail'. 'full' - fast (as above) and slow tests as in - nosetests -A option of 'not bench'. + nosetests -A option of 'not bench and not willfail'. None or '' - run all tests and benchmarks verbose - verbosity value 1-10 @@ -65,9 +40,9 @@ argv = ['scipy module test', self.package_path, '-s'] if labels: if labels == 'fast': - labels = 'not slow and not bench' + labels = 'not slow and not bench and not willfail' elif labels == 'full': - labels = 'not bench' + labels = 'not bench and not willfail' argv += ['-A', labels] argv += ['--verbosity', str(verbose)] if doctests: Modified: branches/testing_cleanup/scipy/weave/tests/test_catalog.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_catalog.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_catalog.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -4,14 +4,13 @@ from scipy.testing import * -from weave import catalog +from scipy.weave import catalog - set_local_path() from weave_test_utils import * +restore_path() - class TestDefaultDir(TestCase): def test_is_writable(self): path = catalog.default_dir() Modified: branches/testing_cleanup/scipy/weave/tests/test_ext_tools.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_ext_tools.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_ext_tools.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -3,17 +3,17 @@ from scipy.testing import * -from weave import ext_tools, c_spec +from scipy.weave import ext_tools, c_spec try: - from weave.standard_array_spec import array_converter + from scipy.weave.standard_array_spec import array_converter except ImportError: pass # requires numpy.numerix set_local_path() from weave_test_utils import * +restore_path() - build_dir = empty_temp_dir() print 'building extensions here:', build_dir Modified: branches/testing_cleanup/scipy/weave/tests/test_inline_tools.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_inline_tools.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_inline_tools.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -3,12 +3,12 @@ from scipy.testing import * -from weave import inline_tools +from scipy.weave import inline_tools set_local_path() from test_scxx import * +restore_path() - class TestInline(TestCase): """ These are long running tests... Modified: branches/testing_cleanup/scipy/weave/tests/test_numpy_scalar_spec.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_numpy_scalar_spec.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_numpy_scalar_spec.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -12,14 +12,11 @@ import numpy from scipy.testing import * -from weave import inline_tools,ext_tools -from weave.build_tools import msvc_exists, gcc_exists -from weave.catalog import unique_file -from weave.numpy_scalar_spec import numpy_complex_scalar_converter +from scipy.weave import inline_tools,ext_tools +from scipy.weave.build_tools import msvc_exists, gcc_exists +from scipy.weave.catalog import unique_file +from scipy.weave.numpy_scalar_spec import numpy_complex_scalar_converter - - - def unique_mod(d,file_name): f = os.path.basename(unique_file(d,file_name)) m = os.path.splitext(f)[0] Modified: branches/testing_cleanup/scipy/weave/tests/test_scxx_dict.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_scxx_dict.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_scxx_dict.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -6,7 +6,7 @@ from scipy.testing import * -from weave import inline_tools +from scipy.weave import inline_tools @@ -112,7 +112,8 @@ self.generic_get('return_val = a["b"];') @dec.slow - def DOESNT_WORK_check_char_fail(self): + @dec.willfail + def test_char_fail(self): # We can't through a KeyError for dicts on RHS of # = but not on LHS. Not sure how to deal with this. try: @@ -134,7 +135,8 @@ self.generic_get(code,['a']) @dec.slow - def DOESNT_WORK_check_obj_fail(self): + @dec.willfail + def test_obj_fail(self): # We can't through a KeyError for dicts on RHS of # = but not on LHS. Not sure how to deal with this. try: Modified: branches/testing_cleanup/scipy/weave/tests/test_scxx_object.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_scxx_object.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_scxx_object.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -6,7 +6,7 @@ from scipy.testing import * -from weave import inline_tools +from scipy.weave import inline_tools class TestObjectConstruct(TestCase): Modified: branches/testing_cleanup/scipy/weave/tests/test_scxx_sequence.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_scxx_sequence.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_scxx_sequence.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -6,7 +6,7 @@ from scipy.testing import * -from weave import inline_tools +from scipy.weave import inline_tools # Test: Modified: branches/testing_cleanup/scipy/weave/tests/test_size_check.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_size_check.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_size_check.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -2,8 +2,8 @@ from numpy import * from scipy.testing import * -from weave import size_check -from weave.ast_tools import * +from scipy.weave import size_check +from scipy.weave.ast_tools import * import numpy as nx Modified: branches/testing_cleanup/scipy/weave/tests/test_slice_handler.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_slice_handler.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_slice_handler.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -1,9 +1,9 @@ from scipy.testing import * -from weave import slice_handler -from weave.slice_handler import indexed_array_pattern -from weave.ast_tools import * +from scipy.weave import slice_handler +from scipy.weave.slice_handler import indexed_array_pattern +from scipy.weave.ast_tools import * def print_assert_equal(test_string,actual,desired): Modified: branches/testing_cleanup/scipy/weave/tests/test_standard_array_spec.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/test_standard_array_spec.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/test_standard_array_spec.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -2,9 +2,8 @@ from numpy import * from scipy.testing import * -from weave import standard_array_spec +from scipy.weave import standard_array_spec - def remove_whitespace(in_str): out = in_str.replace(" ","") out = out.replace("\t","") Modified: branches/testing_cleanup/scipy/weave/tests/weave_test_utils.py =================================================================== --- branches/testing_cleanup/scipy/weave/tests/weave_test_utils.py 2008-01-09 00:53:59 UTC (rev 3806) +++ branches/testing_cleanup/scipy/weave/tests/weave_test_utils.py 2008-01-09 01:08:07 UTC (rev 3807) @@ -28,10 +28,7 @@ # mainly used by catalog tests ################################################### -from numpy.testing import set_package_path, restore_path -set_package_path() -from weave import catalog -restore_path() +from scipy.weave import catalog import glob From scipy-svn at scipy.org Tue Jan 8 22:32:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 8 Jan 2008 21:32:02 -0600 (CST) Subject: [Scipy-svn] r3808 - trunk/scipy/sandbox/timeseries Message-ID: <20080109033202.35E4439C00F@new.scipy.org> Author: mattknox_ca Date: 2008-01-08 21:31:57 -0600 (Tue, 08 Jan 2008) New Revision: 3808 Modified: trunk/scipy/sandbox/timeseries/dates.py Log: converted tabs to spaces Modified: trunk/scipy/sandbox/timeseries/dates.py =================================================================== --- trunk/scipy/sandbox/timeseries/dates.py 2008-01-09 01:08:07 UTC (rev 3807) +++ trunk/scipy/sandbox/timeseries/dates.py 2008-01-09 03:31:57 UTC (rev 3808) @@ -563,39 +563,39 @@ return fcode def guess_freq_date(dates): - """Tries to estimate the frequency of a sequence of datetime objects.""" - if not type(dates[0]) is dt.datetime: - raise AttributeError, "dates not a sequence of datetime objects." + """Tries to estimate the frequency of a sequence of datetime objects.""" + if not type(dates[0]) is dt.datetime: + raise AttributeError, "dates not a sequence of datetime objects." - sorted_dates = numpy.sort(dates) - ddif = numpy.diff(sorted_dates) - dset = set(ddif) - try: - dset.remove(dt.timedelta(0)) - except: - pass - res = min(dset) - if getattr(res, 'seconds', 0) >= 1: - fcode = _c.FR_SEC - elif getattr(res, 'seconds', 0) >= 60: - fcode = _c.FR_MIN - elif getattr(res, 'seconds', 0) >= 60*60: - fcode = _c.FR_HR - elif getattr(res, 'day', 0) >= 1: - fcode = _c.FR_DAY - elif getattr(res, 'day', 0) >= 7: - fcode = _c.FR_WK - elif getattr(res, 'month', 0) >= 1: - fcode = _c.FR_MTH - elif getattr(res, 'month', 0) >= 3: - fcode = _c.FR_QTR - elif getattr(res, 'year', 0) >= 1: - fcode = _c.FR_ANN - else: - warnings.warn("Unable to estimate the frequency! %s" % res.__str__()) - fcode = _c.FR_UND - return fcode - + sorted_dates = numpy.sort(dates) + ddif = numpy.diff(sorted_dates) + dset = set(ddif) + try: + dset.remove(dt.timedelta(0)) + except: + pass + res = min(dset) + if getattr(res, 'seconds', 0) >= 1: + fcode = _c.FR_SEC + elif getattr(res, 'seconds', 0) >= 60: + fcode = _c.FR_MIN + elif getattr(res, 'seconds', 0) >= 60*60: + fcode = _c.FR_HR + elif getattr(res, 'day', 0) >= 1: + fcode = _c.FR_DAY + elif getattr(res, 'day', 0) >= 7: + fcode = _c.FR_WK + elif getattr(res, 'month', 0) >= 1: + fcode = _c.FR_MTH + elif getattr(res, 'month', 0) >= 3: + fcode = _c.FR_QTR + elif getattr(res, 'year', 0) >= 1: + fcode = _c.FR_ANN + else: + warnings.warn("Unable to estimate the frequency! %s" % res.__str__()) + fcode = _c.FR_UND + return fcode + def _listparser(dlist, freq=None): "Constructs a DateArray from a list." @@ -614,8 +614,8 @@ if freq is None or freq == _c.FR_UND: freq = guess_freq(ords) if freq == _c.FR_UND: - dtobj = [DateTimeFromString(s) for s in dlist] - freq = guess_freq_date(dtobj) + dtobj = [DateTimeFromString(s) for s in dlist] + freq = guess_freq_date(dtobj) #...construct a list of dates for s in dlist: x = Date(freq, string=s) From scipy-svn at scipy.org Wed Jan 9 01:42:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 9 Jan 2008 00:42:40 -0600 (CST) Subject: [Scipy-svn] r3809 - in branches/testing_cleanup: . scipy/sandbox/multigrid scipy/sandbox/timeseries Message-ID: <20080109064240.850B539C0CC@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-09 00:42:31 -0600 (Wed, 09 Jan 2008) New Revision: 3809 Modified: branches/testing_cleanup/ branches/testing_cleanup/scipy/sandbox/multigrid/multilevel.py branches/testing_cleanup/scipy/sandbox/multigrid/sa.py branches/testing_cleanup/scipy/sandbox/timeseries/dates.py Log: Merged revisions 3806,3808 via svnmerge from http://svn.scipy.org/svn/scipy/trunk ........ r3806 | wnbell | 2008-01-08 16:53:59 -0800 (Tue, 08 Jan 2008) | 2 lines small change to SA ........ r3808 | mattknox_ca | 2008-01-08 19:31:57 -0800 (Tue, 08 Jan 2008) | 1 line converted tabs to spaces ........ Property changes on: branches/testing_cleanup ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3803 + /branches/scipy.scons:1-3533 /trunk:1-3662,3667-3672,3674-3675,3684,3723-3735,3738,3744,3749,3754-3755,3759,3761,3764,3769,3774,3778-3808 Modified: branches/testing_cleanup/scipy/sandbox/multigrid/multilevel.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/multilevel.py 2008-01-09 03:31:57 UTC (rev 3808) +++ branches/testing_cleanup/scipy/sandbox/multigrid/multilevel.py 2008-01-09 06:42:31 UTC (rev 3809) @@ -88,7 +88,7 @@ *Parameters*: A : {csr_matrix} - NxN matrix in CSR format + NxN matrix in CSR or BSR format B : {None, array_like} : optional Near-nullspace candidates stored in the columns of an NxK array. The default value B=None is equivalent to B=ones((N,1)) @@ -129,10 +129,12 @@ """ + A = A.asfptype() + if B is None: B = ones((A.shape[0],1),dtype=A.dtype) # use constant vector else: - B = asarray(B) + B = asarray(B,dtype=A.dtype) pre,post = None,None #preprocess/postprocess Modified: branches/testing_cleanup/scipy/sandbox/multigrid/sa.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/multigrid/sa.py 2008-01-09 03:31:57 UTC (rev 3808) +++ branches/testing_cleanup/scipy/sandbox/multigrid/sa.py 2008-01-09 06:42:31 UTC (rev 3809) @@ -103,8 +103,8 @@ def sa_fit_candidates(AggOp,candidates,tol=1e-10): - #TODO handle non-floating point candidates better - candidates = candidates.astype('float64') + if candidates.dtype != 'float32': + candidates = asarray(candidates,dtype='float64') K = candidates.shape[1] # num candidates Modified: branches/testing_cleanup/scipy/sandbox/timeseries/dates.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/dates.py 2008-01-09 03:31:57 UTC (rev 3808) +++ branches/testing_cleanup/scipy/sandbox/timeseries/dates.py 2008-01-09 06:42:31 UTC (rev 3809) @@ -563,39 +563,39 @@ return fcode def guess_freq_date(dates): - """Tries to estimate the frequency of a sequence of datetime objects.""" - if not type(dates[0]) is dt.datetime: - raise AttributeError, "dates not a sequence of datetime objects." + """Tries to estimate the frequency of a sequence of datetime objects.""" + if not type(dates[0]) is dt.datetime: + raise AttributeError, "dates not a sequence of datetime objects." - sorted_dates = numpy.sort(dates) - ddif = numpy.diff(sorted_dates) - dset = set(ddif) - try: - dset.remove(dt.timedelta(0)) - except: - pass - res = min(dset) - if getattr(res, 'seconds', 0) >= 1: - fcode = _c.FR_SEC - elif getattr(res, 'seconds', 0) >= 60: - fcode = _c.FR_MIN - elif getattr(res, 'seconds', 0) >= 60*60: - fcode = _c.FR_HR - elif getattr(res, 'day', 0) >= 1: - fcode = _c.FR_DAY - elif getattr(res, 'day', 0) >= 7: - fcode = _c.FR_WK - elif getattr(res, 'month', 0) >= 1: - fcode = _c.FR_MTH - elif getattr(res, 'month', 0) >= 3: - fcode = _c.FR_QTR - elif getattr(res, 'year', 0) >= 1: - fcode = _c.FR_ANN - else: - warnings.warn("Unable to estimate the frequency! %s" % res.__str__()) - fcode = _c.FR_UND - return fcode - + sorted_dates = numpy.sort(dates) + ddif = numpy.diff(sorted_dates) + dset = set(ddif) + try: + dset.remove(dt.timedelta(0)) + except: + pass + res = min(dset) + if getattr(res, 'seconds', 0) >= 1: + fcode = _c.FR_SEC + elif getattr(res, 'seconds', 0) >= 60: + fcode = _c.FR_MIN + elif getattr(res, 'seconds', 0) >= 60*60: + fcode = _c.FR_HR + elif getattr(res, 'day', 0) >= 1: + fcode = _c.FR_DAY + elif getattr(res, 'day', 0) >= 7: + fcode = _c.FR_WK + elif getattr(res, 'month', 0) >= 1: + fcode = _c.FR_MTH + elif getattr(res, 'month', 0) >= 3: + fcode = _c.FR_QTR + elif getattr(res, 'year', 0) >= 1: + fcode = _c.FR_ANN + else: + warnings.warn("Unable to estimate the frequency! %s" % res.__str__()) + fcode = _c.FR_UND + return fcode + def _listparser(dlist, freq=None): "Constructs a DateArray from a list." @@ -614,8 +614,8 @@ if freq is None or freq == _c.FR_UND: freq = guess_freq(ords) if freq == _c.FR_UND: - dtobj = [DateTimeFromString(s) for s in dlist] - freq = guess_freq_date(dtobj) + dtobj = [DateTimeFromString(s) for s in dlist] + freq = guess_freq_date(dtobj) #...construct a list of dates for s in dlist: x = Date(freq, string=s) From scipy-svn at scipy.org Wed Jan 9 15:55:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 9 Jan 2008 14:55:57 -0600 (CST) Subject: [Scipy-svn] r3810 - in branches/testing_cleanup/scipy: linsolve/umfpack/tests stats stats/tests testing Message-ID: <20080109205557.B202539C2DB@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-09 14:55:47 -0600 (Wed, 09 Jan 2008) New Revision: 3810 Modified: branches/testing_cleanup/scipy/linsolve/umfpack/tests/test_umfpack.py branches/testing_cleanup/scipy/stats/info.py branches/testing_cleanup/scipy/stats/morestats.py branches/testing_cleanup/scipy/stats/tests/test_morestats.py branches/testing_cleanup/scipy/testing/decorators.py branches/testing_cleanup/scipy/testing/nosetester.py Log: Fine tuning of test selection Modified: branches/testing_cleanup/scipy/linsolve/umfpack/tests/test_umfpack.py =================================================================== --- branches/testing_cleanup/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-09 06:42:31 UTC (rev 3809) +++ branches/testing_cleanup/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-09 20:55:47 UTC (rev 3810) @@ -16,11 +16,14 @@ import numpy as nm import scipy.linsolve.umfpack as um +# Allow disabling of nose tests if umfpack not present +have_umfpack = um.umfpack._um is not None - class TestSolvers(TestCase): """Tests inverting a sparse linear system""" + __test__ = have_umfpack + def test_solve_complex_without_umfpack(self): """Solve: single precision complex""" linsolve.use_solver( useUmfpack = False ) @@ -107,6 +110,8 @@ class TestFactorization(TestCase): """Tests factorizing a sparse linear system""" + __test__ = have_umfpack + def test_complex_lu(self): """Getting factors of complex matrix""" umfpack = um.UmfpackContext("zi") Modified: branches/testing_cleanup/scipy/stats/info.py =================================================================== --- branches/testing_cleanup/scipy/stats/info.py 2008-01-09 06:42:31 UTC (rev 3809) +++ branches/testing_cleanup/scipy/stats/info.py 2008-01-09 20:55:47 UTC (rev 3810) @@ -198,7 +198,7 @@ levene -- _ shapiro -- _ anderson -- _ -binom_p -- _ +binom_test -- _ fligner -- _ mood -- _ oneway -- _ Modified: branches/testing_cleanup/scipy/stats/morestats.py =================================================================== --- branches/testing_cleanup/scipy/stats/morestats.py 2008-01-09 06:42:31 UTC (rev 3809) +++ branches/testing_cleanup/scipy/stats/morestats.py 2008-01-09 20:55:47 UTC (rev 3810) @@ -17,11 +17,12 @@ import scipy.special as special import futil import numpy as sb +from scipy.testing.decorators import not_a_test __all__ = ['find_repeats', 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot', 'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot', - 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene', 'binom_p', + 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene', 'binom_test', 'fligner', 'mood', 'oneway', 'wilcoxon', 'pdf_moments', 'pdf_fromgamma', 'pdfapprox', 'circmean', 'circvar', 'circstd', @@ -769,7 +770,8 @@ pval = distributions.f.sf(W,k-1,Ntot-k) # 1 - cdf return W, pval -def binom_p(x,n=None,p=0.5): + at not_a_test +def binom_test(x,n=None,p=0.5): """An exact (two-sided) test of the null hypothesis that the probability of success in a Bernoulli experiment is p. Modified: branches/testing_cleanup/scipy/stats/tests/test_morestats.py =================================================================== --- branches/testing_cleanup/scipy/stats/tests/test_morestats.py 2008-01-09 06:42:31 UTC (rev 3809) +++ branches/testing_cleanup/scipy/stats/tests/test_morestats.py 2008-01-09 20:55:47 UTC (rev 3810) @@ -96,11 +96,11 @@ class TestBinomP(TestCase): def test_data(self): - pval = stats.binom_p(100,250) + pval = stats.binom_test(100,250) assert_almost_equal(pval,0.0018833009350757682,11) - pval = stats.binom_p(201,405) + pval = stats.binom_test(201,405) assert_almost_equal(pval,0.92085205962670713,11) - pval = stats.binom_p([682,243],p=3.0/4) + pval = stats.binom_test([682,243],p=3.0/4) assert_almost_equal(pval,0.38249155957481695,11) class TestFindRepeats(TestCase): Modified: branches/testing_cleanup/scipy/testing/decorators.py =================================================================== --- branches/testing_cleanup/scipy/testing/decorators.py 2008-01-09 06:42:31 UTC (rev 3809) +++ branches/testing_cleanup/scipy/testing/decorators.py 2008-01-09 20:55:47 UTC (rev 3810) @@ -25,5 +25,10 @@ This label allows the tester to deselect the test in standard cases ''' t.willfail = True - t.__doc__ += '\n\nThis test will likely fail' return t + +def not_a_test(t): + ''' Signals to nose that this function is not a test + ''' + t.__test__ = False + return t Modified: branches/testing_cleanup/scipy/testing/nosetester.py =================================================================== --- branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-09 06:42:31 UTC (rev 3809) +++ branches/testing_cleanup/scipy/testing/nosetester.py 2008-01-09 20:55:47 UTC (rev 3810) @@ -9,7 +9,7 @@ Usage: NoseTester().test() - is package path - None finds calling module path + is package path - None finds calling module path """ def __init__(self, package_path=None): if package_path is None: @@ -50,4 +50,5 @@ if extra_argv: argv+= extra_argv nose.run(argv=argv) + From scipy-svn at scipy.org Wed Jan 9 19:45:45 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 9 Jan 2008 18:45:45 -0600 (CST) Subject: [Scipy-svn] r3811 - in branches/testing_cleanup/scipy/sandbox: exmplpackage exmplpackage/tests timeseries/lib/tests Message-ID: <20080110004545.3419B39C165@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-09 18:45:34 -0600 (Wed, 09 Jan 2008) New Revision: 3811 Removed: branches/testing_cleanup/scipy/sandbox/exmplpackage/__init__.py branches/testing_cleanup/scipy/sandbox/exmplpackage/foo.py branches/testing_cleanup/scipy/sandbox/exmplpackage/info_exmplpackage.py branches/testing_cleanup/scipy/sandbox/exmplpackage/setup.py branches/testing_cleanup/scipy/sandbox/exmplpackage/spam_src.pyf branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/decorators.py branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/ntest.py branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/tstsupport.py branches/testing_cleanup/scipy/sandbox/exmplpackage/yyy/ Modified: branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/README.txt branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_interpolate.py branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py Log: Cleaned out example package, fixed timeseries tests Deleted: branches/testing_cleanup/scipy/sandbox/exmplpackage/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/__init__.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/__init__.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -1,15 +0,0 @@ -# -# exmplpackage - Example of a Scipy module, see DEVELOPERS.txt -# - -# Get documentation string: -from info_exmplpackage import __doc__ - -# Import symbols from sub-module: -from foo import * - -# Import sub-package: -import yyy - -# Import extension module -import spam Deleted: branches/testing_cleanup/scipy/sandbox/exmplpackage/foo.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/foo.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/foo.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -1,17 +0,0 @@ -""" -foo - Scipy module exmplpackage submodule. -""" - -__all__ = ['exmplpackage_foo_bar','foo_gun'] - -def exmplpackage_foo_bar(): - """ - Scipy module exmplpackage global (see info_exmplpackage.py) test function. - """ - return "Hello from exmplpackage_foo_bar" - -def foo_gun(): - """ - Scipy module exmplpackage test function. - """ - return "Hello from foo_gun" Deleted: branches/testing_cleanup/scipy/sandbox/exmplpackage/info_exmplpackage.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/info_exmplpackage.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/info_exmplpackage.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -1,13 +0,0 @@ -""" -Scipy example module for developers - -This is documentation of exmplpackage. -Provides: - exmplpackage_foo_bar - also available in scipy name space - foo_gun - yyy.fun -""" - -global_symbols = ['exmplpackage_foo_bar'] - -postpone_import = 1 Deleted: branches/testing_cleanup/scipy/sandbox/exmplpackage/setup.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/setup.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/setup.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -1,39 +0,0 @@ -#!/usr/bin/env python - -from os.path import join - -def configuration(parent_package='',top_path=None): - # The following two lines with `return config` constitutes a - # minimal contents of configuration(..) that is suitable for pure - # Python packages. - from numpy.distutils.misc_util import Configuration - config = Configuration('exmplpackage',parent_package,top_path) - - # include test scripts from tests - config.add_data_dir('tests') - - # exmplpackage contains Python sub-package yyy - config.add_subpackage('yyy') - - # exmplpackage generates source code, that will be processed with f2py - def generate_spam_pyf(ext, build_dir): - from distutils.dep_util import newer - target = join(build_dir,'spam.pyf') - source = ext.depends[0] - if newer(source,target): - fin = open(source) - body = fin.read() - fin.close() - fout = open(target,'w') - fout.write('python module spam\n%s\nend python module spam' % body) - fout.close() - return target - config.add_extension('spam', - sources = [generate_spam_pyf], - depends = ['spam_src.pyf']) - - return config - -if __name__ == '__main__': - from numpy.distutils.core import setup - setup(**configuration(top_path='').todict()) Deleted: branches/testing_cleanup/scipy/sandbox/exmplpackage/spam_src.pyf =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/spam_src.pyf 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/spam_src.pyf 2008-01-10 00:45:34 UTC (rev 3811) @@ -1,13 +0,0 @@ -usercode ''' -static char doc_spam_incr[] = "Return incremented argument"; -static PyObject *spam_incr(PyObject *self, PyObject *args) -{ - int input; - if (!PyArg_ParseTuple(args, "i", &input)) - return NULL; - return Py_BuildValue("i", input+1); -} -''' -pymethoddef ''' -{"incr", spam_incr, METH_VARARGS, doc_spam_incr}, -''' Modified: branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/README.txt =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/README.txt 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/README.txt 2008-01-10 00:45:34 UTC (rev 3811) @@ -47,11 +47,13 @@ and performs tests per level import scipy.mypackage -scipy.mypackage.test() # all unlabeled tests -scipy.mypackage.test('all') # unlabeled, labeled and doctests -scipy.mypackage.test(10) # as above, for compatibility, deprecated -scipy.mypackage.test(['slow']) # just slow tests -scipy.mypackage.test(['', 'slow']) # unlabeled and slow tests +scipy.mypackage.test() # fast, unlabeled tests +scipy.mypackage.test('full') # unlabeled, not slow, not villfail +scipy.mypackage.test('slow') # just slow tests +scipy.mypackage.test('bench') # just benchmarks +scipy.mypackage.test(None) # all possible tests, including benchmarks +scipy.mypackage.test(doctests=True) # fast tests, with doctests + At the base level, scipy.test(*args) collects the test suite from each package, and runs it, with *args as above. Deleted: branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/decorators.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/decorators.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/decorators.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -1,13 +0,0 @@ -"""Decorators for labeling test objects.""" - -def slow(t): - """Labels a test as 'slow'. - - The exact definition of a slow test is obviously both subjective and - hardware-dependent, but in general any individual test that requires more - than a second or two should be labeled as slow (the whole suite consits of - thousands of tests, so even a second is significant).""" - - t.slow = True - return t - Deleted: branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/ntest.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/ntest.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/ntest.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -1,37 +0,0 @@ -"""Simple testing utilities, to eventually be put into numpy.testing -""" - -import sys - -from numpy.distutils.misc_util import yellow_text, red_text -from numpy.testing.utils import jiffies - -def measure(code_str,times=1,label=None): - """ Return elapsed time for executing code_str in the - namespace of the caller for given times. - """ - frame = sys._getframe(1) - locs,globs = frame.f_locals,frame.f_globals - - code = compile(code_str, - 'Test name: %s ' % label, - 'exec') - i = 0 - elapsed = jiffies() - while i> sys.stdout, message - sys.stdout.flush() - -def warn(message): - print >> sys.stderr,yellow_text('Warning: %s' % (message)) - sys.stderr.flush() - -def error(message): - print >> sys.stderr,red_text('Error: %s' % (message)) - sys.stderr.flush() Modified: branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -25,7 +25,7 @@ # This single import statement should provide all the common functionality for # scipy tests in a single location. -from tstsupport import * +from scipy.testing import * def setup(): """Module-level setup""" Deleted: branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/tstsupport.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/tstsupport.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/tstsupport.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -1,15 +0,0 @@ -"""Common test support for all scipy test scripts. - -This single module should provide all the common functionality for scipy tests -in a single location, so that test script can just import it and work right -away. -""" - -from unittest import TestCase - -import nose - -# These two modules will need to be later put in the right places... -import decorators as dec - -from ntest import * Modified: branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_interpolate.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_interpolate.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_interpolate.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -13,13 +13,13 @@ from scipy.testing import * -import scipy.sandbox.maskedarray.testutils -from import scipy.sandbox.maskedarray.testutils import * +from scipy.sandbox.maskedarray.testutils import * -import maskedarray.core as coremodule -from maskedarray.core import MaskedArray, masked +import scipy.sandbox.maskedarray.core as coremodule +from scipy.sandbox.maskedarray.core import MaskedArray, masked -from timeseries.lib.interpolate import backward_fill, forward_fill, interp_masked1d +from scipy.sandbox.timeseries.lib.interpolate import \ + backward_fill, forward_fill, interp_masked1d class TestFuncs(TestCase): Modified: branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py =================================================================== --- branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py 2008-01-09 20:55:47 UTC (rev 3810) +++ branches/testing_cleanup/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py 2008-01-10 00:45:34 UTC (rev 3811) @@ -13,20 +13,19 @@ import numpy as N import numpy.core.numeric as numeric -from scipy.testing import NumpyTest, TestCase +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import * +from scipy.sandbox.maskedarray.testutils import * -import maskedarray as MA -import maskedarray.core as coremodule -from maskedarray.core import MaskedArray, masked -from maskedarray import mstats +import scipy.sandbox.maskedarray as MA +import scipy.sandbox.maskedarray.core as coremodule +from scipy.sandbox.maskedarray.core import MaskedArray, masked +from scipy.sandbox.maskedarray import mstats -import timeseries as TS -from timeseries import time_series, thisday +import scipy.sandbox.timeseries as TS +from scipy.sandbox.timeseries import time_series, thisday -from timeseries.lib import moving_funcs as MF +from scipy.sandbox.timeseries.lib import moving_funcs as MF class TestCMovAverage(TestCase): From scipy-svn at scipy.org Thu Jan 10 04:04:30 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 10 Jan 2008 03:04:30 -0600 (CST) Subject: [Scipy-svn] r3812 - in branches/testing_cleanup/scipy: stats testing Message-ID: <20080110090430.9EE3539C183@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-10 03:04:27 -0600 (Thu, 10 Jan 2008) New Revision: 3812 Modified: branches/testing_cleanup/scipy/stats/morestats.py branches/testing_cleanup/scipy/testing/decorators.py Log: Revised nose test discovery decorator Modified: branches/testing_cleanup/scipy/stats/morestats.py =================================================================== --- branches/testing_cleanup/scipy/stats/morestats.py 2008-01-10 00:45:34 UTC (rev 3811) +++ branches/testing_cleanup/scipy/stats/morestats.py 2008-01-10 09:04:27 UTC (rev 3812) @@ -17,7 +17,7 @@ import scipy.special as special import futil import numpy as sb -from scipy.testing.decorators import not_a_test +from scipy.testing.decorators import is_nosetest __all__ = ['find_repeats', 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot', @@ -770,7 +770,7 @@ pval = distributions.f.sf(W,k-1,Ntot-k) # 1 - cdf return W, pval - at not_a_test + at is_nosetest(False) def binom_test(x,n=None,p=0.5): """An exact (two-sided) test of the null hypothesis that the probability of success in a Bernoulli experiment is p. Modified: branches/testing_cleanup/scipy/testing/decorators.py =================================================================== --- branches/testing_cleanup/scipy/testing/decorators.py 2008-01-10 00:45:34 UTC (rev 3811) +++ branches/testing_cleanup/scipy/testing/decorators.py 2008-01-10 09:04:27 UTC (rev 3812) @@ -27,8 +27,16 @@ t.willfail = True return t -def not_a_test(t): - ''' Signals to nose that this function is not a test +def is_nosetest(tf): + ''' Signals to nose that this function is or is not a test + + e.g + >>> @is_nosetest(False) + >>> def func_with_test_in_name(arg1, arg2): pass + ... + >>> ''' - t.__test__ = False - return t + def set_test(t): + t.__test__ = tf + return t + return set_test From scipy-svn at scipy.org Fri Jan 11 14:22:45 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 11 Jan 2008 13:22:45 -0600 (CST) Subject: [Scipy-svn] r3813 - in branches/testing_cleanup/scipy: sandbox testing testing/examples Message-ID: <20080111192245.C644C39C320@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-11 13:21:45 -0600 (Fri, 11 Jan 2008) New Revision: 3813 Added: branches/testing_cleanup/scipy/testing/examples/ branches/testing_cleanup/scipy/testing/examples/README.txt branches/testing_cleanup/scipy/testing/examples/test_foo.py Removed: branches/testing_cleanup/scipy/sandbox/exmplpackage/ Log: Move example tests to example in testing directory Copied: branches/testing_cleanup/scipy/testing/examples/README.txt (from rev 3811, branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/README.txt) Copied: branches/testing_cleanup/scipy/testing/examples/test_foo.py (from rev 3811, branches/testing_cleanup/scipy/sandbox/exmplpackage/tests/test_foo.py) From scipy-svn at scipy.org Fri Jan 11 20:51:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 11 Jan 2008 19:51:06 -0600 (CST) Subject: [Scipy-svn] r3814 - branches/testing_cleanup/scipy/sparse Message-ID: <20080112015106.602D339C047@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-11 19:50:57 -0600 (Fri, 11 Jan 2008) New Revision: 3814 Modified: branches/testing_cleanup/scipy/sparse/__init__.py branches/testing_cleanup/scipy/sparse/base.py branches/testing_cleanup/scipy/sparse/compressed.py branches/testing_cleanup/scipy/sparse/construct.py branches/testing_cleanup/scipy/sparse/coo.py branches/testing_cleanup/scipy/sparse/csc.py branches/testing_cleanup/scipy/sparse/csr.py branches/testing_cleanup/scipy/sparse/dia.py branches/testing_cleanup/scipy/sparse/info.py branches/testing_cleanup/scipy/sparse/lil.py branches/testing_cleanup/scipy/sparse/spfuncs.py branches/testing_cleanup/scipy/sparse/sputils.py Log: Found changes to sparse documentation from missed merge Modified: branches/testing_cleanup/scipy/sparse/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sparse/__init__.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/__init__.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -15,5 +15,5 @@ from spfuncs import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from scipy.testing.pkgtester import Tester -test = Tester().test +from numpy.testing import NumpyTest +test = NumpyTest().test Modified: branches/testing_cleanup/scipy/sparse/base.py =================================================================== --- branches/testing_cleanup/scipy/sparse/base.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/base.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -180,13 +180,15 @@ def asformat(self, format): """Return this matrix in a given sparse format - *Parameters*: - format : desired sparse matrix format - If format is None then no conversion is performed - Other possible values include: - "csr" for csr_matrix format - "csc" for csc_matrix format - "dok" for dok_matrix format and so on + Parameters + ========== + - format : desired sparse matrix format + - If format is None then no conversion is performed + - Other possible values include: + - "csr" for csr_matrix format + - "csc" for csc_matrix format + - "dok" for dok_matrix format and so on + """ if format is None or format == self.format: @@ -375,11 +377,12 @@ def rmatvec(self, other, conjugate=True): """Multiplies the vector 'other' by the sparse matrix, returning a dense vector as a result. - + If 'conjugate' is True: - returns A.transpose().conj() * other + - returns A.transpose().conj() * other Otherwise: - returns A.transpose() * other. + - returns A.transpose() * other. + """ return self.tocsr().rmatvec(other, conjugate=conjugate) Modified: branches/testing_cleanup/scipy/sparse/compressed.py =================================================================== --- branches/testing_cleanup/scipy/sparse/compressed.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/compressed.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -109,11 +109,13 @@ def check_format(self, full_check=True): """check whether the matrix format is valid - *Parameters*: - full_check: - True - rigorous check, O(N) operations : default - False - basic check, O(1) operations + Parameters + ========== + - full_check : {bool} + - True - rigorous check, O(N) operations : default + - False - basic check, O(1) operations + """ #use _swap to determine proper bounds major_name,minor_name = self._swap(('row','column')) Modified: branches/testing_cleanup/scipy/sparse/construct.py =================================================================== --- branches/testing_cleanup/scipy/sparse/construct.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/construct.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -25,19 +25,24 @@ B = spdiags(diags, offsets, m, n) - *Parameters*: - data : matrix whose rows contain the diagonal values - diags : diagonals to set - k = 0 - the main diagonal - k > 0 - the k-th upper diagonal - k < 0 - the k-th lower diagonal - m, n : dimensions of the result - format : format of the result (e.g. "csr") - By default (format=None) an appropriate sparse matrix - format is returned. This choice is subject to change. + Parameters + ========== + - data : matrix whose rows contain the diagonal values + - diags : diagonals to set + - k = 0 - the main diagonal + - k > 0 - the k-th upper diagonal + - k < 0 - the k-th lower diagonal + - m, n : dimensions of the result + - format : format of the result (e.g. "csr") + - By default (format=None) an appropriate sparse matrix + format is returned. This choice is subject to change. - *Example* - ------- + See Also + ======== + The dia_matrix class which implements the DIAgonal format. + + Example + ======= >>> data = array([[1,2,3,4]]).repeat(3,axis=0) >>> diags = array([0,-1,2]) >>> spdiags(data,diags,4,4).todense() @@ -76,16 +81,19 @@ def spkron(A, B, format=None): """kronecker product of sparse matrices A and B - *Parameters*: - A,B : sparse matrices - E.g. csr_matrix, csc_matrix, coo_matrix, etc. + Parameters + ========== + A,B : dense or sparse matrices + format : format of the result (e.g. "csr") + - By default (format=None) an appropriate sparse matrix + format is returned. This choice is subject to change. - *Returns*: - coo_matrix - kronecker product in COOrdinate format + Returns + ======= + kronecker product in a sparse matrix format - *Example*: - ------- + Examples + ======== >>> A = csr_matrix(array([[0,2],[5,0]])) >>> B = csr_matrix(array([[1,2],[3,4]])) @@ -95,8 +103,14 @@ [ 5., 10., 0., 0.], [ 15., 20., 0., 0.]]) + >>> spkron(A,[[1,2],[3,4]]).todense() + matrix([[ 0., 0., 2., 4.], + [ 0., 0., 6., 8.], + [ 5., 10., 0., 0.], + [ 15., 20., 0., 0.]]) + """ - #TODO optimize for small dense B and CSR A + #TODO optimize for small dense B and CSR A -> BSR B = coo_matrix(B) @@ -151,14 +165,15 @@ """Generate a lil_matrix of dimensions (r,c) with the k-th diagonal set to 1. - :Parameters: - r,c : int - Row and column-dimensions of the output. - k : int - Diagonal offset. In the output matrix, - out[m,m+k] == 1 for all m. - dtype : dtype - Data-type of the output array. + Parameters + ========== + - r,c : int + - row and column-dimensions of the output. + - k : int + - diagonal offset. In the output matrix, + - out[m,m+k] == 1 for all m. + - dtype : dtype + - data-type of the output array. """ warn("lil_eye is deprecated. use speye(... , format='lil') instead", \ @@ -171,19 +186,20 @@ def lil_diags(diags,offsets,(m,n),dtype='d'): """Generate a lil_matrix with the given diagonals. - :Parameters: - diags : list of list of values e.g. [[1,2,3],[4,5]] - Values to be placed on each indicated diagonal. - offsets : list of ints - Diagonal offsets. This indicates the diagonal on which - the given values should be placed. - (r,c) : tuple of ints - Row and column dimensions of the output. - dtype : dtype - Output data-type. + Parameters + ========== + - diags : list of list of values e.g. [[1,2,3],[4,5]] + - values to be placed on each indicated diagonal. + - offsets : list of ints + - diagonal offsets. This indicates the diagonal on which + the given values should be placed. + - (r,c) : tuple of ints + - row and column dimensions of the output. + - dtype : dtype + - output data-type. - Example: - ------- + Example + ======= >>> lil_diags([[1,2,3],[4,5],[6]],[0,1,2],(3,3)).todense() matrix([[ 1., 4., 6.], Modified: branches/testing_cleanup/scipy/sparse/coo.py =================================================================== --- branches/testing_cleanup/scipy/sparse/coo.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/coo.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -1,4 +1,4 @@ -""" A sparse matrix in COOrdinate format """ +""" A sparse matrix in COOrdinate or 'triplet' format""" __all__ = ['coo_matrix', 'isspmatrix_coo'] @@ -21,34 +21,52 @@ This can be instantiated in several ways: - coo_matrix(D) - with a dense matrix D + - with a dense matrix D - coo_matrix(S) - with another sparse matrix S (equivalent to S.tocoo()) + - with another sparse matrix S (equivalent to S.tocoo()) - coo_matrix((M, N), [dtype]) - to construct an empty matrix with shape (M, N) - dtype is optional, defaulting to dtype='d'. + - to construct an empty matrix with shape (M, N) + dtype is optional, defaulting to dtype='d'. - coo_matrix((data, ij), [shape=(M, N)]) - When shape is not specified, it is inferred from the index arrays: - ij[0][:] and ij[1][:] + - When shape is not specified, it is inferred from the index arrays: + - ij[0][:] and ij[1][:] - The arguments 'data' and 'ij' represent three arrays: - 1. data[:] the entries of the matrix, in any order - 2. ij[0][:] the row indices of the matrix entries - 3. ij[1][:] the column indices of the matrix entries - - So the following holds: - A[ij[0][k], ij[1][k] = data[k] + - The arguments 'data' and 'ij' represent three arrays: + 1. data[:] the entries of the matrix, in any order + 2. ij[0][:] the row indices of the matrix entries + 3. ij[1][:] the column indices of the matrix entries + So the following holds: + - A[ij[0][k], ij[1][k] = data[k] - Note: - When converting to CSR or CSC format, duplicate (i,j) entries - will be summed together. This facilitates efficient construction - of finite element matrices and the like. + Notes + ===== + Advantages of the COO format + ---------------------------- + - facilitates fast conversion among sparse formats + - permits duplicate entries (see example) + - faster conversion to CSR/CSC than LIL + + Disadvantages of the COO format + ------------------------------- + - does not currently support (forces COO->CSR conversion) + - arithmetic operations + - slicing + - matrix vector products + + Usage + ----- + - COO is a fast format for constructing sparse matrices + - once a matrix has been constructed, convert to CSR or + CSC format for fast arithmetic and matrix vector operations + - By default when converting to CSR or CSC format, duplicate (i,j) + entries will be summed together. This facilitates efficient + construction of finite element matrices and the like. (see example) - *Examples* - ---------- + Examples + ======== >>> from scipy.sparse import * >>> from scipy import * Modified: branches/testing_cleanup/scipy/sparse/csc.py =================================================================== --- branches/testing_cleanup/scipy/sparse/csc.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/csc.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -1,5 +1,4 @@ -"""Compressed Sparse Column matrix format -""" +"""Compressed Sparse Column matrix format""" __all__ = ['csc_matrix', 'isspmatrix_csc'] @@ -23,32 +22,45 @@ This can be instantiated in several ways: - csc_matrix(D) - with a dense matrix or rank-2 ndarray D + - with a dense matrix or rank-2 ndarray D - csc_matrix(S) - with another sparse matrix S (equivalent to S.tocsc()) + - with another sparse matrix S (equivalent to S.tocsc()) - csc_matrix((M, N), [dtype]) - to construct an empty matrix with shape (M, N) - dtype is optional, defaulting to dtype='d'. + - to construct an empty matrix with shape (M, N) + - dtype is optional, defaulting to dtype='d'. - csc_matrix((data, ij), [shape=(M, N)]) - where data, ij satisfy: - a[ij[0, k], ij[1, k]] = data[k] + - where data, ij satisfy: + - a[ij[0, k], ij[1, k]] = data[k] - csc_matrix((data, indices, indptr), [shape=(M, N)]) - is the native CSC representation where: - the row indices for column i are stored in - indices[ indptr[i]: indices[i+1] ] - and their corresponding values are stored in - data[ indptr[i]: indptr[i+1] ] - If the shape parameter is not supplied, the matrix dimensions - are inferred from the index arrays. + - is the standard CSC representation where + the row indices for column i are stored in + - indices[ indptr[i]: indices[i+1] ] + and their corresponding values are stored in + - data[ indptr[i]: indptr[i+1] ] + - If the shape parameter is not supplied, the matrix dimensions + are inferred from the index arrays. + Notes + ===== + Advantages of the CSC format + ---------------------------- + - efficient arithmetic operations CSC + CSC, CSC * CSC, etc. + - efficient column slicing + - fast matrix vector products (CSR,BSR may be faster) + + Disadvantages of the CSC format + ------------------------------- + - slow row slicing operations (prefer CSR) + - changes to the sparsity structure are expensive (prefer LIL, DOK) - *Examples* - ---------- + Examples + ======== + >>> from scipy.sparse import * >>> from scipy import * >>> csc_matrix( (3,4), dtype='i' ).todense() @@ -132,9 +144,9 @@ def get_submatrix( self, slice0, slice1 ): """Return a submatrix of this matrix (new matrix is created). Contigous range of rows and columns can be selected using: - 1. a slice object - 2. a tuple (from, to) - 3. a scalar for single row/column selection.""" + 1. a slice object + 2. a tuple (from, to) + 3. a scalar for single row/column selection.""" aux = _cs_matrix._get_submatrix( self, self.shape[1], self.shape[0], slice1, slice0 ) nr, nc = aux[3:] Modified: branches/testing_cleanup/scipy/sparse/csr.py =================================================================== --- branches/testing_cleanup/scipy/sparse/csr.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/csr.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -1,5 +1,4 @@ -"""Compressed Sparse Row matrix format -""" +"""Compressed Sparse Row matrix format""" __all__ = ['csr_matrix', 'isspmatrix_csr'] @@ -23,32 +22,47 @@ This can be instantiated in several ways: - csr_matrix(D) - with a dense matrix or rank-2 ndarray D + - with a dense matrix or rank-2 ndarray D - csr_matrix(S) - with another sparse matrix S (equivalent to S.tocsr()) + - with another sparse matrix S (equivalent to S.tocsr()) - csr_matrix((M, N), [dtype]) - to construct an empty matrix with shape (M, N) - dtype is optional, defaulting to dtype='d'. + - to construct an empty matrix with shape (M, N) + - dtype is optional, defaulting to dtype='d'. - csr_matrix((data, ij), [shape=(M, N)]) - where data, ij satisfy: - a[ij[0, k], ij[1, k]] = data[k] + - where data, ij satisfy: + - a[ij[0, k], ij[1, k]] = data[k] - csr_matrix((data, indices, indptr), [shape=(M, N)]) - is the native CSR representation where: - the column indices for row i are stored in - indices[ indptr[i]: indices[i+1] ] - and their corresponding values are stored in - data[ indptr[i]: indptr[i+1] ] - If the shape parameter is not supplied, the matrix dimensions - are inferred from the index arrays. + - is the standard CSR representation where + the column indices for row i are stored in + - indices[ indptr[i]: indices[i+1] ] + and their corresponding values are stored in + - data[ indptr[i]: indptr[i+1] ] + - If the shape parameter is not supplied, the matrix dimensions + are inferred from the index arrays. - *Examples* - ---------- + Notes + ===== + Advantages of the CSR format + ---------------------------- + - efficient arithmetic operations CSR + CSR, CSR * CSR, etc. + - efficient row slicing + - fast matrix vector products + + Disadvantages of the CSR format + ------------------------------- + - slow column slicing operations (prefer CSC) + - changes to the sparsity structure are expensive (prefer LIL, DOK) + + + Examples + ======== + >>> from scipy.sparse import * >>> from scipy import * >>> csr_matrix( (3,4), dtype='i' ).todense() @@ -146,10 +160,12 @@ def get_submatrix( self, slice0, slice1 ): """Return a submatrix of this matrix (new matrix is created). Contigous range of rows and columns can be selected using: - 1. a slice object - 2. a tuple (from, to) - 3. a scalar for single row/column selection.""" + 1. a slice object + 2. a tuple (from, to) + 3. a scalar for single row/column selection. + """ + aux = _cs_matrix._get_submatrix( self, self.shape[0], self.shape[1], slice0, slice1 ) nr, nc = aux[3:] Modified: branches/testing_cleanup/scipy/sparse/dia.py =================================================================== --- branches/testing_cleanup/scipy/sparse/dia.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/dia.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -15,23 +15,24 @@ This can be instantiated in several ways: - dia_matrix(D) - with a dense matrix + - with a dense matrix - dia_matrix(S) - with another sparse matrix S (equivalent to S.todia()) + - with another sparse matrix S (equivalent to S.todia()) - dia_matrix((M, N), [dtype]) - to construct an empty matrix with shape (M, N) - dtype is optional, defaulting to dtype='d'. + - to construct an empty matrix with shape (M, N) + dtype is optional, defaulting to dtype='d'. - dia_matrix((data, diags), shape=(M, N)) - where the data[k,:] stores the diagonal entries for - diagonal diag[k] (See example below) + - where the data[k,:] stores the diagonal entries for + diagonal diag[k] (See example below) - *Examples* - ---------- + Examples + ======== + >>> from scipy.sparse import * >>> from scipy import * >>> dia_matrix( (3,4), dtype='i').todense() Modified: branches/testing_cleanup/scipy/sparse/info.py =================================================================== --- branches/testing_cleanup/scipy/sparse/info.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/info.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -7,12 +7,14 @@ Original code by Travis Oliphant. Modified and extended by Ed Schofield, Robert Cimrman, and Nathan Bell. -There are five available sparse matrix types: - (1) csc_matrix: Compressed Sparse Column format - (2) csr_matrix: Compressed Sparse Row format - (3) lil_matrix: List of Lists format - (4) dok_matrix: Dictionary of Keys format - (5) coo_matrix: COOrdinate format (aka IJV, triplet format) +There are seven available sparse matrix types: + 1. csc_matrix: Compressed Sparse Column format + 2. csr_matrix: Compressed Sparse Row format + 3. bsr_matrix: Block Sparse Row format + 4. lil_matrix: List of Lists format + 5. dok_matrix: Dictionary of Keys format + 6. coo_matrix: COOrdinate format (aka IJV, triplet format) + 7. dig_matrix: DIAgonal format To construct a matrix efficiently, use either lil_matrix (recommended) or dok_matrix. The lil_matrix class supports basic slicing and fancy @@ -27,8 +29,10 @@ All conversions among the CSR, CSC, and COO formats are efficient, linear-time operations. -Example: +Example +======= Construct a 1000x1000 lil_matrix and add some values to it: + >>> from scipy import sparse, linsolve >>> from numpy import linalg >>> from numpy.random import rand @@ -38,22 +42,28 @@ >>> A.setdiag(rand(1000)) Now convert it to CSR format and solve (A A^T) x = b for x: + >>> A = A.tocsr() >>> b = rand(1000) >>> x = linsolve.spsolve(A * A.T, b) Convert it to a dense matrix and solve, and check that the result is the same: + >>> A_ = A.todense() >>> x_ = linalg.solve(A_ * A_.T, b) >>> err = linalg.norm(x-x_) Now we can print the error norm with: - print "Norm error =", err + + >>> print "Norm error =", err + It should be small :) -Example: +Example +======= Construct a matrix in COO format: + >>> from scipy import sparse >>> from numpy import array >>> I = array([0,3,1,0]) @@ -64,6 +74,7 @@ Notice that the indices do not need to be sorted. Duplicate (i,j) entries are summed when converting to CSR or CSC. + >>> I = array([0,0,1,3,1,0,0]) >>> J = array([0,2,1,3,1,0,0]) >>> V = array([1,1,1,1,1,1,1]) @@ -72,13 +83,13 @@ This is useful for constructing finite-element stiffness and mass matrices. -Further Details: +Further Details +=============== + CSR column indices are not necessarily sorted. Likewise for CSC row indices. Use the .sorted_indices() and .sort_indices() methods when - sorted indices are necessary. Note that there is no expectation for - sorted indices in the sparsetools module. Furthermore some sparsetools - functions produce matrices with unsorted indices even when sorted - input is given. + sorted indices are required (e.g. when passing data to other libraries). + """ postpone_import = 1 Modified: branches/testing_cleanup/scipy/sparse/lil.py =================================================================== --- branches/testing_cleanup/scipy/sparse/lil.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/lil.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -21,6 +21,27 @@ This contains a list (self.rows) of rows, each of which is a sorted list of column indices of non-zero elements. It also contains a list (self.data) of lists of these elements. + + Notes + ===== + Advantages of the LIL format + ---------------------------- + - supports flexible slicing + - changes to the matrix sparsity structure are efficient + + Disadvantages of the LIL format + ------------------------------- + - arithmetic operations LIL + LIL are slower than CSR/CSC + - slow column slicing + - matrix vector products are slower than CSR/CSC + + Usage + ----- + - LIL is a convenient format for constructing sparse matrices + - once a matrix has been constructed, convert to CSR or + CSC format for fast arithmetic and matrix vector operations + - consider using the COO format when constructing large matrices + """ def __init__(self, A=None, shape=None, dtype=None, copy=False): Modified: branches/testing_cleanup/scipy/sparse/spfuncs.py =================================================================== --- branches/testing_cleanup/scipy/sparse/spfuncs.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/spfuncs.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -14,9 +14,7 @@ from sparsetools import csr_count_blocks def extract_diagonal(A): - """ - extract_diagonal(A) returns the main diagonal of A. - """ + """extract_diagonal(A) returns the main diagonal of A.""" #TODO extract k-th diagonal if isspmatrix_csr(A) or isspmatrix_csc(A): fn = getattr(sparsetools, A.format + "_diagonal") @@ -33,7 +31,7 @@ """Attempt to determine the blocksize of a sparse matrix Returns a blocksize=(r,c) such that - A.nnz / A.tobsr( (r,c) ).nnz > efficiency + - A.nnz / A.tobsr( (r,c) ).nnz > efficiency """ if not (isspmatrix_csr(A) or isspmatrix_csc(A)): A = csr_matrix(A) Modified: branches/testing_cleanup/scipy/sparse/sputils.py =================================================================== --- branches/testing_cleanup/scipy/sparse/sputils.py 2008-01-11 19:21:45 UTC (rev 3813) +++ branches/testing_cleanup/scipy/sparse/sputils.py 2008-01-12 01:50:57 UTC (rev 3814) @@ -21,8 +21,8 @@ upcast(t0, t1, ..., tn) -> T where T is a supported dtype - *Example* - ------- + Example + ======= >>> upcast('int32') From scipy-svn at scipy.org Fri Jan 11 20:54:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 11 Jan 2008 19:54:26 -0600 (CST) Subject: [Scipy-svn] r3815 - branches/testing_cleanup/scipy/sparse Message-ID: <20080112015426.D053839C047@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-11 19:54:24 -0600 (Fri, 11 Jan 2008) New Revision: 3815 Modified: branches/testing_cleanup/scipy/sparse/__init__.py Log: and refixed sparse init for nose tests Modified: branches/testing_cleanup/scipy/sparse/__init__.py =================================================================== --- branches/testing_cleanup/scipy/sparse/__init__.py 2008-01-12 01:50:57 UTC (rev 3814) +++ branches/testing_cleanup/scipy/sparse/__init__.py 2008-01-12 01:54:24 UTC (rev 3815) @@ -15,5 +15,5 @@ from spfuncs import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test From scipy-svn at scipy.org Fri Jan 11 21:06:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 11 Jan 2008 20:06:26 -0600 (CST) Subject: [Scipy-svn] r3816 - trunk Message-ID: <20080112020626.7FC9339C3AB@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-11 20:06:23 -0600 (Fri, 11 Jan 2008) New Revision: 3816 Modified: trunk/ Log: Initialized merge tracking via "svnmerge" with revisions "1-3662" from http://svn.scipy.org/svn/scipy/branches/testing_cleanup Property changes on: trunk ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 + /branches/scipy.scons:1-3533 /branches/testing_cleanup:1-3662 From scipy-svn at scipy.org Sat Jan 12 01:54:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 00:54:03 -0600 (CST) Subject: [Scipy-svn] r3817 - in trunk/scipy/sandbox: . maskedarray maskedarray/alternative_versions maskedarray/tests Message-ID: <20080112065403.ADFB3C7C00A@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-12 00:53:41 -0600 (Sat, 12 Jan 2008) New Revision: 3817 Added: trunk/scipy/sandbox/maskedarray/ trunk/scipy/sandbox/maskedarray/.project trunk/scipy/sandbox/maskedarray/CHANGELOG trunk/scipy/sandbox/maskedarray/LICENSE trunk/scipy/sandbox/maskedarray/README trunk/scipy/sandbox/maskedarray/__init__.py trunk/scipy/sandbox/maskedarray/alternative_versions/ trunk/scipy/sandbox/maskedarray/alternative_versions/core_alt.py trunk/scipy/sandbox/maskedarray/alternative_versions/core_ini.py trunk/scipy/sandbox/maskedarray/alternative_versions/core_initial.py trunk/scipy/sandbox/maskedarray/alternative_versions/test_mrecarray.py trunk/scipy/sandbox/maskedarray/bench.py trunk/scipy/sandbox/maskedarray/core.py trunk/scipy/sandbox/maskedarray/extras.py trunk/scipy/sandbox/maskedarray/morestats.py trunk/scipy/sandbox/maskedarray/mpl_maskedarray.patch trunk/scipy/sandbox/maskedarray/mrecords.py trunk/scipy/sandbox/maskedarray/mstats.py trunk/scipy/sandbox/maskedarray/setup.py trunk/scipy/sandbox/maskedarray/tests/ trunk/scipy/sandbox/maskedarray/tests/test_core.py trunk/scipy/sandbox/maskedarray/tests/test_extras.py trunk/scipy/sandbox/maskedarray/tests/test_morestats.py trunk/scipy/sandbox/maskedarray/tests/test_mrecords.py trunk/scipy/sandbox/maskedarray/tests/test_mstats.py trunk/scipy/sandbox/maskedarray/tests/test_subclassing.py trunk/scipy/sandbox/maskedarray/testutils.py trunk/scipy/sandbox/maskedarray/timer_comparison.py trunk/scipy/sandbox/maskedarray/version.py Log: Added back interim copy of maskedarray - will soon be removed in favor of numpy merged version Added: trunk/scipy/sandbox/maskedarray/.project =================================================================== --- trunk/scipy/sandbox/maskedarray/.project 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/.project 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,17 @@ + + + scipy_svn_maskedarray + + + + + + org.python.pydev.PyDevBuilder + + + + + + org.python.pydev.pythonNature + + Added: trunk/scipy/sandbox/maskedarray/CHANGELOG =================================================================== --- trunk/scipy/sandbox/maskedarray/CHANGELOG 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/CHANGELOG 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,117 @@ + The maskedarray package went through some major updates recently. +Originally, a MaskedArray object had two major attributes: (i) _data, a +(subclass of) ndarray that stored the values, and (ii) _mask, a ndarray of +booleans storing whether the values were masekd or not. This structure was +directly derived from the original implementation of MaskedArray, available in +numpy.core.ma. + +However, this approach wasn't very natural. For example, in order to access the +data of a MaskedArray instance, one had to query the _data attribute instead of +the instance itself. In addition, the previous implementation of MaskedArray as +a subclass of ndarray presented some problems. Thus, most of the attributes of +a MaskedArray object were defined as class defaults, which turned out to be +thread-unsafe. Moreover, subclassing MaskedArray wasn't straightforward, when +the subclass introduced new parameters in its __new__ method. + +The current implementation tries to alleviate these problems. The most +significant difference is that the _data attribute is now a view of the array +as a (subclass of) ndarray. The actual type is set by the _baseclass attribute, +defined at the creation of a new masked array as the class of the underlying +data. Thus, it is still possible to use a matrix object as the underlying data: +the new masked array will then use the matrix methods. Note that if the +underlying data has its own attributes, these latter are not propagated to the +MaskedArray instance, but are reinitialized at each access. In other terms, you +will lose specific values of these attributes during processing. You should +then consider defining a subclass of MaskedArray. Note also that because the +_data attribute is a view, any attempt to directly set it will likely fail. For +example, x._data = 5 will raise an AttributeError exception. You should then +use x._data[:] = 5 instead). + +The _mask attibute is left unchanged. Because it is a basic attribute, it can +be overwritten far too easily. If you want to specify a new value for the mask, +you should use the _setmask or __setmask__ methods: these methods ensure that +the new mask has the same shape as the data, and that the _hardmask condition +is respected. Note that in some particular cases involving subclasses of +MaskedArray, the mask is not always propagated properly. It is recommended to +set the mask of the base object, instead of trying to set the mask through a +view of MaskedArray. + +Following the suggestions of Reggie Dugard, the class defaults have been +suppressed. Unfortunately, that required to add some extra definitions in the +__array_finalize__ method, which tends to have a slight negative impact on +performances. Moreover, most methods now return a view of the masked array +instead of creating a new masked array from scratch. + + +The previous implementation of MaskedArray is called core_ini.py and it can be +found in the alternative_versions directory. This folder contains also yet +another implementation core_alt. This latter is left for documentation purposes, +and should serve as a template when we'll port the package to C. It introduces +yet another attribute, _masklayer. This attribute is always a ndarray of booleans +with the same shape as the data, that stores the values of the masked. The _mask +attribute is then a property, that returns _masklayer or nomask depending on +the value of the _smallmask flag and the values of _masklayer. This approach +seems to solve the anomaly in mask propagation mentioned earlier. However, some +performance tests show that this approach is significantly slower (from 10% to +50%) than the current implementation. It was therfore decided to leave it out of +the main package. + +#............................................................................... +2007-01-22 : core : fixed a call to numpy.float128 on 32b machines +2007-01-21 : core : fixed max/min_fill_values + : : fixed sort (as method and function) +2007-01-18 : core : fixed default filling values for unsigned int_. +2007-01-16 : extras : new function : `mediff1d` +2007-01-15 : mrecords: new method: `addfield` + : core : Force the mask of a masked array `x` to be copied w/... + ...masked_array(x,copy=True,mask=nomask,keep_mask=true) +2007-01-14 : mrecords: Slices are now properly supported + : mrecords: `filled` is now properly supported +2007-01-12 : mrecords: Complete reorganization... +2007-01-10 : mrecords: Defines a class of records that support masked arrays +2007-01-08 : Core: + : core : Force a reset of the class defaults after initialization + : core : Modified __array_finallize__ to allow objects w/ _data... + ... _mask fields to be recognized as MA +2007-01-04 : core : Fixed a but in masked_all_like +2007-01-02 : extras : Force apply_along_axis to output the proper fill_value + : core : Can use dtypes for the definition of default_fill_value +2006-12-30 : core : Cleaned up setitem/setslice w/ hard_mask=True + : core : Fixed masked_unary/binary_operations... + ...to work with subclasses of MaskedArray +2006-12-22 : core : Optimized(?) default_/maximum_/minimum_fill_value + : core : Force __new__ to not return a MaskedArray, in order to ... + : ... optimize __array_finalize__ + : core : Add the hard_mask flag to __new__ (*[False]*) +2006-12-19 : core : Fixed a problem on _set_mask which prevented to set a mask to nomask + : extras : Renamed compress2d to compress_rowcols + : extras : Added dot +2006-12-18 : extras : Added compress2d and mask_rowcols + : extras : moved 'average' to 'extras' +2006-12-13 : core : Fixed make_mask (forced filling to True) + : core : Fixed ndim + : core : Fixed error message in __new__ when wrong sizes + : core : Fixed the reshape function. + : extras : masked_all: set default dtype to float_ + : extras : _fromnxfunctions: make sure that list are recognized + : extras : added notmasked_edges, notmasked_contiguous +2006-12-09 : - Code reorganization: define 2 modules, core and extras +2006-11-25 : core : Disable copy by default + core : Added keep_mask flag (to save mask when creating a ma from a ma) + core : Fixed functions: empty_like + core : Fixed methods: .any and .all + core : New functions: masked_all, masked_all_like + core : New methods: .squeeze +2006-11-20 : core : fixed make_mask + core : fixed nonzero method +2006-11-16 : core : fixed .T +2006-11-12 : core : add max, min as function (not only method...) + core : repr returns a name like masked_xxx, where xxx is the subclass +2006-10-31 : core : make sure that make_mask returns a pure ndarray. +2006-10-30 : core : When converted to a float, a masked singleton is ... + ...transformed to nan instead of raising an exception. +21: Use __get__ method in _arraymethods, _arithmethods, _compamethods +18: Updated put to match the definition of numpy 1.0, deleted putmask, changed resize +2: prevent an extra kword being sent to make_mask_none + +#............................................................ \ No newline at end of file Added: trunk/scipy/sandbox/maskedarray/LICENSE =================================================================== --- trunk/scipy/sandbox/maskedarray/LICENSE 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/LICENSE 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,24 @@ +* Copyright (c) 2006, University of Georgia and Pierre G.F. Gerard-Marchant +* All rights reserved. +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the Univeristy of Georgia nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file Added: trunk/scipy/sandbox/maskedarray/README =================================================================== --- trunk/scipy/sandbox/maskedarray/README 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/README 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1 @@ +# An alternative implementation of masked arrays in numpy \ No newline at end of file Added: trunk/scipy/sandbox/maskedarray/__init__.py =================================================================== --- trunk/scipy/sandbox/maskedarray/__init__.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/__init__.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,22 @@ +"""Masked arrays add-ons. + +A collection of utilities for maskedarray + +:author: Pierre GF Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: __init__.py 3473 2007-10-29 15:18:13Z jarrod.millman $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" +__version__ = '1.0' +__revision__ = "$Revision: 3473 $" +__date__ = '$Date: 2007-10-29 08:18:13 -0700 (Mon, 29 Oct 2007) $' + +import core +from core import * + +import extras +from extras import * + +__all__ = ['core', 'extras'] +__all__ += core.__all__ +__all__ += extras.__all__ Added: trunk/scipy/sandbox/maskedarray/alternative_versions/core_alt.py =================================================================== --- trunk/scipy/sandbox/maskedarray/alternative_versions/core_alt.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/alternative_versions/core_alt.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,2993 @@ +# pylint: disable-msg=E1002 +"""MA: a facility for dealing with missing observations +MA is generally used as a numpy.array look-alike. +by Paul F. Dubois. + +Copyright 1999, 2000, 2001 Regents of the University of California. +Released for unlimited redistribution. +Adapted for numpy_core 2005 by Travis Oliphant and +(mainly) Paul Dubois. + +Subclassing of the base ndarray 2006 by Pierre Gerard-Marchant. +pgmdevlist_AT_gmail_DOT_com +Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com) + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: core_alt.py 3473 2007-10-29 15:18:13Z jarrod.millman $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" +__version__ = '1.0' +__revision__ = "$Revision: 3473 $" +__date__ = '$Date: 2007-10-29 08:18:13 -0700 (Mon, 29 Oct 2007) $' + +__all__ = ['MAError', 'MaskType', 'MaskedArray', + 'bool_', 'complex_', 'float_', 'int_', 'object_', + 'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue', + 'amax', 'amin', 'anom', 'anomalies', 'any', 'arange', + 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', + 'arctanh', 'argmax', 'argmin', 'argsort', 'around', + 'array', 'asarray', + 'bitwise_and', 'bitwise_or', 'bitwise_xor', + 'ceil', 'choose', 'compressed', 'concatenate', 'conjugate', + 'cos', 'cosh', 'count', + 'diagonal', 'divide', 'dump', 'dumps', + 'empty', 'empty_like', 'equal', 'exp', + 'fabs', 'fmod', 'filled', 'floor', 'floor_divide', + 'getmask', 'getmaskarray', 'greater', 'greater_equal', 'hypot', + 'ids', 'inner', 'innerproduct', + 'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', + 'left_shift', 'less', 'less_equal', 'load', 'loads', 'log', 'log10', + 'logical_and', 'logical_not', 'logical_or', 'logical_xor', + 'make_mask', 'make_mask_none', 'mask_or', 'masked', + 'masked_array', 'masked_equal', 'masked_greater', + 'masked_greater_equal', 'masked_inside', 'masked_less', + 'masked_less_equal', 'masked_not_equal', 'masked_object', + 'masked_outside', 'masked_print_option', 'masked_singleton', + 'masked_values', 'masked_where', 'max', 'maximum', 'mean', 'min', + 'minimum', 'multiply', + 'negative', 'nomask', 'nonzero', 'not_equal', + 'ones', 'outer', 'outerproduct', + 'power', 'product', 'ptp', 'put', 'putmask', + 'rank', 'ravel', 'remainder', 'repeat', 'reshape', 'resize', + 'right_shift', 'round_', + 'shape', 'sin', 'sinh', 'size', 'sometrue', 'sort', 'sqrt', 'std', + 'subtract', 'sum', 'swapaxes', + 'take', 'tan', 'tanh', 'transpose', 'true_divide', + 'var', 'where', + 'zeros'] + +import sys +import types +import cPickle +# +import numpy +from numpy import bool_, complex_, float_, int_, object_, str_ + +import numpy.core.umath as umath +import numpy.core.fromnumeric as fromnumeric +from numpy.core.numeric import ndarray +from numpy.core.fromnumeric import amax, amin +import numpy.core.numerictypes as ntypes +from numpy.core.numerictypes import bool_, typecodes +from numpy.core.multiarray import dtype +import numpy.core.numeric as numeric +from numpy.lib.shape_base import expand_dims as n_expand_dims +import warnings + + +MaskType = bool_ +nomask = MaskType(0) + +divide_tolerance = 1.e-35 +numpy.seterr(all='ignore') + +# TODO: There's still a problem with N.add.reduce not working... +# TODO: ...neither does N.add.accumulate + +#####-------------------------------------------------------------------------- +#---- --- Exceptions --- +#####-------------------------------------------------------------------------- +class MAError(Exception): + "Class for MA related errors." + def __init__ (self, args=None): + "Creates an exception." + Exception.__init__(self,args) + self.args = args + def __str__(self): + "Calculates the string representation." + return str(self.args) + __repr__ = __str__ + +#####-------------------------------------------------------------------------- +#---- --- Filling options --- +#####-------------------------------------------------------------------------- +# b: boolean - c: complex - f: floats - i: integer - O: object - S: string +default_filler = {'b': True, + 'c' : 1.e20 + 0.0j, + 'f' : 1.e20, + 'i' : 999999, + 'O' : '?', + 'S' : 'N/A', + 'u' : 999999, + 'V' : '???', + } +max_filler = ntypes._minvals +max_filler.update([(k,-numeric.inf) for k in [numpy.float32, numpy.float64]]) +min_filler = ntypes._maxvals +min_filler.update([(k,numeric.inf) for k in [numpy.float32, numpy.float64]]) +if 'float128' in ntypes.typeDict: + max_filler.update([(numpy.float128,-numeric.inf)]) + min_filler.update([(numpy.float128, numeric.inf)]) + + +def default_fill_value(obj): + "Calculates the default fill value for an object `obj`." + if hasattr(obj,'dtype'): + defval = default_filler[obj.dtype.kind] + elif isinstance(obj, numeric.dtype): + defval = default_filler[obj.kind] + elif isinstance(obj, float): + defval = default_filler['f'] + elif isinstance(obj, int) or isinstance(obj, long): + defval = default_filler['i'] + elif isinstance(obj, str): + defval = default_filler['S'] + elif isinstance(obj, complex): + defval = default_filler['c'] + else: + defval = default_filler['O'] + return defval + +def minimum_fill_value(obj): + "Calculates the default fill value suitable for taking the minimum of `obj`." + if hasattr(obj, 'dtype'): + objtype = obj.dtype + filler = min_filler[objtype] + if filler is None: + raise TypeError, 'Unsuitable type for calculating minimum.' + return filler + elif isinstance(obj, float): + return min_filler[ntypes.typeDict['float_']] + elif isinstance(obj, int): + return min_filler[ntypes.typeDict['int_']] + elif isinstance(obj, long): + return min_filler[ntypes.typeDict['uint']] + elif isinstance(obj, numeric.dtype): + return min_filler[obj] + else: + raise TypeError, 'Unsuitable type for calculating minimum.' + +def maximum_fill_value(obj): + "Calculates the default fill value suitable for taking the maximum of `obj`." + if hasattr(obj, 'dtype'): + objtype = obj.dtype + filler = max_filler[objtype] + if filler is None: + raise TypeError, 'Unsuitable type for calculating minimum.' + return filler + elif isinstance(obj, float): + return max_filler[ntypes.typeDict['float_']] + elif isinstance(obj, int): + return max_filler[ntypes.typeDict['int_']] + elif isinstance(obj, long): + return max_filler[ntypes.typeDict['uint']] + elif isinstance(obj, numeric.dtype): + return max_filler[obj] + else: + raise TypeError, 'Unsuitable type for calculating minimum.' + +def set_fill_value(a, fill_value): + "Sets the fill value of `a` if it is a masked array." + if isinstance(a, MaskedArray): + a.set_fill_value(fill_value) + +def get_fill_value(a): + """Returns the fill value of `a`, if any. + Otherwise, returns the default fill value for that type. + """ + if isinstance(a, MaskedArray): + result = a.fill_value + else: + result = default_fill_value(a) + return result + +def common_fill_value(a, b): + "Returns the common fill_value of `a` and `b`, if any, or `None`." + t1 = get_fill_value(a) + t2 = get_fill_value(b) + if t1 == t2: + return t1 + return None + +#................................................ +def filled(a, value = None): + """Returns `a` as an array with masked data replaced by `value`. +If `value` is `None` or the special element `masked`, `get_fill_value(a)` +is used instead. + +If `a` is already a contiguous numeric array, `a` itself is returned. + +`filled(a)` can be used to be sure that the result is numeric when passing +an object a to other software ignorant of MA, in particular to numpy itself. + """ + if hasattr(a, 'filled'): + return a.filled(value) + elif isinstance(a, ndarray): # and a.flags['CONTIGUOUS']: + return a + elif isinstance(a, dict): + return numeric.array(a, 'O') + else: + return numeric.array(a) + +def get_masked_subclass(*arrays): + """Returns the youngest subclass of MaskedArray from a list of arrays, + or MaskedArray. In case of siblings, the first takes over.""" + if len(arrays) == 1: + arr = arrays[0] + if isinstance(arr, MaskedArray): + rcls = type(arr) + else: + rcls = MaskedArray + else: + arrcls = [type(a) for a in arrays] + rcls = arrcls[0] + if not issubclass(rcls, MaskedArray): + rcls = MaskedArray + for cls in arrcls[1:]: + if issubclass(cls, rcls): + rcls = cls + return rcls + +#####-------------------------------------------------------------------------- +#---- --- Ufuncs --- +#####-------------------------------------------------------------------------- +ufunc_domain = {} +ufunc_fills = {} + +class domain_check_interval: + """Defines a valid interval, +so that `domain_check_interval(a,b)(x) = true` where `x < a` or `x > b`.""" + def __init__(self, a, b): + "domain_check_interval(a,b)(x) = true where x < a or y > b" + if (a > b): + (a, b) = (b, a) + self.a = a + self.b = b + + def __call__ (self, x): + "Execute the call behavior." + return umath.logical_or(umath.greater (x, self.b), + umath.less(x, self.a)) +#............................ +class domain_tan: + """Defines a valid interval for the `tan` function, +so that `domain_tan(eps) = True where `abs(cos(x)) < eps`""" + def __init__(self, eps): + "domain_tan(eps) = true where abs(cos(x)) < eps)" + self.eps = eps + def __call__ (self, x): + "Execute the call behavior." + return umath.less(umath.absolute(umath.cos(x)), self.eps) +#............................ +class domain_safe_divide: + """defines a domain for safe division.""" + def __init__ (self, tolerance=divide_tolerance): + self.tolerance = tolerance + def __call__ (self, a, b): + return umath.absolute(a) * self.tolerance >= umath.absolute(b) +#............................ +class domain_greater: + "domain_greater(v)(x) = true where x <= v" + def __init__(self, critical_value): + "domain_greater(v)(x) = true where x <= v" + self.critical_value = critical_value + + def __call__ (self, x): + "Execute the call behavior." + return umath.less_equal(x, self.critical_value) +#............................ +class domain_greater_equal: + "domain_greater_equal(v)(x) = true where x < v" + def __init__(self, critical_value): + "domain_greater_equal(v)(x) = true where x < v" + self.critical_value = critical_value + + def __call__ (self, x): + "Execute the call behavior." + return umath.less(x, self.critical_value) +#.............................................................................. +class masked_unary_operation: + """Defines masked version of unary operations, +where invalid values are pre-masked. + +:IVariables: + - `f` : function. + - `fill` : Default filling value *[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, mufunc, fill=0, domain=None): + """ masked_unary_operation(aufunc, fill=0, domain=None) + aufunc(fill) must be defined + self(x) returns aufunc(x) + with masked values where domain(x) is true or getmask(x) is true. + """ + self.f = mufunc + self.fill = fill + self.domain = domain + self.__doc__ = getattr(mufunc, "__doc__", str(mufunc)) + self.__name__ = getattr(mufunc, "__name__", str(mufunc)) + ufunc_domain[mufunc] = domain + ufunc_fills[mufunc] = fill + # + def __call__ (self, a, *args, **kwargs): + "Execute the call behavior." +# numeric tries to return scalars rather than arrays when given scalars. + m = getmask(a) + d1 = filled(a, self.fill) + if self.domain is not None: + m = mask_or(m, numeric.asarray(self.domain(d1))) + # Take care of the masked singletong first ... + if m.ndim == 0 and m: + return masked + # Get the result.... + if isinstance(a, MaskedArray): + result = self.f(d1, *args, **kwargs).view(type(a)) + else: + result = self.f(d1, *args, **kwargs).view(MaskedArray) + # Fix the mask if we don't have a scalar + if result.ndim > 0: + result._mask = m + return result + # + def __str__ (self): + return "Masked version of %s. [Invalid values are masked]" % str(self.f) +#.............................................................................. +class masked_binary_operation: + """Defines masked version of binary operations, +where invalid values are pre-masked. + +:IVariables: + - `f` : function. + - `fillx` : Default filling value for first array*[0]*. + - `filly` : Default filling value for second array*[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, mbfunc, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + self.f = mbfunc + self.fillx = fillx + self.filly = filly + self.__doc__ = getattr(mbfunc, "__doc__", str(mbfunc)) + self.__name__ = getattr(mbfunc, "__name__", str(mbfunc)) + ufunc_domain[mbfunc] = None + ufunc_fills[mbfunc] = (fillx, filly) + # + def __call__ (self, a, b, *args, **kwargs): + "Execute the call behavior." + m = mask_or(getmask(a), getmask(b)) + if (not m.ndim) and m: + return masked + result = self.f(a, b, *args, **kwargs).view(get_masked_subclass(a,b)) + if result.ndim > 0: + result.unshare_mask() + result._masklayer |= m + return result + # + def reduce (self, target, axis=0, dtype=None): + """Reduces `target` along the given `axis`.""" + if isinstance(target, MaskedArray): + tclass = type(target) + else: + tclass = MaskedArray + m = getmask(target) + t = filled(target, self.filly) + if t.shape == (): + t = t.reshape(1) + if m is not nomask: + m = make_mask(m, copy=1) + m.shape = (1,) + if m is nomask: + return self.f.reduce(t, axis).view(tclass) + t = t.view(tclass) + t._mask = m + # XXX: "or t.dtype" below is a workaround for what appears + # XXX: to be a bug in reduce. + tr = self.f.reduce(filled(t, self.filly), axis, dtype=dtype or t.dtype) + mr = umath.logical_and.reduce(m, axis) + tr = tr.view(tclass) + if mr.ndim > 0: + tr._mask = mr + return tr + elif mr: + return masked + return tr + + def outer (self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = umath.logical_or.outer(ma, mb) + if (not m.ndim) and m: + return masked + rcls = get_masked_subclass(a,b) + d = self.f.outer(filled(a, self.fillx), filled(b, self.filly)).view(rcls) + if d.ndim > 0: + d._mask = m + return d + + def accumulate (self, target, axis=0): + """Accumulates `target` along `axis` after filling with y fill value.""" + if isinstance(target, MaskedArray): + tclass = type(target) + else: + tclass = masked_array + t = filled(target, self.filly) + return self.f.accumulate(t, axis).view(tclass) + + def __str__ (self): + return "Masked version of " + str(self.f) +#.............................................................................. +class domained_binary_operation: + """Defines binary operations that have a domain, like divide. + +These are complicated so they are a separate class. +They have no reduce, outer or accumulate. + +:IVariables: + - `f` : function. + - `fillx` : Default filling value for first array*[0]*. + - `filly` : Default filling value for second array*[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, dbfunc, domain, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + self.f = dbfunc + self.domain = domain + self.fillx = fillx + self.filly = filly + self.__doc__ = getattr(dbfunc, "__doc__", str(dbfunc)) + self.__name__ = getattr(dbfunc, "__name__", str(dbfunc)) + ufunc_domain[dbfunc] = domain + ufunc_fills[dbfunc] = (fillx, filly) + + def __call__(self, a, b): + "Execute the call behavior." + ma = getmask(a) + mb = getmask(b) + d1 = filled(a, self.fillx) + d2 = filled(b, self.filly) + t = numeric.asarray(self.domain(d1, d2)) + + if fromnumeric.sometrue(t, None): + d2 = numeric.where(t, self.filly, d2) + mb = mask_or(mb, t) + m = mask_or(ma, mb) + if (not m.ndim) and m: + return masked + result = self.f(d1, d2).view(get_masked_subclass(a,b)) + if result.ndim > 0: + result._mask = m + return result + + def __str__ (self): + return "Masked version of " + str(self.f) + +#.............................................................................. +# Unary ufuncs +exp = masked_unary_operation(umath.exp) +conjugate = masked_unary_operation(umath.conjugate) +sin = masked_unary_operation(umath.sin) +cos = masked_unary_operation(umath.cos) +tan = masked_unary_operation(umath.tan) +arctan = masked_unary_operation(umath.arctan) +arcsinh = masked_unary_operation(umath.arcsinh) +sinh = masked_unary_operation(umath.sinh) +cosh = masked_unary_operation(umath.cosh) +tanh = masked_unary_operation(umath.tanh) +abs = absolute = masked_unary_operation(umath.absolute) +fabs = masked_unary_operation(umath.fabs) +negative = masked_unary_operation(umath.negative) +floor = masked_unary_operation(umath.floor) +ceil = masked_unary_operation(umath.ceil) +around = masked_unary_operation(fromnumeric.round_) +logical_not = masked_unary_operation(umath.logical_not) +# Domained unary ufuncs +sqrt = masked_unary_operation(umath.sqrt, 0.0, domain_greater_equal(0.0)) +log = masked_unary_operation(umath.log, 1.0, domain_greater(0.0)) +log10 = masked_unary_operation(umath.log10, 1.0, domain_greater(0.0)) +tan = masked_unary_operation(umath.tan, 0.0, domain_tan(1.e-35)) +arcsin = masked_unary_operation(umath.arcsin, 0.0, + domain_check_interval(-1.0, 1.0)) +arccos = masked_unary_operation(umath.arccos, 0.0, + domain_check_interval(-1.0, 1.0)) +arccosh = masked_unary_operation(umath.arccosh, 1.0, domain_greater_equal(1.0)) +arctanh = masked_unary_operation(umath.arctanh, 0.0, + domain_check_interval(-1.0+1e-15, 1.0-1e-15)) +# Binary ufuncs +add = masked_binary_operation(umath.add) +subtract = masked_binary_operation(umath.subtract) +multiply = masked_binary_operation(umath.multiply, 1, 1) +arctan2 = masked_binary_operation(umath.arctan2, 0.0, 1.0) +equal = masked_binary_operation(umath.equal) +equal.reduce = None +not_equal = masked_binary_operation(umath.not_equal) +not_equal.reduce = None +less_equal = masked_binary_operation(umath.less_equal) +less_equal.reduce = None +greater_equal = masked_binary_operation(umath.greater_equal) +greater_equal.reduce = None +less = masked_binary_operation(umath.less) +less.reduce = None +greater = masked_binary_operation(umath.greater) +greater.reduce = None +logical_and = masked_binary_operation(umath.logical_and) +alltrue = masked_binary_operation(umath.logical_and, 1, 1).reduce +logical_or = masked_binary_operation(umath.logical_or) +sometrue = logical_or.reduce +logical_xor = masked_binary_operation(umath.logical_xor) +bitwise_and = masked_binary_operation(umath.bitwise_and) +bitwise_or = masked_binary_operation(umath.bitwise_or) +bitwise_xor = masked_binary_operation(umath.bitwise_xor) +hypot = masked_binary_operation(umath.hypot) +# Domained binary ufuncs +divide = domained_binary_operation(umath.divide, domain_safe_divide(), 0, 1) +true_divide = domained_binary_operation(umath.true_divide, + domain_safe_divide(), 0, 1) +floor_divide = domained_binary_operation(umath.floor_divide, + domain_safe_divide(), 0, 1) +remainder = domained_binary_operation(umath.remainder, + domain_safe_divide(), 0, 1) +fmod = domained_binary_operation(umath.fmod, domain_safe_divide(), 0, 1) + + +#####-------------------------------------------------------------------------- +#---- --- Mask creation functions --- +#####-------------------------------------------------------------------------- +def getmask(a): + """Returns the mask of `a`, if any, or `nomask`. +Returns `nomask` if `a` is not a masked array. +To get an array for sure use getmaskarray.""" + if hasattr(a, "_mask"): + return a._mask + else: + return nomask + +def getmaskarray(a): + """Returns the mask of `a`, if any. +Otherwise, returns an array of `False`, with the same shape as `a`. + """ + m = getmask(a) + if m is nomask: + return make_mask_none(fromnumeric.shape(a)) + else: + return m + +def is_mask(m): + """Returns `True` if `m` is a legal mask. +Does not check contents, only type. + """ + try: + return m.dtype.type is MaskType + except AttributeError: + return False +# +def make_mask(m, copy=False, small_mask=True, flag=None): + """make_mask(m, copy=0, small_mask=0) +Returns `m` as a mask, creating a copy if necessary or requested. +The function can accept any sequence of integers or `nomask`. +Does not check that contents must be 0s and 1s. +If `small_mask=True`, returns `nomask` if `m` contains no true elements. + +:Parameters: + - `m` (ndarray) : Mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + - `small_mask` (boolean, *[False]*): Flattens mask to `nomask` if `m` is all false. + """ + if flag is not None: + warnings.warn("The flag 'flag' is now called 'small_mask'!", + DeprecationWarning) + small_mask = flag + if m is nomask: + return nomask + elif isinstance(m, ndarray): + m = filled(m, True) + if m.dtype.type is MaskType: + if copy: + result = numeric.array(m, dtype=MaskType, copy=copy) + else: + result = m + else: + result = numeric.array(m, dtype=MaskType) + else: + result = numeric.array(filled(m, True), dtype=MaskType) + # Bas les masques ! + if small_mask and not result.any(): + return nomask + else: + return result + +def make_mask_none(s): + "Returns a mask of shape `s`, filled with `False`." + result = numeric.zeros(s, dtype=MaskType) + return result + +def mask_or (m1, m2, copy=False, small_mask=True): + """Returns the combination of two masks `m1` and `m2`. +The masks are combined with the `logical_or` operator, treating `nomask` as false. +The result may equal m1 or m2 if the other is nomask. + +:Parameters: + - `m` (ndarray) : Mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + - `small_mask` (boolean, *[False]*): Flattens mask to `nomask` if `m` is all false. + """ + if m1 is nomask: + return make_mask(m2, copy=copy, small_mask=small_mask) + if m2 is nomask: + return make_mask(m1, copy=copy, small_mask=small_mask) + if m1 is m2 and is_mask(m1): + return m1 + return make_mask(umath.logical_or(m1, m2), copy=copy, small_mask=small_mask) + +#####-------------------------------------------------------------------------- +#--- --- Masking functions --- +#####-------------------------------------------------------------------------- +def masked_where(condition, x, copy=True): + """Returns `x` as an array masked where `condition` is true. +Masked values of `x` or `condition` are kept. + +:Parameters: + - `condition` (ndarray) : Masking condition. + - `x` (ndarray) : Array to mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + """ + cm = filled(condition,1) + if isinstance(x,MaskedArray): + m = mask_or(x._mask, cm) + return x.__class__(x._data, mask=m, copy=copy) + else: + return MaskedArray(fromnumeric.asarray(x), copy=copy, mask=cm) + +def masked_greater(x, value, copy=1): + "Shortcut to `masked_where`, with ``condition = (x > value)``." + return masked_where(greater(x, value), x, copy=copy) + +def masked_greater_equal(x, value, copy=1): + "Shortcut to `masked_where`, with ``condition = (x >= value)``." + return masked_where(greater_equal(x, value), x, copy=copy) + +def masked_less(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x < value)``." + return masked_where(less(x, value), x, copy=copy) + +def masked_less_equal(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x <= value)``." + return masked_where(less_equal(x, value), x, copy=copy) + +def masked_not_equal(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x != value)``." + return masked_where((x != value), x, copy=copy) + +# +def masked_equal(x, value, copy=True): + """Shortcut to `masked_where`, with ``condition = (x == value)``. +For floating point, consider `masked_values(x, value)` instead. + """ + return masked_where((x == value), x, copy=copy) +# d = filled(x, 0) +# c = umath.equal(d, value) +# m = mask_or(c, getmask(x)) +# return array(d, mask=m, copy=copy) + +def masked_inside(x, v1, v2, copy=True): + """Shortcut to `masked_where`, where `condition` is True for x inside +the interval `[v1,v2]` ``(v1 <= x <= v2)``. +The boundaries `v1` and `v2` can be given in either order. + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf >= v1) & (xf <= v2) + return masked_where(condition, x, copy=copy) + +def masked_outside(x, v1, v2, copy=True): + """Shortcut to `masked_where`, where `condition` is True for x outside +the interval `[v1,v2]` ``(x < v1)|(x > v2)``. +The boundaries `v1` and `v2` can be given in either order. + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf < v1) | (xf > v2) + return masked_where(condition, x, copy=copy) + +# +def masked_object(x, value, copy=True): + """Masks the array `x` where the data are exactly equal to `value`. +This function is suitable only for `object` arrays: for floating point, +please use `masked_values` instead. +The mask is set to `nomask` if posible. + +:parameter copy (Boolean, *[True]*): Returns a copy of `x` if true. """ + if isMaskedArray(x): + condition = umath.equal(x._data, value) + mask = x._mask + else: + condition = umath.equal(fromnumeric.asarray(x), value) + mask = nomask + mask = mask_or(mask, make_mask(condition, small_mask=True)) + return masked_array(x, mask=mask, copy=copy, fill_value=value) + +def masked_values(x, value, rtol=1.e-5, atol=1.e-8, copy=True): + """Masks the array `x` where the data are approximately equal to `value` +(that is, ``abs(x - value) <= atol+rtol*abs(value)``). +Suitable only for floating points. For integers, please use `masked_equal`. +The mask is set to `nomask` if posible. + +:Parameters: + - `rtol` (Float, *[1e-5]*): Tolerance parameter. + - `atol` (Float, *[1e-8]*): Tolerance parameter. + - `copy` (boolean, *[False]*) : Returns a copy of `x` if True. + """ + abs = umath.absolute + xnew = filled(x, value) + if issubclass(xnew.dtype.type, numeric.floating): + condition = umath.less_equal(abs(xnew-value), atol+rtol*abs(value)) + try: + mask = x._mask + except AttributeError: + mask = nomask + else: + condition = umath.equal(xnew, value) + mask = nomask + mask = mask_or(mask, make_mask(condition, small_mask=True)) + return masked_array(xnew, mask=mask, copy=copy, fill_value=value) + +#####-------------------------------------------------------------------------- +#---- --- Printing options --- +#####-------------------------------------------------------------------------- +class _MaskedPrintOption: + """Handles the string used to represent missing data in a masked array.""" + def __init__ (self, display): + "Creates the masked_print_option object." + self._display = display + self._enabled = True + + def display(self): + "Displays the string to print for masked values." + return self._display + + def set_display (self, s): + "Sets the string to print for masked values." + self._display = s + + def enabled(self): + "Is the use of the display value enabled?" + return self._enabled + + def enable(self, small_mask=1): + "Set the enabling small_mask to `small_mask`." + self._enabled = small_mask + + def __str__ (self): + return str(self._display) + + __repr__ = __str__ + +#if you single index into a masked location you get this object. +masked_print_option = _MaskedPrintOption('--') + +#####-------------------------------------------------------------------------- +#---- --- MaskedArray class --- +#####-------------------------------------------------------------------------- +#def _getoptions(a_out, a_in): +# "Copies standards options of a_in to a_out." +# for att in ['] +class _mathmethod(object): + """Defines a wrapper for arithmetic methods. +Instead of directly calling a ufunc, the corresponding method of the `array._data` +object is called instead. + """ + def __init__ (self, methodname, fill_self=0, fill_other=0, domain=None): + """ +:Parameters: + - `methodname` (String) : Method name. + - `fill_self` (Float *[0]*) : Fill value for the instance. + - `fill_other` (Float *[0]*) : Fill value for the target. + - `domain` (Domain object *[None]*) : Domain of non-validity. + """ + self.methodname = methodname + self.fill_self = fill_self + self.fill_other = fill_other + self.domain = domain + self.obj = None + self.__doc__ = self.getdoc() + # + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + try: + return getattr(MaskedArray, self.methodname).__doc__ + except: + return getattr(ndarray, self.methodname).__doc__ + # + def __get__(self, obj, objtype=None): + self.obj = obj + return self + # + def __call__ (self, other, *args): + "Execute the call behavior." + instance = self.obj + m_self = instance._mask + m_other = getmask(other) + base = instance.filled(self.fill_self) + target = filled(other, self.fill_other) + if self.domain is not None: + # We need to force the domain to a ndarray only. + if self.fill_other > self.fill_self: + domain = self.domain(base, target) + else: + domain = self.domain(target, base) + if domain.any(): + #If `other` is a subclass of ndarray, `filled` must have the + # same subclass, else we'll lose some info. + #The easiest then is to fill `target` instead of creating + # a pure ndarray. + #Oh, and we better make a copy! + if isinstance(other, ndarray): + # We don't want to modify other: let's copy target, then + target = target.copy() + target[fromnumeric.asarray(domain)] = self.fill_other + else: + target = numeric.where(fromnumeric.asarray(domain), + self.fill_other, target) + m_other = mask_or(m_other, domain) + m = mask_or(m_self, m_other) + method = getattr(base, self.methodname) + result = method(target, *args).view(type(instance)) + try: + result._mask = m + except AttributeError: + if m: + result = masked + return result +#............................................................................... +class _arraymethod(object): + """Defines a wrapper for basic array methods. +Upon call, returns a masked array, where the new `_data` array is the output +of the corresponding method called on the original `_data`. + +If `onmask` is True, the new mask is the output of the method calld on the initial mask. +If `onmask` is False, the new mask is just a reference to the initial mask. + +:Parameters: + `funcname` : String + Name of the function to apply on data. + `onmask` : Boolean *[True]* + Whether the mask must be processed also (True) or left alone (False). + """ + def __init__(self, funcname, onmask=True): + self._name = funcname + self._onmask = onmask + self.obj = None + self.__doc__ = self.getdoc() + # + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + methdoc = getattr(ndarray, self._name, None) + methdoc = getattr(numpy, self._name, methdoc) +# methdoc = getattr(MaskedArray, self._name, methdoc) + if methdoc is not None: + return methdoc.__doc__ +# try: +# return getattr(MaskedArray, self._name).__doc__ +# except: +# try: +# return getattr(numpy, self._name).__doc__ +# except: +# return getattr(ndarray, self._name).__doc + # + def __get__(self, obj, objtype=None): + self.obj = obj + return self + # + def __call__(self, *args, **params): + methodname = self._name + data = self.obj._data + mask = self.obj._mask + cls = type(self.obj) + result = getattr(data, methodname)(*args, **params).view(cls) + if result.ndim: + if not self._onmask: + result._mask = mask + elif mask is not nomask: + result.__setmask__(getattr(mask, methodname)(*args, **params)) + return result +#.......................................................... + +class flatiter(object): + "Defines an interator." + def __init__(self, ma): + self.ma = ma + self.ma_iter = numpy.asarray(ma).flat + + if ma._mask is nomask: + self.maskiter = None + else: + self.maskiter = ma._mask.flat + + def __iter__(self): + return self + + ### This won't work is ravel makes a copy + def __setitem__(self, index, value): + a = self.ma.ravel() + a[index] = value + + def next(self): + d = self.ma_iter.next() + if self.maskiter is not None and self.maskiter.next(): + d = masked + return d + + +class MaskedArray(numeric.ndarray): + """Arrays with possibly masked values. +Masked values of True exclude the corresponding element from any computation. + +Construction: + x = array(data, dtype=None, copy=True, order=False, + mask = nomask, fill_value=None, small_mask=True) + +If copy=False, every effort is made not to copy the data: +If `data` is a MaskedArray, and argument mask=nomask, then the candidate data +is `data._data` and the mask used is `data._mask`. +If `data` is a numeric array, it is used as the candidate raw data. +If `dtype` is not None and is different from data.dtype.char then a data copy is required. +Otherwise, the candidate is used. + +If a data copy is required, the raw (unmasked) data stored is the result of: +numeric.array(data, dtype=dtype.char, copy=copy) + +If `mask` is `nomask` there are no masked values. +Otherwise mask must be convertible to an array of booleans with the same shape as x. +If `small_mask` is True, a mask consisting of zeros (False) only is compressed to `nomask`. +Otherwise, the mask is not compressed. + +fill_value is used to fill in masked values when necessary, such as when +printing and in method/function filled(). +The fill_value is not used for computation within this module. + """ + __array_priority__ = 10.1 + _defaultmask = nomask + _defaulthardmask = False + _baseclass = numeric.ndarray + def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, fill_value=None, + keep_mask=True, small_mask=True, hard_mask=False, flag=None, + **options): + """array(data, dtype=None, copy=True, mask=nomask, fill_value=None) + +If `data` is already a ndarray, its dtype becomes the default value of dtype. + """ + if flag is not None: + warnings.warn("The flag 'flag' is now called 'small_mask'!", + DeprecationWarning) + small_mask = flag + # Process data............ + _data = numeric.array(data, dtype=dtype, copy=copy, subok=True) + _baseclass = getattr(_data, '_baseclass', type(_data)) + _data = _data.view(cls) + # Pricess mask ........... + # Backwards compat + if hasattr(data,'_mask') and not isinstance(data, ndarray): + _data._mask = data._mask + _data._sharedmask = True + if mask is nomask: + if _data._hasmasked: + if copy: + _data._masklayer = data._masklayer.copy() + _data._sharedmask = False + if not keep_mask: + _data._masklayer.flat = False + _data._hasmasked = False +# else; +# _data._mask = data._mask + else: + mask = numeric.array(mask, dtype=MaskType, copy=copy) + if mask.shape != _data.shape: + (nd, nm) = (_data.size, mask.size) + if nm == 1: + mask = numeric.resize(mask, _data.shape) + elif nm == nd: + mask = fromnumeric.reshape(mask, _data.shape) + else: + msg = "Mask and data not compatible: data size is %i, "+\ + "mask size is %i." + raise MAError, msg % (nd, nm) + if not (_data._hasmasked and keep_mask): + _data._masklayer = mask + _data._hasmasked = True + _data._sharedmask = True + else: + _data._masklayer = _data._masklayer.copy() + _data._mask.__ior__(mask) + _data._sharedmask = False + _data._hasmasked = True + # Process extra options .. + # Update fille_value + _data._fill_value = getattr(data, '_fill_value', fill_value) + if _data._fill_value is None: + _data._fill_value = default_fill_value(_data) + _data._hardmask = hard_mask + _data._smallmask = small_mask + _data._baseclass = _baseclass + return _data + #........................ + def __array_finalize__(self,obj): + """Finalizes the masked array. + """ + # Finalize mask ............... + self._masklayer = getattr(obj, '_masklayer', nomask) + self._hasmasked = getattr(obj, '_hasmasked', False) + if self._masklayer is nomask: + self._masklayer = numeric.zeros(obj.shape, dtype=MaskType) + self._hasmasked = False +# if not self.shape: +# self._mask.shape = obj.shape +# else: +# self._mask.shape = self.shape + if self._hasmasked: + self._masklayer.shape = self.shape +# except ValueError: +# self._mask = nomask + # Get the remaining options ... + self._hardmask = getattr(obj, '_hardmask', self._defaulthardmask) + self._smallmask = getattr(obj, '_smallmask', True) + self._sharedmask = True + self._baseclass = getattr(obj, '_baseclass', type(obj)) + self._fill_value = getattr(obj, '_fill_value', None) + return + #.................................. + def __array_wrap__(self, obj, context=None): + """Special hook for ufuncs. +Wraps the numpy array and sets the mask according to context. + """ + result = obj.view(type(self)) + result._masklayer = self._masklayer.copy() + result._hasmasked = self._hasmasked +# result._hasmasked = result._masklayer.any() + #.......... + if context is not None: + (func, args, out_index) = context + m = reduce(mask_or, [getmask(arg) for arg in args]) + # Get domain mask + domain = ufunc_domain.get(func, None) + if domain is not None: + if len(args) > 2: + d = reduce(domain, args) + else: + d = domain(*args) + if m is nomask: + if d is not nomask: + result._masklayer.flat = d + result._hasmasked = True + else: + result._masklayer |= d + result._hasmasked |= d.any() + else: + result._masklayer.__ior__(m) + result._hasmasked = m.any() + if result._masklayer.size == 1 and result._masklayer.item(): + return masked + #.... + result._fill_value = self._fill_value + result._hardmask = self._hardmask + result._smallmask = self._smallmask + result._baseclass = self._baseclass + return result + #............................................. + def __getitem__(self, indx): + """x.__getitem__(y) <==> x[y] +Returns the item described by i. Not a copy as in previous versions. + """ + # This test is useful, but we should keep things light... +# if getmask(indx) is not nomask: +# msg = "Masked arrays must be filled before they can be used as indices!" +# raise IndexError, msg + # super() can't work here if the underlying data is a matrix... + result = (self._data).__getitem__(indx) + m = self._masklayer[indx] + if hasattr(result, 'shape') and len(result.shape) > 0: + # Not a scalar: make sure that dout is a MA + result = result.view(type(self)) + result.__setmask__(m) + elif not m.shape and m: + return masked + return result + #........................ + def __setitem__(self, indx, value): + """x.__setitem__(i, y) <==> x[i]=y +Sets item described by index. If value is masked, masks those locations. + """ + if self is masked: + raise MAError, 'Cannot alter the masked element.' +# if getmask(indx) is not nomask: +# msg = "Masked arrays must be filled before they can be used as indices!" +# raise IndexError, msg + #.... + if value is masked: +# if self._sharedmask: +# slef.unshare_mask() + self._masklayer[indx] = True + self._hasmasked = True + return + #.... + dval = numeric.asarray(value).astype(self.dtype) + valmask = getmask(value) + + if not self._hasmasked: + if valmask is not nomask: + self._masklayer[indx] = valmask + self._hasmasked = True + elif not self._hardmask: + self.unshare_mask() + if valmask is nomask: + self._masklayer[indx] = False + self._hasmasked = self._masklayer.any() + else: + self._masklayer[indx] = valmask + self._hasmasked = True + elif hasattr(indx, 'dtype') and (indx.dtype==bool_): + indx = indx * umath.logical_not(self._masklayer) +# elif isinstance(index, int): + else: + mindx = mask_or(self._masklayer[indx], valmask, copy=True) + dindx = self._data[indx] + if dindx.size > 1: + dindx[~mindx] = dval + elif mindx is nomask: + dindx = dval + dval = dindx + self._masklayer[indx] = mindx + # Set data .......... + #dval = filled(value).astype(self.dtype) + ndarray.__setitem__(self._data,indx,dval) +# #..... +# if m is nomask or not m.any(): +# self._mask = nomask +# else: +# self._mask = m + #............................................ + def __getslice__(self, i, j): + """x.__getslice__(i, j) <==> x[i:j] +Returns the slice described by i, j. +The use of negative indices is not supported.""" + return self.__getitem__(slice(i,j)) + #........................ + def __setslice__(self, i, j, value): + """x.__setslice__(i, j, value) <==> x[i:j]=value +Sets a slice i:j to `value`. +If `value` is masked, masks those locations.""" + self.__setitem__(slice(i,j), value) + #............................................ + def __setmask__(self, mask): + newmask = make_mask(mask, copy=False, small_mask=self._smallmask) +# self.unshare_mask() + if self._hardmask: + if newmask is not nomask: + self.unshare_mask() + self._masklayer.__ior__(newmask) + self._hasmasked = True + else: +# if self._hasmasked and (mask is nomask): +# self.unshare_mask() + self._masklayer.flat = newmask + self._hasmasked = newmask.any() + if self._masklayer.shape: + self._masklayer.shape = self.shape + _set_mask = __setmask__ + + def _get_mask(self): + """Returns the current mask.""" + if not self._hasmasked and self._smallmask: + return nomask + return self._masklayer + +# def _set_mask(self, mask): +# """Sets the mask to `mask`.""" +# mask = make_mask(mask, copy=False, small_mask=self._smallmask) +# if mask is not nomask: +# if mask.size != self.size: +# raise ValueError, "Inconsistent shape between data and mask!" +# if mask.shape != self.shape: +# mask.shape = self.shape +# self._mask = mask +# else: +# self._mask = nomask + mask = _mask = property(fget=_get_mask, fset=__setmask__, doc="Mask") + #............................................ + def harden_mask(self): + "Forces the mask to hard." + self._hardmask = True + + def soften_mask(self): + "Forces the mask to soft." + self._hardmask = False + + def unshare_mask(self): + if self._sharedmask: + self._masklayer = self._masklayer.copy() + self._sharedmask = False + + #............................................ + def _get_data(self): + "Returns the current data (as a view of the original underlying data)>" + return self.view(self._baseclass) + _data = property(fget=_get_data) + #............................................ + def _get_flat(self): + """Calculates the flat value. + """ + return flatiter(self) + # + def _set_flat (self, value): + "x.flat = value" + y = self.ravel() + y[:] = value + # + flat = property(fget=_get_flat, fset=_set_flat, doc="Flat version") + #............................................ + def get_fill_value(self): + "Returns the filling value." + if self._fill_value is None: + self._fill_value = default_fill_value(self) + return self._fill_value + + def set_fill_value(self, value=None): + """Sets the filling value to `value`. +If None, uses the default, based on the data type.""" + if value is None: + value = default_fill_value(self) + self._fill_value = value + + fill_value = property(fget=get_fill_value, fset=set_fill_value, + doc="Filling value") + + def filled(self, fill_value=None): + """Returns an array of the same class as `_data`, + with masked values filled with `fill_value`. +Subclassing is preserved. + +If `fill_value` is None, uses self.fill_value. + """ + m = self._mask + if m is nomask: + return self._data + # + if fill_value is None: + fill_value = self.fill_value + # + if self is masked_singleton: + result = numeric.asanyarray(fill_value) + else: + result = self._data.copy() + try: + result[m] = fill_value + except (TypeError, AttributeError): + fill_value = numeric.array(fill_value, dtype=object) + d = result.astype(object) + result = fromnumeric.choose(m, (d, fill_value)) + except IndexError: + #ok, if scalar + if self._data.shape: + raise + elif m: + result = numeric.array(fill_value, dtype=self.dtype) + else: + result = self._data + return result + + def compressed(self): + "A 1-D array of all the non-masked data." + d = self.ravel() + if self._mask is nomask: + return d + else: + return d[numeric.logical_not(d._mask)] + #............................................ + def __str__(self): + """x.__str__() <==> str(x) +Calculates the string representation, using masked for fill if it is enabled. +Otherwise, fills with fill value. + """ + if masked_print_option.enabled(): + f = masked_print_option + if self is masked: + return str(f) + m = self._mask + if m is nomask: + res = self._data + else: + if m.shape == () and m: + return str(f) + # convert to object array to make filled work +#CHECK: the two lines below seem more robust than the self._data.astype +# res = numeric.empty(self._data.shape, object_) +# numeric.putmask(res,~m,self._data) + res = self._data.astype("|O8") + res[m] = f + else: + res = self.filled(self.fill_value) + return str(res) + + def __repr__(self): + """x.__repr__() <==> repr(x) +Calculates the repr representation, using masked for fill if it is enabled. +Otherwise fill with fill value. + """ + with_mask = """\ +masked_%(name)s(data = + %(data)s, + mask = + %(mask)s, + fill_value=%(fill)s) +""" + with_mask1 = """\ +masked_%(name)s(data = %(data)s, + mask = %(mask)s, + fill_value=%(fill)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), + } + #............................................ + def __iadd__(self, other): + "Adds other to self in place." + ndarray.__iadd__(self._data,other) + m = getmask(other) + if m is not nomask: + self._masklayer += m + self._hasmasked = True +# if m is not nomask: +# self._masklayer |= m +# self._hasmasked = True + return self + #.... + def __isub__(self, other): + "Subtracts other from self in place." + ndarray.__isub__(self._data,other) + m = getmask(other) +# if not self._hasmasked: +# self._masklayer.flat = m +# elif m is not nomask: +# self._masklayer += m + if m is not nomask: + self._masklayer += m + self._hasmasked = True + return self + #.... + def __imul__(self, other): + "Multiplies self by other in place." + ndarray.__imul__(self._data,other) + m = getmask(other) +# if not self._hasmasked: +# self._masklayer.flat = m +# elif m is not nomask: +# self._masklayer += m + if m is not nomask: + self._masklayer += m + self._hasmasked = True + return self + #.... + def __idiv__(self, other): + "Divides self by other in place." + dom_mask = domain_safe_divide().__call__(self, filled(other,1)) + other_mask = getmask(other) + new_mask = mask_or(other_mask, dom_mask) + ndarray.__idiv__(self._data, other) + self._mask = mask_or(self._mask, new_mask) + return self + #.... + __add__ = _mathmethod('__add__') + __radd__ = _mathmethod('__add__') + __sub__ = _mathmethod('__sub__') + __rsub__ = _mathmethod('__rsub__') + __pow__ = _mathmethod('__pow__') + __mul__ = _mathmethod('__mul__', 1, 1) + __rmul__ = _mathmethod('__mul__', 1, 1) + __div__ = _mathmethod('__div__', 0, 1, domain_safe_divide()) + __rdiv__ = _mathmethod('__rdiv__', 1, 0, domain_safe_divide()) + __truediv__ = _mathmethod('__truediv__', 0, 1, domain_safe_divide()) + __rtruediv__ = _mathmethod('__rtruediv__', 1, 0, domain_safe_divide()) + __floordiv__ = _mathmethod('__floordiv__', 0, 1, domain_safe_divide()) + __rfloordiv__ = _mathmethod('__rfloordiv__', 1, 0, domain_safe_divide()) + __eq__ = _mathmethod('__eq__') + __ne__ = _mathmethod('__ne__') + __le__ = _mathmethod('__le__') + __lt__ = _mathmethod('__lt__') + __ge__ = _mathmethod('__ge__') + __gt__ = _mathmethod('__gt__') + + #............................................ + def __float__(self): + "Converts self to float." + if self._mask is not nomask: + warnings.warn("Warning: converting a masked element to nan.") + return numpy.nan + #raise MAError, 'Cannot convert masked element to a Python float.' + return float(self.item()) + + def __int__(self): + "Converts self to int." + if self._mask is not nomask: + raise MAError, 'Cannot convert masked element to a Python int.' + return int(self.item()) + #............................................ + def count(self, axis=None): + """Counts the non-masked elements of the array along a given axis, +and returns a masked array where the mask is True where all data are masked. +If `axis` is None, counts all the non-masked elements, and returns either a +scalar or the masked singleton.""" + m = self._mask + s = self.shape + ls = len(s) + if m is nomask: + if ls == 0: + return 1 + if ls == 1: + return s[0] + if axis is None: + return self.size + else: + n = s[axis] + t = list(s) + del t[axis] + return numeric.ones(t) * n + n1 = fromnumeric.size(m, axis) + n2 = m.astype(int_).sum(axis) + if axis is None: + return (n1-n2) + else: + return masked_array(n1 - n2) + #............................................ +# def _get_shape(self): +# "Returns the current shape." +# return self._data.shape +# # +# def _set_shape (self, newshape): +# "Sets the array's shape." +# self._data.shape = newshape +# if self._mask is not nomask: +# #self._mask = self._mask.copy() +# self._mask.shape = newshape +# # +# shape = property(fget=_get_shape, fset=_set_shape, +# doc="Shape of the array, as a tuple.") + # + def reshape (self, *s): + """Reshapes the array to shape s. +Returns a new masked array. +If you want to modify the shape in place, please use `a.shape = s`""" + # TODO: Do we keep super, or reshape _data and take a view ? + result = super(MaskedArray, self).reshape(*s) + result._masklayer = self._masklayer.reshape(*s) + return result + # + repeat = _arraymethod('repeat') + # + def resize(self, newshape, refcheck=True, order=False): + """Attempts to modify size and shape of self inplace. + The array must own its own memory and not be referenced by other arrays. + Returns None. + """ + try: + self._data.resize(newshape, refcheck, order) + if self.mask is not nomask: + self._mask.resize(newshape, refcheck, order) + except ValueError: + raise ValueError("Cannot resize an array that has been referenced " + "or is referencing another array in this way.\n" + "Use the resize function.") + return None + # + flatten = _arraymethod('flatten') + # + def put(self, indices, values, mode='raise'): + """Sets storage-indexed locations to corresponding values. +a.put(values, indices, mode) sets a.flat[n] = values[n] for each n in indices. +`values` can be scalar or an array shorter than indices, and it will be repeated, +if necessary. +If `values` has some masked values, the initial mask is updated in consequence, +else the corresponding values are unmasked. + """ + m = self._mask + # Hard mask: Get rid of the values/indices that fall on masked data + if self._hardmask and self._mask is not nomask: + mask = self._mask[indices] + indices = numeric.asarray(indices) + values = numeric.asanyarray(values) + values.resize(indices.shape) + indices = indices[~mask] + values = values[~mask] + #.... + self._data.put(indices, values, mode=mode) + #.... + if m is nomask: + m = getmask(values) + else: + m = m.copy() + if getmask(values) is nomask: + m.put(indices, False, mode=mode) + else: + m.put(indices, values._mask, mode=mode) + m = make_mask(m, copy=False, small_mask=True) + self._mask = m + #............................................ + def ids (self): + """Return the address of the data and mask areas.""" + return (self.ctypes.data, self._mask.ctypes.data) + #............................................ + def all(self, axis=None, out=None): + """a.all(axis) returns True if all entries along the axis are True. + Returns False otherwise. If axis is None, uses the flatten array. + Masked data are considered as True during computation. + Outputs a masked array, where the mask is True if all data are masked along the axis. + Note: the out argument is not really operational... + """ + d = self.filled(True).all(axis=axis, out=out).view(type(self)) + if d.ndim > 0: + d.__setmask__(self._mask.all(axis)) + return d + + def any(self, axis=None, out=None): + """a.any(axis) returns True if some or all entries along the axis are True. + Returns False otherwise. If axis is None, uses the flatten array. + Masked data are considered as False during computation. + Outputs a masked array, where the mask is True if all data are masked along the axis. + Note: the out argument is not really operational... + """ + d = self.filled(False).any(axis=axis, out=out).view(type(self)) + if d.ndim > 0: + d.__setmask__(self._mask.all(axis)) + return d + + def nonzero(self): + """a.nonzero() returns a tuple of arrays + + Returns a tuple of arrays, one for each dimension of a, + containing the indices of the non-zero elements in that + dimension. The corresponding non-zero values can be obtained + with + a[a.nonzero()]. + + To group the indices by element, rather than dimension, use + transpose(a.nonzero()) + instead. The result of this is always a 2d array, with a row for + each non-zero element.""" + return numeric.asarray(self.filled(0)).nonzero() + #............................................ + def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): + """a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) +Returns the sum along the offset diagonal of the array's indicated `axis1` and `axis2`. + """ + # TODO: What are we doing with `out`? + m = self._mask + if m is nomask: + result = super(MaskedArray, self).trace(offset=offset, axis1=axis1, + axis2=axis2, out=out) + return result.astype(dtype) + else: + D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) + return D.astype(dtype).sum(axis=None) + #............................................ + def sum(self, axis=None, dtype=None): + """a.sum(axis=None, dtype=None) +Sums the array `a` over the given axis `axis`. +Masked values are set to 0. +If `axis` is None, applies to a flattened version of the array. + """ + if self._mask is nomask: + mask = nomask + else: + mask = self._mask.all(axis) + if (not mask.ndim) and mask: + return masked + result = self.filled(0).sum(axis, dtype=dtype).view(type(self)) + if result.ndim > 0: + result.__setmask__(mask) + return result + + def cumsum(self, axis=None, dtype=None): + """a.cumprod(axis=None, dtype=None) +Returns the cumulative sum of the elements of array `a` along the given axis `axis`. +Masked values are set to 0. +If `axis` is None, applies to a flattened version of the array. + """ + result = self.filled(0).cumsum(axis=axis, dtype=dtype).view(type(self)) + result.__setmask__(self.mask) + return result + + def prod(self, axis=None, dtype=None): + """a.prod(axis=None, dtype=None) +Returns the product of the elements of array `a` along the given axis `axis`. +Masked elements are set to 1. +If `axis` is None, applies to a flattened version of the array. + """ + if self._mask is nomask: + mask = nomask + else: + mask = self._mask.all(axis) + if (not mask.ndim) and mask: + return masked + result = self.filled(1).prod(axis=axis, dtype=dtype).view(type(self)) + if result.ndim: + result.__setmask__(mask) + return result + product = prod + + def cumprod(self, axis=None, dtype=None): + """a.cumprod(axis=None, dtype=None) +Returns the cumulative product of ethe lements of array `a` along the given axis `axis`. +Masked values are set to 1. +If `axis` is None, applies to a flattened version of the array. + """ + result = self.filled(1).cumprod(axis=axis, dtype=dtype).view(type(self)) + result.__setmask__(self.mask) + return result + + def mean(self, axis=None, dtype=None): + """a.mean(axis=None, dtype=None) + + Averages the array over the given axis. If the axis is None, + averages over all dimensions of the array. Equivalent to + + a.sum(axis, dtype) / size(a, axis). + + The optional dtype argument is the data type for intermediate + calculations in the sum. + + Returns a masked array, of the same class as a. + """ + if self._mask is nomask: + return super(MaskedArray, self).mean(axis=axis, dtype=dtype) + else: + dsum = self.sum(axis=axis, dtype=dtype) + cnt = self.count(axis=axis) + return dsum*1./cnt + + def anom(self, axis=None, dtype=None): + """a.anom(axis=None, dtype=None) + Returns the anomalies, or deviation from the average. + """ + m = self.mean(axis, dtype) + if not axis: + return (self - m) + else: + return (self - expand_dims(m,axis)) + + def var(self, axis=None, dtype=None): + """a.var(axis=None, dtype=None) +Returns the variance, a measure of the spread of a distribution. + +The variance is the average of the squared deviations from the mean, +i.e. var = mean((x - x.mean())**2). + """ + if self._mask is nomask: + # TODO: Do we keep super, or var _data and take a view ? + return super(MaskedArray, self).var(axis=axis, dtype=dtype) + else: + cnt = self.count(axis=axis) + danom = self.anom(axis=axis, dtype=dtype) + danom *= danom + dvar = danom.sum(axis) / cnt +# dvar /= cnt + if axis is not None: + dvar._mask = mask_or(self._mask.all(axis), (cnt==1)) + return dvar + + def std(self, axis=None, dtype=None): + """a.std(axis=None, dtype=None) +Returns the standard deviation, a measure of the spread of a distribution. + +The standard deviation is the square root of the average of the squared +deviations from the mean, i.e. std = sqrt(mean((x - x.mean())**2)). + """ + dvar = self.var(axis,dtype) + if axis is not None or dvar is not masked: + dvar = sqrt(dvar) + return dvar + #............................................ + def argsort(self, axis=None, fill_value=None, kind='quicksort', + order=None): + """Returns an array of indices that sort 'a' along the specified axis. + Masked values are filled beforehand to `fill_value`. + If `fill_value` is None, uses the default for the data type. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `kind` : String *['quicksort']* + Sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + + Returns: array of indices that sort 'a' along the specified axis. + + This method executes an indirect sort along the given axis using the + algorithm specified by the kind keyword. It returns an array of indices of + the same shape as 'a' that index data along the given axis in sorted order. + + The various sorts are characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order. The three + available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is not + along the last axis. Consequently, sorts along the last axis are faster and use + less space than sorts along other axis. + """ + if fill_value is None: + fill_value = default_fill_value(self) + d = self.filled(fill_value) + return d.argsort(axis=axis, kind=kind, order=order) + #........................ + def argmin(self, axis=None, fill_value=None): + """Returns a ndarray of indices for the minimum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = minimum_fill_value(self) + d = self.filled(fill_value) + return d.argmin(axis) + #........................ + def argmax(self, axis=None, fill_value=None): + """Returns the array of indices for the maximum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = maximum_fill_value(self._data) + d = self.filled(fill_value) + return d.argmax(axis) + + def sort(self, axis=-1, kind='quicksort', order=None, + endwith=True, fill_value=None): + """ + Sort a along the given axis. + + Keyword arguments: + + axis -- axis to be sorted (default -1) + kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. + order -- If a has fields defined, then the order keyword can be the + field name to sort on or a list (or tuple) of field names + to indicate the order that fields should be used to define + the sort. + endwith--Boolean flag indicating whether missing values (if any) should + be forced in the upper indices (at the end of the array) or + lower indices (at the beginning). + + Returns: None. + + This method sorts 'a' in place along the given axis using the algorithm + specified by the kind keyword. + + The various sorts may characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order and is most + useful when used with argsort where the key might differ from the items + being sorted. The three available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is + not along the last axis. Consequently, sorts along the last axis are faster + and use less space than sorts along other axis. + + """ + if fill_value is None: + if endwith: + filler = minimum_fill_value(self) + else: + filler = maximum_fill_value(self) + else: + filler = fill_value + indx = self.filled(filler).argsort(axis=axis,kind=kind,order=order) + self[:] = self[indx] + return + #............................................ + def min(self, axis=None, fill_value=None): + """Returns the minimum/a along the given axis. +If `axis` is None, applies to the flattened array. Masked values are filled +with `fill_value` during processing. If `fill_value is None, it is set to the +maximum_fill_value corresponding to the data type.""" + mask = self._mask + # Check all/nothing case ...... + if mask is nomask: + return super(MaskedArray, self).min(axis=axis) + elif (not mask.ndim) and mask: + return masked + # Get the mask ................ + if axis is None: + mask = umath.logical_and.reduce(mask.flat) + else: + mask = umath.logical_and.reduce(mask, axis=axis) + # Get the fil value ........... + if fill_value is None: + fill_value = minimum_fill_value(self) + # Get the data ................ + result = self.filled(fill_value).min(axis=axis).view(type(self)) + if result.ndim > 0: + result._mask = mask + return result + #........................ + def max(self, axis=None, fill_value=None): + """Returns the maximum/a along the given axis. +If `axis` is None, applies to the flattened array. Masked values are filled +with `fill_value` during processing. If `fill_value is None, it is set to the +maximum_fill_value corresponding to the data type.""" + mask = self._mask + # Check all/nothing case ...... + if mask is nomask: + return super(MaskedArray, self).max(axis=axis) + elif (not mask.ndim) and mask: + return masked + # Check teh mask .............. + if axis is None: + mask = umath.logical_and.reduce(mask.flat) + else: + mask = umath.logical_and.reduce(mask, axis=axis) + # Get the fill value .......... + if fill_value is None: + fill_value = maximum_fill_value(self) + # Get the data ................ + result = self.filled(fill_value).max(axis=axis).view(type(self)) + if result.ndim > 0: + result._mask = mask + return result + #........................ + def ptp(self, axis=None, fill_value=None): + """Returns the visible data range (max-min) along the given axis. +If the axis is `None`, applies on a flattened array. Masked values are filled +with `fill_value` for processing. If `fill_value` is None, the maximum is uses +the maximum default, the minimum uses the minimum default.""" + return self.max(axis, fill_value) - self.min(axis, fill_value) + + # Array methods --------------------------------------- + conj = conjugate = _arraymethod('conjugate') + copy = _arraymethod('copy') + diagonal = _arraymethod('diagonal') + take = _arraymethod('take') + ravel = _arraymethod('ravel') + transpose = _arraymethod('transpose') + T = property(fget=lambda self:self.transpose()) + swapaxes = _arraymethod('swapaxes') + clip = _arraymethod('clip', onmask=False) + compress = _arraymethod('compress') + copy = _arraymethod('copy') + squeeze = _arraymethod('squeeze') + #-------------------------------------------- + def tolist(self, fill_value=None): + """Copies the data portion of the array to a hierarchical python list and + returns that list. Data items are converted to the nearest compatible Python + type. Masked values are filled with `fill_value`""" + return self.filled(fill_value).tolist() + #........................ + def tostring(self, fill_value=None): + """a.tostring(order='C', fill_value=None) -> raw copy of array data as a Python string. + + Keyword arguments: + order : order of the data item in the copy {"C","F","A"} (default "C") + fill_value : value used in lieu of missing data + + Construct a Python string containing the raw bytes in the array. The order + of the data in arrays with ndim > 1 is specified by the 'order' keyword and + this keyword overrides the order of the array. The + choices are: + + "C" -- C order (row major) + "Fortran" -- Fortran order (column major) + "Any" -- Current order of array. + None -- Same as "Any" + + Masked data are filled with fill_value. If fill_value is None, the data-type- + dependent default is used.""" + return self.filled(fill_value).tostring() + #-------------------------------------------- + # Backwards Compatibility. Heck... + @property + def data(self): + """Returns the `_data` part of the MaskedArray. +You should really use `_data` instead...""" + return self._data + def raw_data(self): + """Returns the `_data` part of the MaskedArray. +You should really use `_data` instead...""" + return self._data + +##.............................................................................. + + + +#class _arithmethods: +# """Defines a wrapper for arithmetic methods. +#Instead of directly calling a ufunc, the corresponding method of the `array._data` +#object is called instead. +# """ +# def __init__ (self, methodname, fill_self=0, fill_other=0, domain=None): +# """ +#:Parameters: +# - `methodname` (String) : Method name. +# - `fill_self` (Float *[0]*) : Fill value for the instance. +# - `fill_other` (Float *[0]*) : Fill value for the target. +# - `domain` (Domain object *[None]*) : Domain of non-validity. +# """ +# self.methodname = methodname +# self.fill_self = fill_self +# self.fill_other = fill_other +# self.domain = domain +# # +# def __call__ (self, instance, other, *args): +# "Execute the call behavior." +# m_self = instance._mask +# m_other = getmask(other) +# base = filled(instance,self.fill_self) +# target = filled(other, self.fill_other) +# if self.domain is not None: +# # We need to force the domain to a ndarray only. +# if self.fill_other > self.fill_self: +# domain = self.domain(base, target) +# else: +# domain = self.domain(target, base) +# if domain.any(): +# #If `other` is a subclass of ndarray, `filled` must have the +# # same subclass, else we'll lose some info. +# #The easiest then is to fill `target` instead of creating +# # a pure ndarray. +# #Oh, and we better make a copy! +# if isinstance(other, ndarray): +# if target is other: +# # We don't want to modify other: let's copy target, then +# target = target.copy() +# target[:] = numeric.where(fromnumeric.asarray(domain), +# self.fill_other, target) +# else: +# target = numeric.where(fromnumeric.asarray(domain), +# self.fill_other, target) +# m_other = mask_or(m_other, domain) +# m = mask_or(m_self, m_other) +# method = getattr(base, self.methodname) +# return instance.__class__(method(target, *args), mask=m) +# # +# def patch(self): +# """Applies the method `func` from class `method` to MaskedArray""" +# return types.MethodType(self,None,MaskedArray) +#.............................................................................. + +#####-------------------------------------------------------------------------- +#---- --- Shortcuts --- +#####--------------------------------------------------------------------------- +def isMaskedArray(x): + "Is x a masked array, that is, an instance of MaskedArray?" + return isinstance(x, MaskedArray) +isarray = isMaskedArray +isMA = isMaskedArray #backward compatibility +#masked = MaskedArray(0, int, mask=1) +masked_singleton = MaskedArray(0, dtype=int_, mask=True) +masked = masked_singleton + +masked_array = MaskedArray +def array(data, dtype=None, copy=False, order=False, mask=nomask, + keep_mask=True, small_mask=True, hard_mask=None, fill_value=None): + """array(data, dtype=None, copy=True, order=False, mask=nomask, + keep_mask=True, small_mask=True, fill_value=None) +Acts as shortcut to MaskedArray, with options in a different order for convenience. +And backwards compatibility... + """ + #TODO: we should try to put 'order' somwehere + return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, + keep_mask=keep_mask, small_mask=small_mask, + hard_mask=hard_mask, fill_value=fill_value) + +def is_masked(x): + """Returns whether x has some masked values.""" + m = getmask(x) + if m is nomask: + return False + elif m.any(): + return True + return False + + +#####-------------------------------------------------------------------------- +#---- --- Patch methods --- +#####-------------------------------------------------------------------------- +#class _arraymethod: +# """Defines a wrapper for basic array methods. +#Upon call, returns a masked array, where the new `_data` array is the output +#of the corresponding method called on the original `_data`. +# +#If `onmask` is True, the new mask is the output of the method calld on the initial mask. +#If `onmask` is False, the new mask is just a reference to the initial mask. +# +#:Parameters: +# `funcname` : String +# Name of the function to apply on data. +# `onmask` : Boolean *[True]* +# Whether the mask must be processed also (True) or left alone (False). +# """ +# def __init__(self, funcname, onmask=True): +# self._name = funcname +# self._onmask = onmask +# self.__doc__ = getattr(ndarray, self._name).__doc__ +# def __call__(self, instance, *args, **params): +# methodname = self._name +# (d,m) = (instance._data, instance._mask) +# C = instance.__class__ +# if m is nomask: +# return C(getattr(d,methodname).__call__(*args, **params)) +# elif self._onmask: +# return C(getattr(d,methodname).__call__(*args, **params), +# mask=getattr(m,methodname)(*args, **params) ) +# else: +# return C(getattr(d,methodname).__call__(*args, **params), mask=m) +# +# def patch(self): +# "Adds the new method to MaskedArray." +# return types.MethodType(self, None, MaskedArray) +##...................................... +#MaskedArray.conj = MaskedArray.conjugate = _arraymethod('conjugate').patch() +#MaskedArray.diagonal = _arraymethod('diagonal').patch() +#MaskedArray.take = _arraymethod('take').patch() +#MaskedArray.ravel = _arraymethod('ravel').patch() +#MaskedArray.transpose = _arraymethod('transpose').patch() +#MaskedArray.T = _arraymethod('transpose').patch() +#MaskedArray.swapaxes = _arraymethod('swapaxes').patch() +#MaskedArray.clip = _arraymethod('clip', onmask=False).patch() +#MaskedArray.compress = _arraymethod('compress').patch() +#MaskedArray.resize = _arraymethod('resize').patch() +#MaskedArray.copy = _arraymethod('copy').patch() + + + +#####--------------------------------------------------------------------------- +#---- --- Extrema functions --- +#####--------------------------------------------------------------------------- +class _extrema_operation(object): + def __call__(self, a, b=None): + "Executes the call behavior." + if b is None: + return self.reduce(a) + return where(self.compare(a, b), a, b) + #......... + def reduce(self, target, axis=None): + """Reduces target along the given axis.""" + m = getmask(target) + if axis is not None: + kargs = { 'axis' : axis } + else: + kargs = {} + + if m is nomask: + t = self.ufunc.reduce(target, **kargs) + else: + target = target.filled(self.fill_value_func(target)).view(type(target)) + t = self.ufunc.reduce(target, **kargs) + m = umath.logical_and.reduce(m, **kargs) + if hasattr(t, '_mask'): + t._mask = m + elif m: + t = masked + return t + #......... + def outer (self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = logical_or.outer(ma, mb) + result = self.ufunc.outer(filled(a), filled(b)) + result._mask = m + return result +#............................ +class _minimum_operation(_extrema_operation): + "Object to calculate minima" + def __init__ (self): + """minimum(a, b) or minimum(a) +In one argument case, returns the scalar minimum. + """ + self.ufunc = umath.minimum + self.afunc = amin + self.compare = less + self.fill_value_func = minimum_fill_value +#............................ +class _maximum_operation(_extrema_operation): + "Object to calculate maxima" + def __init__ (self): + """maximum(a, b) or maximum(a) + In one argument case returns the scalar maximum. + """ + self.ufunc = umath.maximum + self.afunc = amax + self.compare = greater + self.fill_value_func = maximum_fill_value +#.......................................................... +def min(array, axis=None, out=None): + """Returns the minima along the given axis. +If `axis` is None, applies to the flattened array.""" + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") + if axis is None: + return minimum(array) + else: + return minimum.reduce(array, axis) +#............................ +def max(obj, axis=None, out=None): + """Returns the maxima along the given axis. +If `axis` is None, applies to the flattened array.""" + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") + if axis is None: + return maximum(obj) + else: + return maximum.reduce(obj, axis) +#............................. +def ptp(obj, axis=None): + """a.ptp(axis=None) = a.max(axis)-a.min(axis)""" + try: + return obj.max(axis)-obj.min(axis) + except AttributeError: + return max(obj, axis=axis) - min(obj, axis=axis) + + +#####--------------------------------------------------------------------------- +#---- --- Definition of functions from the corresponding methods --- +#####--------------------------------------------------------------------------- +class _frommethod: + """Defines functions from existing MaskedArray methods. +:ivar _methodname (String): Name of the method to transform. + """ + def __init__(self, methodname): + self._methodname = methodname + self.__doc__ = self.getdoc() + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + try: + return getattr(MaskedArray, self._methodname).__doc__ + except: + return getattr(numpy, self._methodname).__doc__ + def __call__(self, a, *args, **params): + if isinstance(a, MaskedArray): + return getattr(a, self._methodname).__call__(*args, **params) + #FIXME ---- + #As x is not a MaskedArray, we transform it to a ndarray with asarray + #... and call the corresponding method. + #Except that sometimes it doesn't work (try reshape([1,2,3,4],(2,2))) + #we end up with a "SystemError: NULL result without error in PyObject_Call" + #A dirty trick is then to call the initial numpy function... + method = getattr(fromnumeric.asarray(a), self._methodname) + try: + return method(*args, **params) + except SystemError: + return getattr(numpy,self._methodname).__call__(a, *args, **params) + +all = _frommethod('all') +anomalies = anom = _frommethod('anom') +any = _frommethod('any') +conjugate = _frommethod('conjugate') +ids = _frommethod('ids') +nonzero = _frommethod('nonzero') +diagonal = _frommethod('diagonal') +maximum = _maximum_operation() +mean = _frommethod('mean') +minimum = _minimum_operation () +product = _frommethod('prod') +ptp = _frommethod('ptp') +ravel = _frommethod('ravel') +repeat = _frommethod('repeat') +std = _frommethod('std') +sum = _frommethod('sum') +swapaxes = _frommethod('swapaxes') +take = _frommethod('take') +var = _frommethod('var') + +#.............................................................................. +def power(a, b, third=None): + """Computes a**b elementwise. + Masked values are set to 1.""" + if third is not None: + raise MAError, "3-argument power not supported." + ma = getmask(a) + mb = getmask(b) + m = mask_or(ma, mb) + fa = filled(a, 1) + fb = filled(b, 1) + if fb.dtype.char in typecodes["Integer"]: + return masked_array(umath.power(fa, fb), m) + md = make_mask((fa < 0), small_mask=1) + m = mask_or(m, md) + if m is nomask: + return masked_array(umath.power(fa, fb)) + else: + fa[m] = 1 + return masked_array(umath.power(fa, fb), m) + +#.............................................................................. +def argsort(a, axis=None, kind='quicksort', order=None, fill_value=None): + """Returns an array of indices that sort 'a' along the specified axis. + Masked values are filled beforehand to `fill_value`. + If `fill_value` is None, uses the default for the data type. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `kind` : String *['quicksort']* + Sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + + Returns: array of indices that sort 'a' along the specified axis. + + This method executes an indirect sort along the given axis using the + algorithm specified by the kind keyword. It returns an array of indices of + the same shape as 'a' that index data along the given axis in sorted order. + + The various sorts are characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order. The three + available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is not + along the last axis. Consequently, sorts along the last axis are faster and use + less space than sorts along other axis. + """ + if fill_value is None: + fill_value = default_fill_value(a) + d = filled(a, fill_value) + if axis is None: + return d.argsort(kind=kind, order=order) + return d.argsort(axis, kind=kind, order=order) + +def argmin(a, axis=None, fill_value=None): + """Returns the array of indices for the minimum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = default_fill_value(a) + d = filled(a, fill_value) + return d.argmin(axis=axis) + +def argmax(a, axis=None, fill_value=None): + """Returns the array of indices for the maximum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = default_fill_value(a) + try: + fill_value = - fill_value + except: + pass + d = filled(a, fill_value) + return d.argmax(axis=axis) + +def sort(a, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None): + """ + Sort a along the given axis. + +Keyword arguments: + +axis -- axis to be sorted (default -1) +kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. +order -- If a has fields defined, then the order keyword can be the + field name to sort on or a list (or tuple) of field names + to indicate the order that fields should be used to define + the sort. +endwith--Boolean flag indicating whether missing values (if any) should + be forced in the upper indices (at the end of the array) or + lower indices (at the beginning). + +Returns: None. + +This method sorts 'a' in place along the given axis using the algorithm +specified by the kind keyword. + +The various sorts may characterized by average speed, worst case +performance, need for work space, and whether they are stable. A stable +sort keeps items with the same key in the same relative order and is most +useful when used with argsort where the key might differ from the items +being sorted. The three available algorithms have the following properties: + +|------------------------------------------------------| +| kind | speed | worst case | work space | stable| +|------------------------------------------------------| +|'quicksort'| 1 | O(n^2) | 0 | no | +|'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | +|'heapsort' | 3 | O(n*log(n)) | 0 | no | +|------------------------------------------------------| + +All the sort algorithms make temporary copies of the data when the sort is +not along the last axis. Consequently, sorts along the last axis are faster +and use less space than sorts along other axis. + +""" + a = numeric.asanyarray(a) + if fill_value is None: + if endwith: + filler = minimum_fill_value(a) + else: + filler = maximum_fill_value(a) + else: + filler = fill_value +# return + indx = numpy.indices(a.shape).tolist() + indx[axis] = filled(a,filler).argsort(axis=axis,kind=kind,order=order) + return a[indx] + +def compressed(x): + """Returns a compressed version of a masked array (or just the array if it + wasn't masked first).""" + if getmask(x) is None: + return x + else: + return x.compressed() + +def count(a, axis = None): + "Count of the non-masked elements in a, or along a certain axis." + a = masked_array(a) + return a.count(axis) + +def concatenate(arrays, axis=0): + "Concatenates the arrays along the given axis" + d = numeric.concatenate([filled(a) for a in arrays], axis) + rcls = get_masked_subclass(*arrays) + data = d.view(rcls) + for x in arrays: + if getmask(x) is not nomask: + break + else: + return data + dm = numeric.concatenate([getmaskarray(a) for a in arrays], axis) + dm = make_mask(dm, copy=False, small_mask=True) + data._mask = dm + return data + +def expand_dims(x,axis): + """Expand the shape of a by including newaxis before given axis.""" + result = n_expand_dims(x,axis) + if isinstance(x, MaskedArray): + new_shape = result.shape + result = x.view() + result.shape = new_shape + if result._mask is not nomask: + result._mask.shape = new_shape + return result + +#...................................... +def left_shift (a, n): + "Left shift n bits" + m = getmask(a) + if m is nomask: + d = umath.left_shift(filled(a), n) + return masked_array(d) + else: + d = umath.left_shift(filled(a, 0), n) + return masked_array(d, mask=m) + +def right_shift (a, n): + "Right shift n bits" + m = getmask(a) + if m is nomask: + d = umath.right_shift(filled(a), n) + return masked_array(d) + else: + d = umath.right_shift(filled(a, 0), n) + return masked_array(d, mask=m) +#...................................... +def put(a, indices, values, mode='raise'): + """Sets storage-indexed locations to corresponding values. + Values and indices are filled if necessary.""" + # We can't use 'frommethod', the order of arguments is different + try: + return a.put(indices, values, mode=mode) + except AttributeError: + return fromnumeric.asarray(a).put(indices, values, mode=mode) + +def putmask(a, mask, values): #, mode='raise'): + """`putmask(a, mask, v)` results in `a = v` for all places where `mask` is true. +If `v` is shorter than `mask`, it will be repeated as necessary. +In particular `v` can be a scalar or length 1 array.""" + # We can't use 'frommethod', the order of arguments is different + try: + return a.putmask(values, mask) + except AttributeError: + return fromnumeric.asarray(a).putmask(values, mask) + +def transpose(a,axes=None): + """Returns a view of the array with dimensions permuted according to axes. +If `axes` is None (default), returns array with dimensions reversed. + """ + #We can't use 'frommethod', as 'transpose' doesn't take keywords + try: + return a.transpose(axes) + except AttributeError: + return fromnumeric.asarray(a).transpose(axes) + +def reshape(a, new_shape): + """Changes the shape of the array `a` to `new_shape`.""" + #We can't use 'frommethod', it whine about some parameters. Dmmit. + try: + return a.reshape(new_shape) + except AttributeError: + return fromnumeric.asarray(a).reshape(new_shape) + +def resize(x, new_shape): + """resize(a,new_shape) returns a new array with the specified shape. + The total size of the original array can be any size. + The new array is filled with repeated copies of a. If a was masked, the new + array will be masked, and the new mask will be a repetition of the old one. + """ + # We can't use _frommethods here, as N.resize is notoriously whiny. + m = getmask(x) + if m is not nomask: + m = fromnumeric.resize(m, new_shape) + result = fromnumeric.resize(x, new_shape).view(get_masked_subclass(x)) + if result.ndim: + result._mask = m + return result + + +#................................................ +def rank(obj): + """Gets the rank of sequence a (the number of dimensions, not a matrix rank) +The rank of a scalar is zero.""" + return fromnumeric.rank(filled(obj)) +# +def shape(obj): + """Returns the shape of `a` (as a function call which also works on nested sequences). + """ + return fromnumeric.shape(filled(obj)) +# +def size(obj, axis=None): + """Returns the number of elements in the array along the given axis, +or in the sequence if `axis` is None. + """ + return fromnumeric.size(filled(obj), axis) +#................................................ + +#####-------------------------------------------------------------------------- +#---- --- Extra functions --- +#####-------------------------------------------------------------------------- +def where (condition, x, y): + """where(condition, x, y) is x where condition is nonzero, y otherwise. + condition must be convertible to an integer array. + Answer is always the shape of condition. + The type depends on x and y. It is integer if both x and y are + the value masked. + """ + fc = filled(not_equal(condition, 0), 0) + xv = filled(x) + xm = getmask(x) + yv = filled(y) + ym = getmask(y) + d = numeric.choose(fc, (yv, xv)) + md = numeric.choose(fc, (ym, xm)) + m = getmask(condition) + m = make_mask(mask_or(m, md), copy=False, small_mask=True) + return masked_array(d, mask=m) + +def choose (indices, t, out=None, mode='raise'): + "Returns array shaped like indices with elements chosen from t" + #TODO: implement options `out` and `mode`, if possible. + def fmask (x): + "Returns the filled array, or True if ``masked``." + if x is masked: + return 1 + return filled(x) + def nmask (x): + "Returns the mask, True if ``masked``, False if ``nomask``." + if x is masked: + return 1 + m = getmask(x) + if m is nomask: + return 0 + return m + c = filled(indices, 0) + masks = [nmask(x) for x in t] + a = [fmask(x) for x in t] + d = numeric.choose(c, a) + m = numeric.choose(c, masks) + m = make_mask(mask_or(m, getmask(indices)), copy=0, small_mask=1) + return masked_array(d, mask=m) + +def round_(a, decimals=0, out=None): + """Returns reference to result. Copies a and rounds to 'decimals' places. + + Keyword arguments: + decimals -- number of decimals to round to (default 0). May be negative. + out -- existing array to use for output (default copy of a). + + Return: + Reference to out, where None specifies a copy of the original array a. + + Round to the specified number of decimals. When 'decimals' is negative it + specifies the number of positions to the left of the decimal point. The + real and imaginary parts of complex numbers are rounded separately. + Nothing is done if the array is not of float type and 'decimals' is greater + than or equal to 0.""" + result = fromnumeric.round_(filled(a), decimals, out) + if isinstance(a,MaskedArray): + result = result.view(type(a)) + result._mask = a._mask + else: + result = result.view(MaskedArray) + return result + +def arange(start, stop=None, step=1, dtype=None): + """Just like range() except it returns a array whose type can be specified + by the keyword argument dtype. + """ + return array(numeric.arange(start, stop, step, dtype),mask=nomask) + +def inner(a, b): + """inner(a,b) returns the dot product of two arrays, which has + shape a.shape[:-1] + b.shape[:-1] with elements computed by summing the + product of the elements from the last dimensions of a and b. + Masked elements are replace by zeros. + """ + fa = filled(a, 0) + fb = filled(b, 0) + if len(fa.shape) == 0: + fa.shape = (1,) + if len(fb.shape) == 0: + fb.shape = (1,) + return masked_array(numeric.inner(fa, fb)) +innerproduct = inner + +def outer(a, b): + """outer(a,b) = {a[i]*b[j]}, has shape (len(a),len(b))""" + fa = filled(a, 0).ravel() + fb = filled(b, 0).ravel() + d = numeric.outer(fa, fb) + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + return masked_array(d) + ma = getmaskarray(a) + mb = getmaskarray(b) + m = make_mask(1-numeric.outer(1-ma, 1-mb), copy=0) + return masked_array(d, mask=m) +outerproduct = outer + +def allequal (a, b, fill_value=True): + """ +Returns `True` if all entries of a and b are equal, using +fill_value as a truth value where either or both are masked. + """ + m = mask_or(getmask(a), getmask(b)) + if m is nomask: + x = filled(a) + y = filled(b) + d = umath.equal(x, y) + return d.all() + elif fill_value: + x = filled(a) + y = filled(b) + d = umath.equal(x, y) + dm = array(d, mask=m, copy=False) + return dm.filled(True).all(None) + else: + return False + +def allclose (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8): + """ Returns `True` if all elements of `a` and `b` are equal subject to given tolerances. +If `fill_value` is True, masked values are considered equal. +If `fill_value` is False, masked values considered unequal. +The relative error rtol should be positive and << 1.0 +The absolute error `atol` comes into play for those elements of `b` + that are very small or zero; it says how small `a` must be also. + """ + m = mask_or(getmask(a), getmask(b)) + d1 = filled(a) + d2 = filled(b) + x = filled(array(d1, copy=0, mask=m), fill_value).astype(float) + y = filled(array(d2, copy=0, mask=m), 1).astype(float) + d = umath.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y)) + return fromnumeric.alltrue(fromnumeric.ravel(d)) + +#.............................................................................. +def asarray(a, dtype=None): + """asarray(data, dtype) = array(data, dtype, copy=0) +Returns `a` as an masked array. +No copy is performed if `a` is already an array. +Subclasses are converted to base class MaskedArray. + """ + return masked_array(a, dtype=dtype, copy=False, keep_mask=True) + +def empty(new_shape, dtype=float): + """empty((d1,...,dn),dtype=float,order='C') +Returns a new array of shape (d1,...,dn) and given type with all its +entries uninitialized. This can be faster than zeros.""" + return numeric.empty(new_shape, dtype).view(MaskedArray) + +def empty_like(a): + """empty_like(a) +Returns an empty (uninitialized) array of the shape and typecode of a. +Note that this does NOT initialize the returned array. +If you require your array to be initialized, you should use zeros_like().""" + return numeric.empty_like(a).view(MaskedArray) + +def ones(new_shape, dtype=float): + """ones(shape, dtype=None) +Returns an array of the given dimensions, initialized to all ones.""" + return numeric.ones(new_shape, dtype).view(MaskedArray) + +def zeros(new_shape, dtype=float): + """zeros(new_shape, dtype=None) +Returns an array of the given dimensions, initialized to all zeros.""" + return numeric.zeros(new_shape, dtype).view(MaskedArray) + +#####-------------------------------------------------------------------------- +#---- --- Pickling --- +#####-------------------------------------------------------------------------- +#FIXME: We're kinda stuck with forcing the mask to have the same shape as the data +def _mareconstruct(subtype, baseshape, basetype,): + """Internal function that builds a new MaskedArray from the information stored +in a pickle.""" + _data = ndarray.__new__(ndarray, baseshape, basetype) + _mask = ndarray.__new__(ndarray, baseshape, basetype) + return MaskedArray.__new__(subtype, _data, mask=_mask, dtype=basetype, small_mask=False) + +def _getstate(a): + "Returns the internal state of the masked array, for pickling purposes." + state = (1, + a.shape, + a.dtype, + a.flags.fnc, + a.tostring(), + getmaskarray(a).tostring()) + return state + +def _setstate(a, state): + """Restores the internal state of the masked array, for pickling purposes. +`state` is typically the output of the ``__getstate__`` output, and is a 5-tuple: + + - class name + - a tuple giving the shape of the data + - a typecode for the data + - a binary string for the data + - a binary string for the mask. + """ + (ver, shp, typ, isf, raw, msk) = state + super(MaskedArray, a).__setstate__((shp, typ, isf, raw)) + (a._mask).__setstate__((shp, dtype('|b1'), isf, msk)) + +def _reduce(a): + """Returns a 3-tuple for pickling a MaskedArray.""" + return (_mareconstruct, + (a.__class__, (0,), 'b', ), + a.__getstate__()) + +def dump(a,F): + """Pickles the MaskedArray `a` to the file `F`. +`F` can either be the handle of an exiting file, or a string representing a file name. + """ + if not hasattr(F,'readline'): + F = open(F,'w') + return cPickle.dump(a,F) + +def dumps(a): + """Returns 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.""" + if not hasattr(F, 'readline'): + F = open(F,'r') + return cPickle.load(F) + +def loads(strg): + "Loads a pickle from the current string.""" + return cPickle.loads(strg) + +MaskedArray.__getstate__ = _getstate +MaskedArray.__setstate__ = _setstate +MaskedArray.__reduce__ = _reduce +MaskedArray.__dump__ = dump +MaskedArray.__dumps__ = dumps + +################################################################################ + +if __name__ == '__main__': + import numpy as N + from maskedarray.testutils import assert_equal, assert_array_equal, assert_mask_equal + pi = N.pi +# coremodule = __main__ + + a = array([1,2,3,4,5],mask=[0,1,0,0,0]) + x = add.reduce(a) + assert_equal(add.reduce(a), 13) + + if 0: + x = masked_array([1,2,3], mask=[1,0,0]) + mx = masked_array(x) + assert_equal(mx.mask, x.mask) + mx = masked_array(x, mask=[0,1,0], keep_mask=False) + assert_equal(mx.mask, [0,1,0]) + mx = masked_array(x, mask=[0,1,0], keep_mask=True) + assert_equal(mx.mask, [1,1,0]) + #We default to true + mx = masked_array(x, mask=[0,1,0]) + assert_equal(mx.mask, [1,1,0]) + if 0: + import numpy.core.ma as nma + x = nma.arange(5) + x[2] = nma.masked + X = masked_array(x, mask=x._mask) + assert_equal(X._mask, x.mask) + assert_equal(X._data, x._data) + X = masked_array(x) + assert_equal(X._data, x._data) + assert_equal(X._mask, x.mask) + assert_equal(getmask(x), [0,0,1,0,0]) + if 0: + d = arange(5) + 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) + x[[1,4]] = [10,40] + assert( x.mask is not m) + assert( x[3] is masked) + assert( x[4] is not masked) + assert_equal(x, [0,10,2,-1,40]) + if 0: + d = arange(5) + n = [0,0,0,1,1] + m = make_mask(n) + xh = array(d, mask = m, hard_mask=True) + # We need to copy, to avoid updating d in xh! + xs = array(d, mask = m, hard_mask=False, copy=True) + xh[[1,4]] = [10,40] + xs[[1,4]] = [10,40] + assert_equal(xh._data, [0,10,2,3,4]) + 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) + xh[1:4] = [10,20,30] + xs[1:4] = [10,20,30] + assert_equal(xh._data, [0,10,20,3,4]) + assert_equal(xs._data, [0,10,20,30,40]) + #assert_equal(xh.mask.ctypes.data, m.ctypes.data) + assert_equal(xs.mask, nomask) + xh[0] = masked + xs[0] = masked + assert_equal(xh.mask, [1,0,0,1,1]) + assert_equal(xs.mask, [1,0,0,0,0]) + xh[:] = 1 + xs[:] = 1 + assert_equal(xh._data, [0,1,1,3,4]) + assert_equal(xs._data, [1,1,1,1,1]) + assert_equal(xh.mask, [1,0,0,1,1]) + assert_equal(xs.mask, nomask) + # Switch to soft mask + xh.soften_mask() + xh[:] = arange(5) + assert_equal(xh._data, [0,1,2,3,4]) + assert_equal(xh.mask, nomask) + # Switch back to hard mask + xh.harden_mask() + xh[xh<3] = masked + assert_equal(xh._data, [0,1,2,3,4]) + assert_equal(xh._mask, [1,1,1,0,0]) + xh[filled(xh>1,False)] = 5 + assert_equal(xh._data, [0,1,2,5,5]) + assert_equal(xh._mask, [1,1,1,0,0]) + # + xh = array([[1,2],[3,4]], mask = [[1,0],[0,0]], hard_mask=True) + xh[0] = 0 + assert_equal(xh._data, [[1,0],[3,4]]) + assert_equal(xh._mask, [[1,0],[0,0]]) + xh[-1,-1] = 5 + assert_equal(xh._data, [[1,0],[3,5]]) + assert_equal(xh._mask, [[1,0],[0,0]]) + xh[filled(xh<5,False)] = 2 + assert_equal(xh._data, [[1,2],[2,5]]) + assert_equal(xh._mask, [[1,0],[0,0]]) + # + "Another test of hardmask" + d = arange(5) + n = [0,0,0,1,1] + m = make_mask(n) + xh = array(d, mask = m, hard_mask=True) + xh[4:5] = 999 + #assert_equal(xh.mask.ctypes.data, m.ctypes.data) + xh[0:1] = 999 + assert_equal(xh._data,[999,1,2,3,4]) + if 0: + x = N.array([[ 0.13, 0.26, 0.90], + [ 0.28, 0.33, 0.63], + [ 0.31, 0.87, 0.70]]) + m = N.array([[ True, False, False], + [False, False, False], + [True, True, False]], dtype=N.bool_) + mx = masked_array(x, mask=m) + xbig = N.array([[False, False, True], + [False, False, True], + [False, True, True]], dtype=N.bool_) + mxbig = (mx > 0.5) + mxsmall = (mx < 0.5) + # + assert (mxbig.all()==False) + assert (mxbig.any()==True) + y = mxbig.all(0) + assert_equal(mxbig.all(0),[False, False, True]) + assert_equal(mxbig.all(1), [False, False, True]) + assert_equal(mxbig.any(0),[False, False, True]) + assert_equal(mxbig.any(1), [True, True, True]) + + if 1: + "Tests put." + d = arange(5) + 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) + x[[1,4]] = [10,40] + assert( x.mask is not m) + assert( x[3] is masked) + assert( 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) + i = [0,2,4,6] + x.put(i, [6,4,2,0]) + assert_equal(x, asarray([6,1,4,3,2,5,0,7,8,9,])) + assert_equal(x.mask, [0,0,0,0,0,1,0,0,0,0]) + x.put(i, masked_array([0,2,4,6],[1,0,1,0])) + assert_array_equal(x, [0,1,2,3,4,5,6,7,8,9,]) + assert_equal(x.mask, [1,0,0,0,1,1,0,0,0,0]) + # + x = masked_array(arange(10), mask=[1,0,0,0,0]*2) + put(x, i, [6,4,2,0]) + assert_equal(x, asarray([6,1,4,3,2,5,0,7,8,9,])) + assert_equal(x.mask, [0,0,0,0,0,1,0,0,0,0]) + put(x, i, masked_array([0,2,4,6],[1,0,1,0])) + assert_array_equal(x, [0,1,2,3,4,5,6,7,8,9,]) + assert_equal(x.mask, [1,0,0,0,1,1,0,0,0,0]) + + if 1: + x = arange(20) + x = x.reshape(4,5) + x.flat[5] = 12 + assert x[1,0] == 12 + z = x + 10j * x + assert_equal(z.real, x) + assert_equal(z.imag, 10*x) + assert_equal((z*conjugate(z)).real, 101*x*x) + z.imag[...] = 0.0 + if 1: + x = array([1.0, 0, -1, pi/2]*2, mask=[0,1]+[0]*6) + y = array([1.0, 0, -1, pi/2]*2, mask=[1,0]+[0]*6) + d = (x,y) + + z = N.add(x, y) + + for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', + 'sin', 'cos', 'tan', + 'arcsin', 'arccos', 'arctan', + 'sinh', 'cosh', 'tanh', + 'arcsinh', + 'arccosh', + 'arctanh', + 'absolute', 'fabs', 'negative', + # 'nonzero', 'around', + 'floor', 'ceil', + # 'sometrue', 'alltrue', + 'logical_not', + 'add', 'subtract', 'multiply', + 'divide', 'true_divide', 'floor_divide', + 'remainder', 'fmod', 'hypot', 'arctan2', + 'equal', 'not_equal', 'less_equal', 'greater_equal', + 'less', 'greater', + 'logical_and', 'logical_or', 'logical_xor', + ]: + print f + try: + uf = getattr(umath, f) + except AttributeError: + uf = getattr(fromnumeric, f) + mf = eval(f) #getattr(coremodule, f) + args = d[:uf.nin] + ur = uf(*args) + mr = mf(*args) + assert_equal(ur.filled(0), mr.filled(0), f) + assert_mask_equal(ur.mask, mr.mask) Added: trunk/scipy/sandbox/maskedarray/alternative_versions/core_ini.py =================================================================== --- trunk/scipy/sandbox/maskedarray/alternative_versions/core_ini.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/alternative_versions/core_ini.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,3033 @@ +"""MA: a facility for dealing with missing observations +MA is generally used as a numpy.array look-alike. +by Paul F. Dubois. + +Copyright 1999, 2000, 2001 Regents of the University of California. +Released for unlimited redistribution. +Adapted for numpy_core 2005 by Travis Oliphant and +(mainly) Paul Dubois. + +Subclassing of the base ndarray 2006 by Pierre Gerard-Marchant. +pgmdevlist_at_gmail_dot_com + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: core_ini.py 3473 2007-10-29 15:18:13Z jarrod.millman $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" +__version__ = '1.0' +__revision__ = "$Revision: 3473 $" +__date__ = '$Date: 2007-10-29 08:18:13 -0700 (Mon, 29 Oct 2007) $' + +__all__ = ['MAError', 'MaskType', 'MaskedArray', + 'bool_', 'complex_', 'float_', 'int_', 'object_', + 'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue', + 'amax', 'amin', 'anom', 'anomalies', 'any', 'arange', + 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', + 'arctanh', 'argmax', 'argmin', 'argsort', 'around', + 'array', 'asarray', + 'bitwise_and', 'bitwise_or', 'bitwise_xor', + 'ceil', 'choose', 'compressed', 'concatenate', 'conjugate', + 'cos', 'cosh', 'count', + 'diagonal', 'divide', 'dump', 'dumps', + 'empty', 'empty_like', 'equal', 'exp', + 'fabs', 'fmod', 'filled', 'floor', 'floor_divide', + 'getmask', 'getmaskarray', 'greater', 'greater_equal', 'hypot', + 'ids', 'inner', 'innerproduct', + 'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', + 'left_shift', 'less', 'less_equal', 'load', 'loads', 'log', 'log10', + 'logical_and', 'logical_not', 'logical_or', 'logical_xor', + 'make_mask', 'make_mask_none', 'mask_or', 'masked', + 'masked_array', 'masked_equal', 'masked_greater', + 'masked_greater_equal', 'masked_inside', 'masked_less', + 'masked_less_equal', 'masked_not_equal', 'masked_object', + 'masked_outside', 'masked_print_option', 'masked_singleton', + 'masked_values', 'masked_where', 'max', 'maximum', 'mean', 'min', + 'minimum', 'multiply', + 'negative', 'nomask', 'nonzero', 'not_equal', + 'ones', 'outer', 'outerproduct', + 'power', 'product', 'ptp', 'put', 'putmask', + 'rank', 'ravel', 'remainder', 'repeat', 'reshape', 'resize', + 'right_shift', 'round_', + 'shape', 'sin', 'sinh', 'size', 'sometrue', 'sort', 'sqrt', 'std', + 'subtract', 'sum', 'swapaxes', + 'take', 'tan', 'tanh', 'transpose', 'true_divide', + 'var', 'where', + 'zeros'] + +import sys +import types +import cPickle +# +import numpy +from numpy import bool_, complex_, float_, int_, object_, str_ + +import numpy.core.umath as umath +import numpy.core.fromnumeric as fromnumeric +from numpy.core.numeric import ndarray +from numpy.core.fromnumeric import amax, amin +import numpy.core.numerictypes as ntypes +from numpy.core.numerictypes import bool_, typecodes +from numpy.core.multiarray import dtype +import numpy.core.numeric as numeric +from numpy.lib.shape_base import expand_dims as n_expand_dims +import warnings + + + +MaskType = bool_ +nomask = MaskType(0) + +divide_tolerance = 1.e-35 +numpy.seterr(all='ignore') + +#####-------------------------------------------------------------------------- +#---- --- Helper functions --- +#####-------------------------------------------------------------------------- +def convert_typecode(f,dtchar): + """Converts the type of `f` to a type compatible with `dtchar`, for inline operations.""" + ftype = f.dtype.char + if dtchar == ftype: + return f + elif dtchar in typecodes['Integer']: + if ftype in typecodes['Integer']: + f = f.astype(dtchar) + else: + raise TypeError, 'Incorrect type for in-place operation.' + elif dtchar in typecodes['Float']: + if ftype in typecodes['Integer']: + f = f.astype(dtchar) + elif ftype in typecodes['Float']: + f = f.astype(dtchar) + else: + raise TypeError, 'Incorrect type for in-place operation.' + elif dtchar in typecodes['Complex']: + if ftype in typecodes['Integer']: + f = f.astype(dtchar) + elif ftype in typecodes['Float']: + f = f.astype(dtchar) + elif ftype in typecodes['Complex']: + f = f.astype(dtchar) + else: + raise TypeError, 'Incorrect type for in-place operation.' + else: + raise TypeError, 'Incorrect type for in-place operation.' + return f + +#####-------------------------------------------------------------------------- +#---- --- Exceptions --- +#####-------------------------------------------------------------------------- +class MAError(Exception): + "Class for MA related errors." + def __init__ (self, args=None): + "Creates an exception." + Exception.__init__(self,args) + self.args = args + def __str__(self): + "Calculates the string representation." + return str(self.args) + __repr__ = __str__ + +#####-------------------------------------------------------------------------- +#---- --- Filling options --- +#####-------------------------------------------------------------------------- +# b: boolean - c: complex - f: floats - i: integer - O: object - S: string +default_filler = {'b': True, + 'c' : 1.e20 + 0.0j, + 'f' : 1.e20, + 'i' : 999999, + 'O' : '?', + 'S' : 'N/A', + 'u' : 999999, + 'V' : '???', + } +#{0: , +# 1: , +# 2: , +# 3: , +# 4: , +# 5: , +# 6: , +# 7: , +# 8: , +# 9: , +# 10: , +# 11: , +# 12: , +# 13: , +# 14: , +# 15: , +# 16: , +# 17: , +# 18: , +# 19: , +# 20: , +max_filler = ntypes._minvals +max_filler.update([(k,-numeric.inf) for k in [numpy.float32, numpy.float64]]) +min_filler = ntypes._maxvals +min_filler.update([(k,numeric.inf) for k in [numpy.float32, numpy.float64]]) +if 'float128' in ntypes.typeDict: + max_filler.update([(numpy.float128,-numeric.inf)]) + min_filler.update([(numpy.float128, numeric.inf)]) + + +def default_fill_value (obj): + "Calculates the default fill value for an object `obj`." + if hasattr(obj,'dtype'): + return default_filler[obj.dtype.kind] + elif isinstance(obj, float): + return default_filler['f'] + elif isinstance(obj, int) or isinstance(obj, long): + return default_filler['i'] + elif isinstance(obj, str): + return default_filler['S'] + elif isinstance(obj, complex): + return default_filler['c'] + elif isinstance(obj, numeric.dtype): + return default_filler[obj.kind] + else: + return default_filler['O'] + +def minimum_fill_value (obj): + "Calculates the default fill value suitable for taking the minimum of `obj`." + if hasattr(obj, 'dtype'): + objtype = obj.dtype + filler = min_filler[objtype] + if filler is None: + raise TypeError, 'Unsuitable type for calculating minimum.' + return filler + elif isinstance(obj, float): + return min_filler[ntypes.typeDict['float_']] + elif isinstance(obj, int): + return min_filler[ntypes.typeDict['int_']] + elif isinstance(obj, long): + return min_filler[ntypes.typeDict['uint']] + elif isinstance(obj, numeric.dtype): + return min_filler[obj] + else: + raise TypeError, 'Unsuitable type for calculating minimum.' + +def maximum_fill_value (obj): + "Calculates the default fill value suitable for taking the maximum of `obj`." + if hasattr(obj, 'dtype'): + objtype = obj.dtype + filler = max_filler[objtype] + if filler is None: + raise TypeError, 'Unsuitable type for calculating minimum.' + return filler + elif isinstance(obj, float): + return max_filler[ntypes.typeDict['float_']] + elif isinstance(obj, int): + return max_filler[ntypes.typeDict['int_']] + elif isinstance(obj, long): + return max_filler[ntypes.typeDict['uint']] + elif isinstance(obj, numeric.dtype): + return max_filler[obj] + else: + raise TypeError, 'Unsuitable type for calculating minimum.' + +def set_fill_value (a, fill_value): + "Sets the fill value of `a` if it is a masked array." + if isinstance(a, MaskedArray): + a.set_fill_value(fill_value) + +def get_fill_value (a): + """Returns the fill value of `a`, if any. + Otherwise, returns the default fill value for that type. + """ + if isinstance(a, MaskedArray): + result = a.fill_value + else: + result = default_fill_value(a) + return result + +def common_fill_value (a, b): + "Returns the common fill_value of `a` and `b`, if any, or `None`." + t1 = get_fill_value(a) + t2 = get_fill_value(b) + if t1 == t2: + return t1 + return None + +#................................................ +def filled(a, value = None): + """Returns `a` as an array with masked data replaced by `value`. +If `value` is `None` or the special element `masked`, `get_fill_value(a)` +is used instead. + +If `a` is already a contiguous numeric array, `a` itself is returned. + +`filled(a)` can be used to be sure that the result is numeric when passing +an object a to other software ignorant of MA, in particular to numpy itself. + """ + if hasattr(a, 'filled'): + return a.filled(value) + elif isinstance(a, ndarray): # and a.flags['CONTIGUOUS']: + return a + elif isinstance(a, types.DictType): + return numeric.array(a, 'O') + else: + return numeric.array(a) + +#####-------------------------------------------------------------------------- +#---- --- Ufuncs --- +#####-------------------------------------------------------------------------- +ufunc_domain = {} +ufunc_fills = {} + +class domain_check_interval: + """Defines a valid interval, +so that `domain_check_interval(a,b)(x) = true` where `x < a` or `x > b`.""" + def __init__(self, a, b): + "domain_check_interval(a,b)(x) = true where x < a or y > b" + if (a > b): + (a, b) = (b, a) + self.a = a + self.b = b + + def __call__ (self, x): + "Execute the call behavior." + return umath.logical_or(umath.greater (x, self.b), + umath.less(x, self.a)) +#............................ +class domain_tan: + """Defines a valid interval for the `tan` function, +so that `domain_tan(eps) = True where `abs(cos(x)) < eps`""" + def __init__(self, eps): + "domain_tan(eps) = true where abs(cos(x)) < eps)" + self.eps = eps + def __call__ (self, x): + "Execute the call behavior." + return umath.less(umath.absolute(umath.cos(x)), self.eps) +#............................ +class domain_safe_divide: + """defines a domain for safe division.""" + def __init__ (self, tolerance=divide_tolerance): + self.tolerance = tolerance + def __call__ (self, a, b): + return umath.absolute(a) * self.tolerance >= umath.absolute(b) +#............................ +class domain_greater: + "domain_greater(v)(x) = true where x <= v" + def __init__(self, critical_value): + "domain_greater(v)(x) = true where x <= v" + self.critical_value = critical_value + + def __call__ (self, x): + "Execute the call behavior." + return umath.less_equal(x, self.critical_value) +#............................ +class domain_greater_equal: + "domain_greater_equal(v)(x) = true where x < v" + def __init__(self, critical_value): + "domain_greater_equal(v)(x) = true where x < v" + self.critical_value = critical_value + + def __call__ (self, x): + "Execute the call behavior." + return umath.less(x, self.critical_value) +#.............................................................................. +class masked_unary_operation: + """Defines masked version of unary operations, +where invalid values are pre-masked. + +:IVariables: + - `f` : function. + - `fill` : Default filling value *[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, mufunc, fill=0, domain=None): + """ masked_unary_operation(aufunc, fill=0, domain=None) + aufunc(fill) must be defined + self(x) returns aufunc(x) + with masked values where domain(x) is true or getmask(x) is true. + """ + self.f = mufunc + self.fill = fill + self.domain = domain + self.__doc__ = getattr(mufunc, "__doc__", str(mufunc)) + self.__name__ = getattr(mufunc, "__name__", str(mufunc)) + ufunc_domain[mufunc] = domain + ufunc_fills[mufunc] = fill + # + def __call__ (self, a, *args, **kwargs): + "Execute the call behavior." +# numeric tries to return scalars rather than arrays when given scalars. + m = getmask(a) + d1 = filled(a, self.fill) + if self.domain is not None: + m = mask_or(m, numeric.asarray(self.domain(d1))) + result = self.f(d1, *args, **kwargs) + # + if isinstance(result, MaskedArray): + return result.__class__(result, mask=m) + return masked_array(result, mask=m) + # + def __str__ (self): + return "Masked version of %s. [Invalid values are masked]" % str(self.f) +#.............................................................................. +class masked_binary_operation: + """Defines masked version of binary operations, +where invalid values are pre-masked. + +:IVariables: + - `f` : function. + - `fillx` : Default filling value for first array*[0]*. + - `filly` : Default filling value for second array*[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, mbfunc, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + self.f = mbfunc + self.fillx = fillx + self.filly = filly + self.__doc__ = getattr(mbfunc, "__doc__", str(mbfunc)) + self.__name__ = getattr(mbfunc, "__name__", str(mbfunc)) + ufunc_domain[mbfunc] = None + ufunc_fills[mbfunc] = (fillx, filly) + # + def __call__ (self, a, b, *args, **kwargs): + "Execute the call behavior." + m = mask_or(getmask(a), getmask(b)) + d1 = filled(a, self.fillx) + d2 = filled(b, self.filly) + result = self.f(d1, d2, *args, **kwargs) +# if isinstance(result, ndarray) \ +# and m.ndim != 0 \ +# and m.shape != result.shape: +# m = mask_or(getmaskarray(a), getmaskarray(b)) + if isinstance(result, MaskedArray): + return result.__class__(result, mask=m) + return masked_array(result, mask=m) + # + def reduce (self, target, axis=0, dtype=None): + """Reduces `target` along the given `axis`.""" + if isinstance(target, MaskedArray): + tclass = target.__class__ + else: + tclass = MaskedArray + m = getmask(target) + t = filled(target, self.filly) + if t.shape == (): + t = t.reshape(1) + if m is not nomask: + m = make_mask(m, copy=1) + m.shape = (1,) + if m is nomask: + return tclass(self.f.reduce (t, axis)) + else: + t = tclass(t, mask=m) + # XXX: "or t.dtype" below is a workaround for what appears + # XXX: to be a bug in reduce. + t = self.f.reduce(filled(t, self.filly), axis, dtype=dtype or t.dtype) + m = umath.logical_and.reduce(m, axis) + if isinstance(t, ndarray): + return tclass(t, mask=m, fill_value=get_fill_value(target)) + elif m: + return masked + else: + return t + + def outer (self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = umath.logical_or.outer(ma, mb) + d = self.f.outer(filled(a, self.fillx), filled(b, self.filly)) + if isinstance(d, MaskedArray): + return d.__class__(d, mask=m) + return masked_array(d, mask=m) + + def accumulate (self, target, axis=0): + """Accumulates `target` along `axis` after filling with y fill value.""" + if isinstance(target, MaskedArray): + tclass = target.__class__ + else: + tclass = masked_array + t = filled(target, self.filly) + return tclass(self.f.accumulate(t, axis)) + + def __str__ (self): + return "Masked version of " + str(self.f) +#.............................................................................. +class domained_binary_operation: + """Defines binary operations that have a domain, like divide. + +These are complicated so they are a separate class. +They have no reduce, outer or accumulate. + +:IVariables: + - `f` : function. + - `fillx` : Default filling value for first array*[0]*. + - `filly` : Default filling value for second array*[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, dbfunc, domain, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + self.f = dbfunc + self.domain = domain + self.fillx = fillx + self.filly = filly + self.__doc__ = getattr(dbfunc, "__doc__", str(dbfunc)) + self.__name__ = getattr(dbfunc, "__name__", str(dbfunc)) + ufunc_domain[dbfunc] = domain + ufunc_fills[dbfunc] = (fillx, filly) + + def __call__(self, a, b): + "Execute the call behavior." + ma = getmask(a) + mb = getmask(b) + d1 = filled(a, self.fillx) + d2 = filled(b, self.filly) + t = numeric.asarray(self.domain(d1, d2)) + if fromnumeric.sometrue(t, None): + d2 = numeric.where(t, self.filly, d2) + mb = mask_or(mb, t) + m = mask_or(ma, mb) + result = self.f(d1, d2) + if isinstance(result, MaskedArray): + return result.__class__(result, mask=m) + return masked_array(result, mask=m) + + def __str__ (self): + return "Masked version of " + str(self.f) + +#.............................................................................. +# Unary ufuncs +exp = masked_unary_operation(umath.exp) +conjugate = masked_unary_operation(umath.conjugate) +sin = masked_unary_operation(umath.sin) +cos = masked_unary_operation(umath.cos) +tan = masked_unary_operation(umath.tan) +arctan = masked_unary_operation(umath.arctan) +arcsinh = masked_unary_operation(umath.arcsinh) +sinh = masked_unary_operation(umath.sinh) +cosh = masked_unary_operation(umath.cosh) +tanh = masked_unary_operation(umath.tanh) +abs = absolute = masked_unary_operation(umath.absolute) +fabs = masked_unary_operation(umath.fabs) +negative = masked_unary_operation(umath.negative) +floor = masked_unary_operation(umath.floor) +ceil = masked_unary_operation(umath.ceil) +around = masked_unary_operation(fromnumeric.round_) +logical_not = masked_unary_operation(umath.logical_not) +# Domained unary ufuncs +sqrt = masked_unary_operation(umath.sqrt, 0.0, domain_greater_equal(0.0)) +log = masked_unary_operation(umath.log, 1.0, domain_greater(0.0)) +log10 = masked_unary_operation(umath.log10, 1.0, domain_greater(0.0)) +tan = masked_unary_operation(umath.tan, 0.0, domain_tan(1.e-35)) +arcsin = masked_unary_operation(umath.arcsin, 0.0, + domain_check_interval(-1.0, 1.0)) +arccos = masked_unary_operation(umath.arccos, 0.0, + domain_check_interval(-1.0, 1.0)) +arccosh = masked_unary_operation(umath.arccosh, 1.0, domain_greater_equal(1.0)) +arctanh = masked_unary_operation(umath.arctanh, 0.0, + domain_check_interval(-1.0+1e-15, 1.0-1e-15)) +# Binary ufuncs +add = masked_binary_operation(umath.add) +subtract = masked_binary_operation(umath.subtract) +multiply = masked_binary_operation(umath.multiply, 1, 1) +arctan2 = masked_binary_operation(umath.arctan2, 0.0, 1.0) +equal = masked_binary_operation(umath.equal) +equal.reduce = None +not_equal = masked_binary_operation(umath.not_equal) +not_equal.reduce = None +less_equal = masked_binary_operation(umath.less_equal) +less_equal.reduce = None +greater_equal = masked_binary_operation(umath.greater_equal) +greater_equal.reduce = None +less = masked_binary_operation(umath.less) +less.reduce = None +greater = masked_binary_operation(umath.greater) +greater.reduce = None +logical_and = masked_binary_operation(umath.logical_and) +alltrue = masked_binary_operation(umath.logical_and, 1, 1).reduce +logical_or = masked_binary_operation(umath.logical_or) +sometrue = logical_or.reduce +logical_xor = masked_binary_operation(umath.logical_xor) +bitwise_and = masked_binary_operation(umath.bitwise_and) +bitwise_or = masked_binary_operation(umath.bitwise_or) +bitwise_xor = masked_binary_operation(umath.bitwise_xor) +hypot = masked_binary_operation(umath.hypot) +# Domained binary ufuncs +divide = domained_binary_operation(umath.divide, domain_safe_divide(), 0, 1) +true_divide = domained_binary_operation(umath.true_divide, + domain_safe_divide(), 0, 1) +floor_divide = domained_binary_operation(umath.floor_divide, + domain_safe_divide(), 0, 1) +remainder = domained_binary_operation(umath.remainder, + domain_safe_divide(), 0, 1) +fmod = domained_binary_operation(umath.fmod, domain_safe_divide(), 0, 1) + + +#####-------------------------------------------------------------------------- +#---- --- Mask creation functions --- +#####-------------------------------------------------------------------------- +def getmask(a): + """Returns the mask of `a`, if any, or `nomask`. +Returns `nomask` if `a` is not a masked array. +To get an array for sure use getmaskarray.""" + if hasattr(a, "_mask"): + return a._mask + else: + return nomask + +def getmaskarray(a): + """Returns the mask of `a`, if any. +Otherwise, returns an array of `False`, with the same shape as `a`. + """ + m = getmask(a) + if m is nomask: + return make_mask_none(fromnumeric.shape(a)) + else: + return m + +def is_mask(m): + """Returns `True` if `m` is a legal mask. +Does not check contents, only type. + """ + try: + return m.dtype.type is MaskType + except AttributeError: + return False +# +def make_mask(m, copy=False, small_mask=True, flag=None): + """make_mask(m, copy=0, small_mask=0) +Returns `m` as a mask, creating a copy if necessary or requested. +The function can accept any sequence of integers or `nomask`. +Does not check that contents must be 0s and 1s. +If `small_mask=True`, returns `nomask` if `m` contains no true elements. + +:Parameters: + - `m` (ndarray) : Mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + - `small_mask` (boolean, *[False]*): Flattens mask to `nomask` if `m` is all false. + """ + if flag is not None: + warnings.warn("The flag 'flag' is now called 'small_mask'!", + DeprecationWarning) + small_mask = flag + if m is nomask: + return nomask + elif isinstance(m, ndarray): + m = filled(m, True) + if m.dtype.type is MaskType: + if copy: + result = numeric.array(m, dtype=MaskType, copy=copy) + else: + result = m + else: + result = numeric.array(m, dtype=MaskType) + else: + result = numeric.array(filled(m, True), dtype=MaskType) + # Bas les masques ! + if small_mask and not result.any(): + return nomask + else: + return result + +def make_mask_none(s): + "Returns a mask of shape `s`, filled with `False`." + result = numeric.zeros(s, dtype=MaskType) + return result + +def mask_or (m1, m2, copy=False, small_mask=True): + """Returns the combination of two masks `m1` and `m2`. +The masks are combined with the `logical_or` operator, treating `nomask` as false. +The result may equal m1 or m2 if the other is nomask. + +:Parameters: + - `m` (ndarray) : Mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + - `small_mask` (boolean, *[False]*): Flattens mask to `nomask` if `m` is all false. + """ + if m1 is nomask: + return make_mask(m2, copy=copy, small_mask=small_mask) + if m2 is nomask: + return make_mask(m1, copy=copy, small_mask=small_mask) + if m1 is m2 and is_mask(m1): + return m1 + return make_mask(umath.logical_or(m1, m2), copy=copy, small_mask=small_mask) + +#####-------------------------------------------------------------------------- +#--- --- Masking functions --- +#####-------------------------------------------------------------------------- +def masked_where(condition, x, copy=True): + """Returns `x` as an array masked where `condition` is true. +Masked values of `x` or `condition` are kept. + +:Parameters: + - `condition` (ndarray) : Masking condition. + - `x` (ndarray) : Array to mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + """ + cm = filled(condition,1) + if isinstance(x,MaskedArray): + m = mask_or(x._mask, cm) + return x.__class__(x._data, mask=m, copy=copy) + else: + return MaskedArray(fromnumeric.asarray(x), copy=copy, mask=cm) + +def masked_greater(x, value, copy=1): + "Shortcut to `masked_where`, with ``condition = (x > value)``." + return masked_where(greater(x, value), x, copy=copy) + +def masked_greater_equal(x, value, copy=1): + "Shortcut to `masked_where`, with ``condition = (x >= value)``." + return masked_where(greater_equal(x, value), x, copy=copy) + +def masked_less(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x < value)``." + return masked_where(less(x, value), x, copy=copy) + +def masked_less_equal(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x <= value)``." + return masked_where(less_equal(x, value), x, copy=copy) + +def masked_not_equal(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x != value)``." + return masked_where((x != value), x, copy=copy) + +# +def masked_equal(x, value, copy=True): + """Shortcut to `masked_where`, with ``condition = (x == value)``. +For floating point, consider `masked_values(x, value)` instead. + """ + return masked_where((x == value), x, copy=copy) +# d = filled(x, 0) +# c = umath.equal(d, value) +# m = mask_or(c, getmask(x)) +# return array(d, mask=m, copy=copy) + +def masked_inside(x, v1, v2, copy=True): + """Shortcut to `masked_where`, where `condition` is True for x inside +the interval `[v1,v2]` ``(v1 <= x <= v2)``. +The boundaries `v1` and `v2` can be given in either order. + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf >= v1) & (xf <= v2) + return masked_where(condition, x, copy=copy) + +def masked_outside(x, v1, v2, copy=True): + """Shortcut to `masked_where`, where `condition` is True for x outside +the interval `[v1,v2]` ``(x < v1)|(x > v2)``. +The boundaries `v1` and `v2` can be given in either order. + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf < v1) | (xf > v2) + return masked_where(condition, x, copy=copy) + +# +def masked_object(x, value, copy=True): + """Masks the array `x` where the data are exactly equal to `value`. +This function is suitable only for `object` arrays: for floating point, +please use `masked_values` instead. +The mask is set to `nomask` if posible. + +:parameter copy (Boolean, *[True]*): Returns a copy of `x` if true. """ + if isMaskedArray(x): + condition = umath.equal(x._data, value) + mask = x._mask + else: + condition = umath.equal(fromnumeric.asarray(x), value) + mask = nomask + mask = mask_or(mask, make_mask(condition, small_mask=True)) + return masked_array(x, mask=mask, copy=copy, fill_value=value) + +def masked_values(x, value, rtol=1.e-5, atol=1.e-8, copy=True): + """Masks the array `x` where the data are approximately equal to `value` +(that is, ``abs(x - value) <= atol+rtol*abs(value)``). +Suitable only for floating points. For integers, please use `masked_equal`. +The mask is set to `nomask` if posible. + +:Parameters: + - `rtol` (Float, *[1e-5]*): Tolerance parameter. + - `atol` (Float, *[1e-8]*): Tolerance parameter. + - `copy` (boolean, *[False]*) : Returns a copy of `x` if True. + """ + abs = umath.absolute + xnew = filled(x, value) + if issubclass(xnew.dtype.type, numeric.floating): + condition = umath.less_equal(abs(xnew-value), atol+rtol*abs(value)) + try: + mask = x._mask + except AttributeError: + mask = nomask + else: + condition = umath.equal(xnew, value) + mask = nomask + mask = mask_or(mask, make_mask(condition, small_mask=True)) + return masked_array(xnew, mask=mask, copy=copy, fill_value=value) + +#####-------------------------------------------------------------------------- +#---- --- Printing options --- +#####-------------------------------------------------------------------------- +class _MaskedPrintOption: + """Handles the string used to represent missing data in a masked array.""" + def __init__ (self, display): + "Creates the masked_print_option object." + self._display = display + self._enabled = True + + def display(self): + "Displays the string to print for masked values." + return self._display + + def set_display (self, s): + "Sets the string to print for masked values." + self._display = s + + def enabled(self): + "Is the use of the display value enabled?" + return self._enabled + + def enable(self, small_mask=1): + "Set the enabling small_mask to `small_mask`." + self._enabled = small_mask + + def __str__ (self): + return str(self._display) + + __repr__ = __str__ + +#if you single index into a masked location you get this object. +masked_print_option = _MaskedPrintOption('--') + +#####-------------------------------------------------------------------------- +#---- --- MaskedArray class --- +#####-------------------------------------------------------------------------- +class MaskedArray(numeric.ndarray): + """Arrays with possibly masked values. +Masked values of True exclude the corresponding element from any computation. + +Construction: + x = array(data, dtype=None, copy=True, order=False, + mask = nomask, fill_value=None, small_mask=True) + +If copy=False, every effort is made not to copy the data: +If `data` is a MaskedArray, and argument mask=nomask, then the candidate data +is `data._data` and the mask used is `data._mask`. +If `data` is a numeric array, it is used as the candidate raw data. +If `dtype` is not None and is different from data.dtype.char then a data copy is required. +Otherwise, the candidate is used. + +If a data copy is required, the raw (unmasked) data stored is the result of: +numeric.array(data, dtype=dtype.char, copy=copy) + +If `mask` is `nomask` there are no masked values. +Otherwise mask must be convertible to an array of booleans with the same shape as x. +If `small_mask` is True, a mask consisting of zeros (False) only is compressed to `nomask`. +Otherwise, the mask is not compressed. + +fill_value is used to fill in masked values when necessary, such as when +printing and in method/function filled(). +The fill_value is not used for computation within this module. + """ + __array_priority__ = 10.1 + _defaultmask = nomask + _defaulthardmask = False + #TODO: There some reorganization to do round here + def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, fill_value=None, + keep_mask=True, small_mask=True, hard_mask=False, flag=None, + **options): + """array(data, dtype=None, copy=True, mask=nomask, fill_value=None) + +If `data` is already a ndarray, its dtype becomes the default value of dtype. + """ + if flag is not None: + warnings.warn("The flag 'flag' is now called 'small_mask'!", + DeprecationWarning) + small_mask = flag + # 1. Argument is MA ........... + if isinstance(data, MaskedArray) or\ + (hasattr(data,"_mask") and hasattr(data,"_data")) : + if data is masked: + return masked.view(cls) + if keep_mask: + if mask is nomask: + if copy: + cls._defaultmask = data._mask.copy() + else: + cls._defaultmask = data._mask + else: + cls._defaultmask = mask_or(data._mask, mask, + copy=copy, small_mask=small_mask) + else: + cls._defaultmask = make_mask(mask, copy=copy, small_mask=small_mask) + # Update fille_value + if fill_value is None: + cls._fill_value = data._fill_value + else: + cls._fill_value = fill_value + cls._defaulthardmask = hard_mask + _data = data._data + if dtype is not None and _data.dtype != numeric.dtype(dtype): + return _data.astype(dtype).view(cls) + elif copy: + return _data.copy().view(cls) + else: + return _data.view(cls) + # 2. Argument is not MA ....... + if isinstance(data, ndarray): + if dtype is not None and data.dtype != numeric.dtype(dtype): + _data = data.astype(dtype) + elif copy: + _data = data.copy() + else: + _data = data + else: + _data = numeric.array(data, dtype=dtype, copy=copy) +# try: +# _data = numeric.array(data, dtype=dtype, copy=copy) +# except TypeError: +# _data = empty(len(data), dtype=dtype) +# for (k,v) in enumerate(data): +# _data[k] = v +# if mask is nomask: +# cls.__defaultmask = getmask(_data) +# return _data.view(cls) + # Define mask ................. + mask = make_mask(mask, copy=copy, small_mask=small_mask) + #....Check shapes compatibility + if mask is not nomask: + (nd, nm) = (_data.size, mask.size) + if (nm != nd): + # We need to resize w/ a function, in case _data is only a reference + if nm == 1: + mask = fromnumeric.resize(mask, _data.shape) + elif nd == 1: + _data = fromnumeric.resize(_data, mask.shape) + else: + msg = "Mask and data not compatible: data size is %i, "+\ + "mask size is %i." + raise MAError, msg % (nd, nm) + elif (mask.shape != _data.shape): + mask = mask.reshape(_data.shape) +# mask = _data.shape + #.... + cls._fill_value = fill_value + cls._defaulthardmask = hard_mask + cls._defaultmask = mask + cls._defaultoptions = options + return numeric.asanyarray(_data).view(cls) + #.................................. + def __array_wrap__(self, obj, context=None): + """Special hook for ufuncs. +Wraps the numpy array and sets the mask according to context. + """ +# mclass = self.__class__ + #.......... + if context is None: +# return mclass(obj, mask=self._mask, copy=False) + return MaskedArray(obj, mask=self._mask, copy=False, + dtype=obj.dtype, + fill_value=self.fill_value, ) + #.......... + (func, args) = context[:2] + m = reduce(mask_or, [getmask(arg) for arg in args]) + # Get domain mask + domain = ufunc_domain.get(func, None) + if domain is not None: + m = mask_or(m, domain(*[getattr(arg, '_data', arg) for arg in args])) + # Update mask + if m is not nomask: + try: + dshape = obj.shape + except AttributeError: + pass + else: + if m.shape != dshape: + m = reduce(mask_or, [getmaskarray(arg) for arg in args]) +# return mclass(obj, copy=False, mask=m) + return MaskedArray(obj, copy=False, mask=m,) +# dtype=obj.dtype, fill_value=self._fill_value) + #........................ + #TODO: there should be some reorganization to do round here. + def __array_finalize__(self,obj): + """Finalizes the masked array. + """ + # + if isinstance(obj, MaskedArray): + # We came here from a MaskedArray + self._data = obj._data + self._mask = obj._mask + self._hardmask = obj._hardmask + self._fill_value = obj._fill_value + self.options = obj.options + else: + # We came here from a .view() + if hasattr(obj,'_data') and hasattr(obj, '_mask'): + # obj is an old masked array or a smart record + self._data = obj._data + self._mask = obj._mask + else: + # obj is anything but... + self._data = obj + self._mask = self._defaultmask + # Set the instance default + self._hardmask = self._defaulthardmask + self.fill_value = self._fill_value + self.options = self._defaultoptions + # Reset the class default + MaskedArray._defaultmask = nomask + MaskedArray._defaulthardmask = False + MaskedArray._fill_value = None +# # + return + #............................................ + def __getitem__(self, indx): + """x.__getitem__(y) <==> x[y] +Returns the item described by i. Not a copy as in previous versions. + """ + if getmask(indx) is not nomask: + msg = "Masked arrays must be filled before they can be used as indices!" + raise IndexError, msg + dout = self._data[indx] + m = self._mask + scalardout = (len(numeric.shape(dout))==0) + # + if m is nomask: + if scalardout: + return dout + else: + return self.__class__(dout, mask=nomask, keep_mask=True, + fill_value=self._fill_value, + **self.options) + #.... + mi = m[indx] + if mi.size == 1: + if mi: + return masked + return dout + else: + return self.__class__(dout, mask=mi, fill_value=self._fill_value, + **self.options) + #........................ + def __setitem__(self, index, value): + """x.__setitem__(i, y) <==> x[i]=y +Sets item described by index. If value is masked, masks those locations. + """ + if self is masked: + raise MAError, 'Cannot alter the masked element.' + if getmask(index) is not nomask: + msg = "Masked arrays must be filled before they can be used as indices!" + raise IndexError, msg + #.... + (d, m) = (self._data, self._mask) + #.... + if value is masked: + if m is nomask: + m = make_mask_none(d.shape) + else: + m = m.copy() + m[index] = True + self._mask = m + return + #.... + if m is nomask: + d[index] = filled(value) + valmask = getmask(value) + if valmask is not nomask: + m = make_mask_none(d.shape) + m[index] = valmask + elif not self._hardmask: + d[index] = filled(value) + valmask = getmask(value) + m = m.copy() + if valmask is nomask: + m[index] = False + else: + m[index] = valmask + elif hasattr(index, 'dtype') and (index.dtype==bool_): + index *= ~m + d[index] = filled(value) +# elif isinstance(index, int): + else: + mindx = m[index] + value = masked_array(value, mask=mindx, keep_mask=True) + valdata = filled(value) + valmask = getmask(value) + if valmask is nomask: + d[index] = valdata + elif valmask.size > 1: + dindx = d[index] + numeric.putmask(dindx, ~valmask, valdata) + d[index] = dindx + numeric.putmask(mindx, valmask, True) + m[index] = mindx + #..... + if not m.any(): + self._mask = nomask + else: + self._mask = m + #............................................ + def __getslice__(self, i, j): + """x.__getslice__(i, j) <==> x[i:j] +Returns the slice described by i, j. +The use of negative indices is not supported.""" + m = self._mask + dout = self._data[i:j] + if m is nomask: + return self.__class__(dout, fill_value=self._fill_value, + **self.options) + else: + return self.__class__(dout, mask=m[i:j], fill_value=self._fill_value, + **self.options) + #........................ + def __setslice__(self, i, j, value): + """x.__setslice__(i, j, value) <==> x[i:j]=value +Sets a slice i:j to `value`. +If `value` is masked, masks those locations.""" + if self is masked: + #TODO: Well, maybe we could/should + raise MAError, "Cannot alter the 'masked' object." + #.... + (d, m) = (self._data, self._mask) + #.... + if value is masked: + if m is nomask: + m = make_mask_none(d.shape) + m[i:j] = True + self._mask = m + return + #.... + if m is nomask: + valmask = getmask(value) + valdata = filled(value) + d[i:j] = valdata + if valmask is not nomask: + m = make_mask_none(d.shape) + m[i:j] = valmask + elif not self._hardmask: + valmask = getmask(value) + valdata = filled(value) + d[i:j] = valdata + if valmask is nomask: + m[i:j] = False + else: + m[i:j] = valmask + else: + mindx = m[i:j] + value = masked_array(value, mask=mindx, keep_mask=True) + valmask = value._mask + if valmask is nomask: + d[i:j][~mindx] = filled(value) + elif valmask.size > 1: + d[i:j][~mindx] = value[~valmask] + m[i:j][valmask] = True + #..... + if not m.any(): + self._mask = nomask + else: + self._mask = m + #............................................ + # If we don't want to crash the performance, we better leave __getattribute__ alone... +# def __getattribute__(self, name): +# """x.__getattribute__('name') = x.name +#Returns the chosen attribute. +#If the attribute cannot be directly accessed, checks the _data section. +# """ +# try: +# return ndarray.__getattribute__(self, name) +# except AttributeError: +# pass +# try: +# return self._data.__getattribute__(name) +# except AttributeError: +# raise AttributeError + #............................................ + def __str__(self): + """x.__str__() <==> str(x) +Calculates the string representation, using masked for fill if it is enabled. +Otherwise, fills with fill value. + """ + if masked_print_option.enabled(): + f = masked_print_option + if self is masked: + return str(f) + m = self._mask + if m is nomask: + res = self._data + else: + if m.shape == () and m: + return str(f) + # convert to object array to make filled work +#CHECK: the two lines below seem more robust than the self._data.astype +# res = numeric.empty(self._data.shape, object_) +# numeric.putmask(res,~m,self._data) + res = self._data.astype("|O8") + res[self._mask] = f + else: + res = self.filled(self.fill_value) + return str(res) + + def __repr__(self): + """x.__repr__() <==> repr(x) +Calculates the repr representation, using masked for fill if it is enabled. +Otherwise fill with fill value. + """ + with_mask = """\ +masked_%(name)s(data = + %(data)s, + mask = + %(mask)s, + fill_value=%(fill)s) +""" + with_mask1 = """\ +masked_%(name)s(data = %(data)s, + mask = %(mask)s, + fill_value=%(fill)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), + } + #............................................ + def __abs__(self): + """x.__abs__() <==> abs(x) +Returns a masked array of the current subclass, with the new `_data` +the absolute of the inital `_data`. + """ + return self.__class__(self._data.__abs__(), mask=self._mask, + fill_value = self._fill_value, **self.options) + # + def __neg__(self): + """x.__abs__() <==> neg(x) +Returns a masked array of the current subclass, with the new `_data` +the negative of the inital `_data`.""" + try: + return self.__class__(self._data.__neg__(), mask=self._mask, + fill_value = self._fill_value, **self.options) + except MAError: + return negative(self) + # + def __iadd__(self, other): + "Adds other to self in place." + f = convert_typecode(filled(other, 0), self._data.dtype.char) + m = getmask(other) + self._data += f + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + # + def __isub__(self, other): + "Subtracts other from self in place." + f = convert_typecode(filled(other, 0), self._data.dtype.char) + m = getmask(other) + self._data -= f + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + # + def __imul__(self, other): + "Multiplies self by other in place." + f = convert_typecode(filled(other, 1), self._data.dtype.char) + m = getmask(other) + self._data *= f + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + # + def __idiv__(self, other): + "Divides self by other in place." + f = convert_typecode(filled(other, 0), self._data.dtype.char) + mo = getmask(other) + result = divide(self, masked_array(f, mask=mo)) + self._data = result._data + dm = result._mask + if dm is not self._mask: + self._mask = dm + return self + +# # +# def __eq__(self, other): +# return equal(self,other) +# +# def __ne__(self, other): +# return not_equal(self,other) +# +# def __lt__(self, other): +# return less(self,other) +# +# def __le__(self, other): +# return less_equal(self,other) +# +# def __gt__(self, other): +# return greater(self,other) +# +# def __ge__(self, other): +# return greater_equal(self,other) + + #............................................ + def __float__(self): + "Converts self to float." + if self._mask is not nomask: + warnings.warn("Warning: converting a masked element to nan.") + return numpy.nan + #raise MAError, 'Cannot convert masked element to a Python float.' + return float(self._data.item()) + + def __int__(self): + "Converts self to int." + if self._mask is not nomask: + raise MAError, 'Cannot convert masked element to a Python int.' + return int(self._data.item()) + + @property + def dtype(self): + """returns the data type of `_data`.""" + return self._data.dtype + + def astype (self, tc): + """Returns self as an array of given type. +Subclassing is preserved.""" + if tc == self._data.dtype: + return self + try: + return self.__class__(self, mask=self._mask, dtype=tc, copy=True, + **self.options) + except: +# d = self._data.astype(tc) + return self.__class__(self._data.astype(tc), mask=self._mask, + dtype=tc, **self.options) +# +# + #............................................ + def harden_mask(self): + "Forces the mask to hard" + self._hardmask = True + def soften_mask(self): + "Forces the mask to soft" + self._hardmask = False + #............................................ + #TODO: FIX THAT: THAT"S NOT A REAL FLATITER + def _get_flat(self): + """Calculates the flat value. + """ + if self._mask is nomask: + return masked_array(self._data.ravel(), mask=nomask, copy=False, + fill_value = self._fill_value, + **self.options) + else: + return masked_array(self._data.ravel(), mask=self._mask.ravel(), + copy=False, fill_value = self._fill_value, + **self.options) + # + def _set_flat (self, value): + "x.flat = value" + y = self.ravel() + y[:] = value + # + flat = property(fget=_get_flat, fset=_set_flat, doc="Flat version") + # + #............................................ + def _get_real(self): + "Returns the real part of a complex array." + return self.__class__(self._data.real, mask=self.mask, + fill_value = self._fill_value, **self.options) + def _set_real (self, value): + "Sets the real part of a complex array to `value`." + y = self.real + y[...] = value + + real = property(fget=_get_real, fset=_set_real, doc="Get it real!") + + def _get_imaginary(self): + "Returns the imaginary part of a complex array." + return self.__class__(self._data.imag, mask=self.mask, + fill_value = self._fill_value, **self.options) + + def _set_imaginary (self, value): + "Sets the imaginary part of a complex array to `value`." + y = self.imaginary + y[...] = value + + imag = property(fget=_get_imaginary, fset=_set_imaginary, + doc="Imaginary part.") + imaginary = imag + #............................................ + def _get_mask(self): + """Returns the current mask.""" + return self._mask + def _set_mask(self, mask): + """Sets the mask to `mask`.""" + mask = make_mask(mask, copy=False, small_mask=True) + if mask is not nomask: + if mask.size != self._data.size: + raise ValueError, "Inconsistent shape between data and mask!" + if mask.shape != self._data.shape: + mask.shape = self._data.shape + self._mask = mask + else: + self._mask = nomask + mask = property(fget=_get_mask, fset=_set_mask, doc="Mask") + #............................................ + def get_fill_value(self): + "Returns the filling value." + return self._fill_value + + def set_fill_value(self, value=None): + """Sets the filling value to `value`. +If None, uses the default, based on the data type.""" + if value is None: + value = default_fill_value(self._data) + self._fill_value = value + + fill_value = property(fget=get_fill_value, fset=set_fill_value, + doc="Filling value") + + def filled(self, fill_value=None): + """Returns an array of the same class as `_data`, + with masked values filled with `fill_value`. +Subclassing is preserved. + +If `fill_value` is None, uses self.fill_value. + """ + d = self._data + m = self._mask + if m is nomask: + return d + # + if fill_value is None: + value = self.fill_value + else: + value = fill_value + # + if self is masked_singleton: + result = numeric.asanyarray(value) + else: + result = d.copy() + try: + result[m] = value + except (TypeError, AttributeError): + value = numeric.array(value, dtype=object) + d = d.astype(object) + result = fromnumeric.choose(m, (d, value)) + except IndexError: + #ok, if scalar + if d.shape: + raise + elif m: + result = numeric.array(value, dtype=d.dtype) + else: + result = d + return result + + def compressed(self): + "A 1-D array of all the non-masked data." + d = self._data.ravel() + if self._mask is nomask: + return d + else: + return d[~self._mask.ravel()] + #............................................ + def count(self, axis=None): + """Counts the non-masked elements of the array along a given axis, +and returns a masked array where the mask is True where all data are masked. +If `axis` is None, counts all the non-masked elements, and returns either a +scalar or the masked singleton.""" + m = self._mask + s = self._data.shape + ls = len(s) + if m is nomask: + if ls == 0: + return 1 + if ls == 1: + return s[0] + if axis is None: + return self._data.size + else: + n = s[axis] + t = list(s) + del t[axis] + return numeric.ones(t) * n + n1 = fromnumeric.size(m, axis) + n2 = m.astype(int_).sum(axis) + if axis is None: + return (n1-n2) + else: + return masked_array(n1 - n2) + #............................................ + def _get_shape(self): + "Returns the current shape." + return self._data.shape + # + def _set_shape (self, newshape): + "Sets the array's shape." + self._data.shape = newshape + if self._mask is not nomask: + #self._mask = self._mask.copy() + self._mask.shape = newshape + # + shape = property(fget=_get_shape, fset=_set_shape, + doc="Shape of the array, as a tuple.") + # + def _get_size(self): + "Returns the current size." + return self._data.size + size = property(fget=_get_size, + doc="Size (number of elements) of the array.") + # + def _get_ndim(self): + "Returns the number of dimensions." + return self._data.ndim + ndim = property(fget=_get_ndim, + doc="Number of dimensions of the array.") + # + def reshape (self, *s): + """Reshapes the array to shape s. +Returns a new masked array. +If you want to modify the shape in place, please use `a.shape = s`""" + if self._mask is not nomask: + return self.__class__(self._data.reshape(*s), + mask=self._mask.reshape(*s), + fill_value=self.fill_value, **self.options) + else: + return self.__class__(self._data.reshape(*s), + fill_value=self.fill_value, **self.options) + # + def repeat(self, repeats, axis=None): + """Repeat elements of `a` `repeats` times along `axis`. +`repeats` is a sequence of length `a.shape[axis]` telling how many times +each element should be repeated. +The mask is repeated accordingly. + """ + f = self.filled() + if isinstance(repeats, types.IntType): + if axis is None: + num = f.size + else: + num = f.shape[axis] + repeats = tuple([repeats]*num) + + m = self._mask + if m is not nomask: + m = fromnumeric.repeat(m, repeats, axis) + d = fromnumeric.repeat(f, repeats, axis) + return self.__class__(d, mask=m, fill_value=self.fill_value, + **self.options) + # + def resize(self, newshape, refcheck=True, order=False): + """Attempts to modify size and shape of self inplace. + The array must own its own memory and not be referenced by other arrays. + Returns None. + """ + try: + self._data.resize(newshape,) + if self.mask is not nomask: + self._mask.resize(newshape,) + except ValueError: + msg = "Cannot resize an array that has been referenced or "+\ + "is referencing another array in this way.\n"+\ + "Use the resize function." + raise ValueError, msg + return None + # + def flatten(self): + """Flattens the array in place. + """ + flatsize = self.size + self._data.resize((flatsize,)) + if self.mask is not nomask: + self._mask.resize((flatsize,)) + return self + + # + def put(self, indices, values, mode='raise'): + """Sets storage-indexed locations to corresponding values. +a.put(values, indices, mode) sets a.flat[n] = values[n] for each n in indices. +`values` can be scalar or an array shorter than indices, and it will be repeat, +if necessary. +If `values` has some masked values, the initial mask is updated in consequence, +else the corresponding values are unmasked. + """ + #TODO: Check that + (d, m) = (self._data, self._mask) + ind = filled(indices) + v = filled(values) + d.put(ind, v, mode=mode) + if m is not nomask: + if getmask(values) is not nomask: + m.put(ind, values._mask, mode=mode) + else: + m.put(ind, False, mode=mode) + self._mask = make_mask(m, copy=False, small_mask=True) + #............................................ + def ids (self): + """Return the ids of the data and mask areas.""" + return (id(self._data), id(self._mask)) + #............................................ + def all(self, axis=None): + """a.all(axis) returns True if all entries along the axis are True. + Returns False otherwise. If axis is None, uses the flatten array. + Masked data are considered as True during computation. + Outputs a masked array, where the mask is True if all data are masked along the axis. + """ + d = filled(self, True).all(axis) + m = self._mask.all(axis) + return self.__class__(d, mask=m, dtype=bool_, + fill_value=self._fill_value, **self.options) + def any(self, axis=None): + """a.any(axis) returns True if some or all entries along the axis are True. + Returns False otherwise. If axis is None, uses the flatten array. + Masked data are considered as False during computation. + Outputs a masked array, where the mask is True if all data are masked along the axis. + """ + d = filled(self, False).any(axis) + m = self._mask.all(axis) + return self.__class__(d, mask=m, dtype=bool_, + fill_value=self._fill_value, **self.options) + def nonzero(self): + """a.nonzero() returns a tuple of arrays + + Returns a tuple of arrays, one for each dimension of a, + containing the indices of the non-zero elements in that + dimension. The corresponding non-zero values can be obtained + with + a[a.nonzero()]. + + To group the indices by element, rather than dimension, use + transpose(a.nonzero()) + instead. The result of this is always a 2d array, with a row for + each non-zero element.""" + return numeric.asarray(self.filled(0)).nonzero() + #............................................ + def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): + """a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) +Returns the sum along the offset diagonal of the array's indicated `axis1` and `axis2`. + """ + #TODO: What are we doing with `out`? + (d,m) = (self._data, self._mask) + if m is nomask: + return d.trace(offset=offset, axis1=axis1, axis2=axis2, + out=out).astype(dtype) + else: + D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2, + ).astype(dtype) + return D.sum(axis=None) + #............................................ + def sum(self, axis=None, dtype=None): + """a.sum(axis=None, dtype=None) +Sums the array `a` over the given axis `axis`. +Masked values are set to 0. +If `axis` is None, applies to a flattened version of the array. + """ + if self._mask is nomask: +# if axis is None: +# return self._data.sum(None, dtype=dtype) + return self.__class__(self._data.sum(axis, dtype=dtype), + mask=nomask, fill_value=self.fill_value, + **self.options) + else: +# if axis is None: +# return self.filled(0).sum(None, dtype=dtype) + return self.__class__(self.filled(0).sum(axis, dtype=dtype), + mask=self._mask.all(axis), + fill_value=self.fill_value, **self.options) + + def cumsum(self, axis=None, dtype=None): + """a.cumprod(axis=None, dtype=None) +Returns the cumulative sum of the elements of array `a` along the given axis `axis`. +Masked values are set to 0. +If `axis` is None, applies to a flattened version of the array. + """ + if self._mask is nomask: +# if axis is None: +# return self._data.cumsum(None, dtype=dtype) + return self.__class__(self._data.cumsum(axis=axis, dtype=dtype), + fill_value=self.fill_value, **self.options) + else: +# if axis is None: +# return self.filled(0).cumsum(None, dtype=dtype) + return self.__class__(self.filled(0).cumsum(axis=axis, dtype=dtype), + mask=self._mask, fill_value=self.fill_value, + **self.options) + + def prod(self, axis=None, dtype=None): + """a.prod(axis=None, dtype=None) +Returns the product of the elements of array `a` along the given axis `axis`. +Masked elements are set to 1. +If `axis` is None, applies to a flattened version of the array. + """ + if self._mask is nomask: +# if axis is None: +# return self._data.prod(None, dtype=dtype) + return self.__class__(self._data.prod(axis, dtype=dtype), + mask=nomask, fill_value=self.fill_value, + **self.options) +# return self.__class__(self._data.prod(axis=axis, dtype=dtype)) + else: +# if axis is None: +# return self.filled(1).prod(None, dtype=dtype) + return self.__class__(self.filled(1).prod(axis=axis, dtype=dtype), + mask=self._mask.all(axis), + fill_value=self.fill_value, + **self.options) + product = prod + + def cumprod(self, axis=None, dtype=None): + """a.cumprod(axis=None, dtype=None) +Returns the cumulative product of ethe lements of array `a` along the given axis `axis`. +Masked values are set to 1. +If `axis` is None, applies to a flattened version of the array. + """ + if self._mask is nomask: +# if axis is None: +# return self._data.cumprod(None, dtype=dtype) + return self.__class__(self._data.cumprod(axis=axis, dtype=dtype), + mask=nomask, fill_value=self.fill_value, + **self.options) + else: +# if axis is None: +# return self.filled(1).cumprod(None, dtype=dtype) + return self.__class__(self.filled(1).cumprod(axis=axis, dtype=dtype), + mask=self._mask, + fill_value=self.fill_value, **self.options) + + def mean(self, axis=None, dtype=None): + """a.mean(axis=None, dtype=None) + + Averages the array over the given axis. If the axis is None, + averages over all dimensions of the array. Equivalent to + + a.sum(axis, dtype) / size(a, axis). + + The optional dtype argument is the data type for intermediate + calculations in the sum. + + Returns a masked array, of the same class as a. + """ + if self._mask is nomask: +# if axis is None: +# return self._data.mean(axis=None, dtype=dtype) + return self.__class__(self._data.mean(axis=axis, dtype=dtype), + mask=nomask, fill_value=self.fill_value, + **self.options) + else: + dsum = fromnumeric.sum(self.filled(0), axis=axis, dtype=dtype) + cnt = self.count(axis=axis) + mask = self._mask.all(axis) + if axis is None and mask: + return masked + return self.__class__(dsum*1./cnt, mask=mask, + fill_value=self.fill_value, **self.options) + + def anom(self, axis=None, dtype=None): + """a.anom(axis=None, dtype=None) + Returns the anomalies, or deviation from the average. + """ + m = self.mean(axis, dtype) + if not axis: + return (self - m) + else: + return (self - expand_dims(m,axis)) + + def var(self, axis=None, dtype=None): + """a.var(axis=None, dtype=None) +Returns the variance, a measure of the spread of a distribution. + +The variance is the average of the squared deviations from the mean, +i.e. var = mean((x - x.mean())**2). + """ + if self._mask is nomask: +# if axis is None: +# return self._data.var(axis=None, dtype=dtype) + return self.__class__(self._data.var(axis=axis, dtype=dtype), + mask=nomask, + fill_value=self.fill_value, **self.options) + else: + cnt = self.count(axis=axis) + danom = self.anom(axis=axis, dtype=dtype) + danom *= danom + dvar = danom.sum(axis) / cnt +# dvar /= cnt + if axis is None: + return dvar + return self.__class__(dvar, + mask=mask_or(self._mask.all(axis), (cnt==1)), + fill_value=self.fill_value, **self.options) + + def std(self, axis=None, dtype=None): + """a.std(axis=None, dtype=None) +Returns the standard deviation, a measure of the spread of a distribution. + +The standard deviation is the square root of the average of the squared +deviations from the mean, i.e. std = sqrt(mean((x - x.mean())**2)). + """ + dvar = self.var(axis,dtype) + if axis is None: + if dvar is masked: + return masked + else: + # Should we use umath.sqrt instead ? + return sqrt(dvar) + return self.__class__(sqrt(dvar._data), mask=dvar._mask, + dtype = self.dtype, + fill_value=self.fill_value, **self.options) + #............................................ + def argsort(self, axis=None, fill_value=None, kind='quicksort', + order=None): + """Returns an array of indices that sort 'a' along the specified axis. + Masked values are filled beforehand to `fill_value`. + If `fill_value` is None, uses the default for the data type. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `kind` : String *['quicksort']* + Sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + + Returns: array of indices that sort 'a' along the specified axis. + + This method executes an indirect sort along the given axis using the + algorithm specified by the kind keyword. It returns an array of indices of + the same shape as 'a' that index data along the given axis in sorted order. + + The various sorts are characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order. The three + available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is not + along the last axis. Consequently, sorts along the last axis are faster and use + less space than sorts along other axis. + """ + if fill_value is None: + fill_value = default_fill_value(self._data) + d = self.filled(fill_value) + if axis is None: + return d.argsort(kind=kind, order=order) + return d.argsort(axis, kind=kind, order=order) + + def argmin(self, axis=None, fill_value=None): + """Returns the array of indices for the minimum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = default_fill_value(self._data) + d = self.filled(fill_value) + if axis is None: + return d.argmin() + return d.argmin(axis) + + def argmax(self, axis=None, fill_value=None): + """Returns the array of indices for the maximum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = default_fill_value(self._data) + try: + fill_value = - fill_value + except: + pass + d = self.filled(fill_value) + if axis is None: + return d.argmax() + return d.argmax(axis) + + def sort(self, axis=-1, kind='quicksort', order=None, endwith=True): + """ + Sort a along the given axis. + + Keyword arguments: + + axis -- axis to be sorted (default -1) + kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. + order -- If a has fields defined, then the order keyword can be the + field name to sort on or a list (or tuple) of field names + to indicate the order that fields should be used to define + the sort. + endwith--Boolean flag indicating whether missing values (if any) should + be forced in the upper indices (at the end of the array) or + lower indices (at the beginning). + + Returns: None. + + This method sorts 'a' in place along the given axis using the algorithm + specified by the kind keyword. + + The various sorts may characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order and is most + useful when used with argsort where the key might differ from the items + being sorted. The three available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is + not along the last axis. Consequently, sorts along the last axis are faster + and use less space than sorts along other axis. + + """ + + if endwith: + filler = minimum_fill_value(self.dtype) + else: + filler = maximum_fill_value(self.dtype) + indx = self.filled(filler).argsort(axis=axis,kind=kind,order=order) + self._data = self._data[indx] + m = self._mask + if m is not nomask: + self._mask = m[indx] + return + #............................................ + # Backwards Compatibility. Heck... + @property + def data(self): + """Returns the `_data` part of the MaskedArray. +You should really use `_data` instead...""" + return self._data + def raw_data(self): + """Returns the `_data` part of the MaskedArray. +You should really use `_data` instead...""" + return self._data + +##.............................................................................. + + + +#class _arithmethods: +# """Defines a wrapper for arithmetic methods. +#Instead of directly calling a ufunc, the corresponding method of the `array._data` +#object is called instead. +# """ +# def __init__ (self, methodname, fill_self=0, fill_other=0, domain=None): +# """ +#:Parameters: +# - `methodname` (String) : Method name. +# - `fill_self` (Float *[0]*) : Fill value for the instance. +# - `fill_other` (Float *[0]*) : Fill value for the target. +# - `domain` (Domain object *[None]*) : Domain of non-validity. +# """ +# self.methodname = methodname +# self.fill_self = fill_self +# self.fill_other = fill_other +# self.domain = domain +# # +# def __call__ (self, instance, other, *args): +# "Execute the call behavior." +# m_self = instance._mask +# m_other = getmask(other) +# base = filled(instance,self.fill_self) +# target = filled(other, self.fill_other) +# if self.domain is not None: +# # We need to force the domain to a ndarray only. +# if self.fill_other > self.fill_self: +# domain = self.domain(base, target) +# else: +# domain = self.domain(target, base) +# if domain.any(): +# #If `other` is a subclass of ndarray, `filled` must have the +# # same subclass, else we'll lose some info. +# #The easiest then is to fill `target` instead of creating +# # a pure ndarray. +# #Oh, and we better make a copy! +# if isinstance(other, ndarray): +# if target is other: +# # We don't want to modify other: let's copy target, then +# target = target.copy() +# target[:] = numeric.where(fromnumeric.asarray(domain), +# self.fill_other, target) +# else: +# target = numeric.where(fromnumeric.asarray(domain), +# self.fill_other, target) +# m_other = mask_or(m_other, domain) +# m = mask_or(m_self, m_other) +# method = getattr(base, self.methodname) +# return instance.__class__(method(target, *args), mask=m) +# # +# def patch(self): +# """Applies the method `func` from class `method` to MaskedArray""" +# return types.MethodType(self,None,MaskedArray) +#.............................................................................. +class _arithmethods(object): + """Defines a wrapper for arithmetic methods. +Instead of directly calling a ufunc, the corresponding method of the `array._data` +object is called instead. + """ + def __init__ (self, methodname, fill_self=0, fill_other=0, domain=None): + """ +:Parameters: + - `methodname` (String) : Method name. + - `fill_self` (Float *[0]*) : Fill value for the instance. + - `fill_other` (Float *[0]*) : Fill value for the target. + - `domain` (Domain object *[None]*) : Domain of non-validity. + """ + self.methodname = methodname + self.fill_self = fill_self + self.fill_other = fill_other + self.domain = domain + self.obj = None + self.__doc__ = self.getdoc() + # + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + try: + return getattr(MaskedArray, self.methodname).__doc__ + except: + return getattr(numpy, self.methodname).__doc__ + # + def __get__(self, obj, objtype=None): + self.obj = obj + return self + # + def __call__ (self, other, *args): + "Execute the call behavior." + instance = self.obj + m_self = instance._mask + m_other = getmask(other) + base = filled(instance,self.fill_self) + target = filled(other, self.fill_other) + if self.domain is not None: + # We need to force the domain to a ndarray only. + if self.fill_other > self.fill_self: + domain = self.domain(base, target) + else: + domain = self.domain(target, base) + if domain.any(): + #If `other` is a subclass of ndarray, `filled` must have the + # same subclass, else we'll lose some info. + #The easiest then is to fill `target` instead of creating + # a pure ndarray. + #Oh, and we better make a copy! + if isinstance(other, ndarray): + if target is other or target is base: + # We don't want to modify other: let's copy target, then + # Same if target us base, instead... + target = target.copy() + target[:] = numeric.where(fromnumeric.asarray(domain), + self.fill_other, target) + else: + target = numeric.where(fromnumeric.asarray(domain), + self.fill_other, target) + m_other = mask_or(m_other, domain) + m = mask_or(m_self, m_other) + method = getattr(base, self.methodname) + return instance.__class__(method(target, *args), mask=m, + fill_value=instance.fill_value, + **instance.options) +#...................................... +class _compamethods(object): + """Defines comparison methods (eq, ge, gt...). +Instead of calling a ufunc, the method of the masked object is called. + """ + def __init__ (self, methodname, fill_self=0, fill_other=0): + """ +:Parameters: + - `methodname` (String) : Method name. + - `fill_self` (Float *[0]*) : Fill value for the instance. + - `fill_other` (Float *[0]*) : Fill value for the target. + - `domain` (Domain object *[None]*) : Domain of non-validity. + """ + self.methodname = methodname + self.fill_self = fill_self + self.fill_other = fill_other + self.obj = None + self.__doc__ = self.getdoc() + # + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + try: + return getattr(MaskedArray, self.methodname).__doc__ + except: + return getattr(numpy, self.methodname).__doc__ + # + def __get__(self, obj, objtype=None): + self.obj = obj + return self + # + def __call__ (self, other, *args): + "Execute the call behavior." + instance = self.obj + m = mask_or(instance._mask, getmask(other), small_mask=False) + base = instance.filled(self.fill_self) + target = filled(other, self.fill_other) + method = getattr(base, self.methodname) + return instance.__class__(method(target, *args), mask=m, + **instance.options) +#.......................................................... +MaskedArray.__add__ = _arithmethods('__add__') +MaskedArray.__radd__ = _arithmethods('__add__') +MaskedArray.__sub__ = _arithmethods('__sub__') +MaskedArray.__rsub__ = _arithmethods('__rsub__') +MaskedArray.__pow__ = _arithmethods('__pow__') +MaskedArray.__mul__ = _arithmethods('__mul__', 1, 1) +MaskedArray.__rmul__ = _arithmethods('__mul__', 1, 1) +MaskedArray.__div__ = _arithmethods('__div__', 0, 1, + domain_safe_divide()) +MaskedArray.__rdiv__ = _arithmethods('__rdiv__', 1, 0, + domain_safe_divide()) +MaskedArray.__truediv__ = _arithmethods('__truediv__', 0, 1, + domain_safe_divide()) +MaskedArray.__rtruediv__ = _arithmethods('__rtruediv__', 1, 0, + domain_safe_divide()) +MaskedArray.__floordiv__ = _arithmethods('__floordiv__', 0, 1, + domain_safe_divide()) +MaskedArray.__rfloordiv__ = _arithmethods('__rfloordiv__', 1, 0, + domain_safe_divide()) +MaskedArray.__eq__ = _compamethods('__eq__') +MaskedArray.__ne__ = _compamethods('__ne__') +MaskedArray.__le__ = _compamethods('__le__') +MaskedArray.__lt__ = _compamethods('__lt__') +MaskedArray.__ge__ = _compamethods('__ge__') +MaskedArray.__gt__ = _compamethods('__gt__') +#####-------------------------------------------------------------------------- +#---- --- Shortcuts --- +#####--------------------------------------------------------------------------- +def isMaskedArray (x): + "Is x a masked array, that is, an instance of MaskedArray?" + return isinstance(x, MaskedArray) +isarray = isMaskedArray +isMA = isMaskedArray #backward compatibility +#masked = MaskedArray(0, int, mask=1) +masked_singleton = MaskedArray(0, dtype=int_, mask=True) +masked = masked_singleton + +masked_array = MaskedArray +def array(data, dtype=None, copy=False, order=False, mask=nomask, + keep_mask=True, small_mask=True, hard_mask=None, fill_value=None): + """array(data, dtype=None, copy=True, order=False, mask=nomask, + keep_mask=True, small_mask=True, fill_value=None) +Acts as shortcut to MaskedArray, with options in a different order for convenience. +And backwards compatibility... + """ + return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, + keep_mask=keep_mask, small_mask=small_mask, + hard_mask=hard_mask, fill_value=fill_value) + +def is_masked(x): + """Returns whether x has some masked values.""" + m = getmask(x) + if m is nomask: + return False + elif m.any(): + return True + return False + + +#####-------------------------------------------------------------------------- +#---- --- Patch methods --- +#####-------------------------------------------------------------------------- +#class _arraymethod: +# """Defines a wrapper for basic array methods. +#Upon call, returns a masked array, where the new `_data` array is the output +#of the corresponding method called on the original `_data`. +# +#If `onmask` is True, the new mask is the output of the method calld on the initial mask. +#If `onmask` is False, the new mask is just a reference to the initial mask. +# +#:Parameters: +# `funcname` : String +# Name of the function to apply on data. +# `onmask` : Boolean *[True]* +# Whether the mask must be processed also (True) or left alone (False). +# """ +# def __init__(self, funcname, onmask=True): +# self._name = funcname +# self._onmask = onmask +# self.__doc__ = getattr(ndarray, self._name).__doc__ +# def __call__(self, instance, *args, **params): +# methodname = self._name +# (d,m) = (instance._data, instance._mask) +# C = instance.__class__ +# if m is nomask: +# return C(getattr(d,methodname).__call__(*args, **params)) +# elif self._onmask: +# return C(getattr(d,methodname).__call__(*args, **params), +# mask=getattr(m,methodname)(*args, **params) ) +# else: +# return C(getattr(d,methodname).__call__(*args, **params), mask=m) +# +# def patch(self): +# "Adds the new method to MaskedArray." +# return types.MethodType(self, None, MaskedArray) +##...................................... +#MaskedArray.conj = MaskedArray.conjugate = _arraymethod('conjugate').patch() +#MaskedArray.diagonal = _arraymethod('diagonal').patch() +#MaskedArray.take = _arraymethod('take').patch() +#MaskedArray.ravel = _arraymethod('ravel').patch() +#MaskedArray.transpose = _arraymethod('transpose').patch() +#MaskedArray.T = _arraymethod('transpose').patch() +#MaskedArray.swapaxes = _arraymethod('swapaxes').patch() +#MaskedArray.clip = _arraymethod('clip', onmask=False).patch() +#MaskedArray.compress = _arraymethod('compress').patch() +#MaskedArray.resize = _arraymethod('resize').patch() +#MaskedArray.copy = _arraymethod('copy').patch() + +class _arraymethod(object): + """Defines a wrapper for basic array methods. +Upon call, returns a masked array, where the new `_data` array is the output +of the corresponding method called on the original `_data`. + +If `onmask` is True, the new mask is the output of the method calld on the initial mask. +If `onmask` is False, the new mask is just a reference to the initial mask. + +:Parameters: + `funcname` : String + Name of the function to apply on data. + `onmask` : Boolean *[True]* + Whether the mask must be processed also (True) or left alone (False). + """ + def __init__(self, funcname, onmask=True): + self._name = funcname + self._onmask = onmask + self.obj = None + self.__doc__ = self.getdoc() + # + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + try: + return getattr(MaskedArray, self._name).__doc__ + except: + return getattr(numpy, self._name).__doc__ + # + def __get__(self, obj, objtype=None): + self.obj = obj + return self + # + def __call__(self, *args, **params): + methodname = self._name + obj = self.obj + (d, m) = (obj._data, obj._mask) + (t, f) = (obj.dtype, obj._fill_value) + C = self.obj.__class__ + if m is nomask: + return C(getattr(d,methodname).__call__(*args, **params), + dtype=t, fill_value=f) + elif self._onmask: + return C(getattr(d,methodname).__call__(*args, **params), + mask=getattr(m,methodname)(*args, **params), + dtype=t, fill_value=f, **obj.options) + else: + return C(getattr(d,methodname).__call__(*args, **params), mask=m, + dtype=t, fill_value=f, **obj.options) +#...................................... +MaskedArray.conj = MaskedArray.conjugate = _arraymethod('conjugate') +MaskedArray.copy = _arraymethod('copy') +MaskedArray.diagonal = _arraymethod('diagonal') +MaskedArray.take = _arraymethod('take') +MaskedArray.ravel = _arraymethod('ravel') +MaskedArray.transpose = _arraymethod('transpose') +MaskedArray.T = property(fget=lambda self:self.transpose()) +MaskedArray.swapaxes = _arraymethod('swapaxes') +MaskedArray.clip = _arraymethod('clip', onmask=False) +MaskedArray.compress = _arraymethod('compress') +MaskedArray.copy = _arraymethod('copy') +MaskedArray.squeeze = _arraymethod('squeeze') + +#####-------------------------------------------------------------------------- +#---- --- Extrema functions --- +#####-------------------------------------------------------------------------- +class _minimum_operation: + "Object to calculate minima" + def __init__ (self): + """minimum(a, b) or minimum(a) +In one argument case, returns the scalar minimum. + """ + pass + #......... + def __call__ (self, a, b=None): + "Execute the call behavior." + if b is None: + m = getmask(a) + if m is nomask: + d = amin(filled(a).ravel()) + return d + ac = a.compressed() + if len(ac) == 0: + return masked + else: + return amin(ac) + else: + return where(less(a, b), a, b) + #......... + def reduce(self, target, axis=0): + """Reduces `target` along the given `axis`.""" + m = getmask(target) + if m is nomask: + t = filled(target) + return masked_array (umath.minimum.reduce (t, axis)) + else: + t = umath.minimum.reduce(filled(target, minimum_fill_value(target)), + axis) + m = umath.logical_and.reduce(m, axis) +# return masked_array(t, mask=m, fill_value=get_fill_value(target)) + try: + return target.__class__(t, mask=m, dtype=t.dtype, + fill_value=get_fill_value(target)) + except AttributeError: + return masked_array(t, mask=m, dtype=t.dtype, + fill_value=get_fill_value(target)) + #......... + def outer(self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = logical_or.outer(ma, mb) + d = umath.minimum.outer(filled(a), filled(b)) + return masked_array(d, mask=m) + +def min(array, axis=None, out=None): + """Returns the minima along the given axis. +If `axis` is None, applies to the flattened array.""" + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") + if axis is None: + return minimum(array) + else: + return minimum.reduce(array, axis) +#................................................ +class _maximum_operation: + "Object to calculate maxima" + def __init__ (self): + """maximum(a, b) or maximum(a) + In one argument case returns the scalar maximum. + """ + pass + #......... + def __call__ (self, a, b=None): + "Executes the call behavior." + if b is None: + m = getmask(a) + if m is nomask: + d = amax(filled(a).ravel()) + return d + ac = a.compressed() + if len(ac) == 0: + return masked + else: + return amax(ac) + else: + return where(greater(a, b), a, b) + #......... + def reduce (self, target, axis=0): + """Reduces target along the given axis.""" + m = getmask(target) + if m is nomask: + t = filled(target) + return masked_array(umath.maximum.reduce (t, axis)) + else: + t = umath.maximum.reduce(filled(target, maximum_fill_value(target)), + axis) + m = umath.logical_and.reduce(m, axis) + try: + return target.__class__(t, mask=m, dtype=t.dtype, + fill_value=get_fill_value(target)) + except AttributeError: + return masked_array(t, mask=m, dtype=t.dtype, + fill_value=get_fill_value(target)) + #......... + def outer (self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = logical_or.outer(ma, mb) + d = umath.maximum.outer(filled(a), filled(b)) + return masked_array(d, mask=m) + +def max(obj, axis=None, out=None): + """Returns the maxima along the given axis. +If `axis` is None, applies to the flattened array.""" + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") + if axis is None: + return maximum(obj) + else: + return maximum.reduce(obj, axis) +#................................................ +def ptp(obj, axis=None): + """a.ptp(axis=None) = a.max(axis)-a.min(axis)""" + try: + return obj.max(axis)-obj.min(axis) + except AttributeError: + return max(obj, axis=axis) - min(obj, axis=axis) +#................................................ +MaskedArray.min = min +MaskedArray.max = max +MaskedArray.ptp = ptp + +#####--------------------------------------------------------------------------- +#---- --- Definition of functions from the corresponding methods --- +#####--------------------------------------------------------------------------- +class _frommethod: + """Defines functions from existing MaskedArray methods. +:ivar _methodname (String): Name of the method to transform. + """ + def __init__(self, methodname): + self._methodname = methodname + self.__doc__ = self.getdoc() + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + try: + return getattr(MaskedArray, self._methodname).__doc__ + except: + return getattr(numpy, self._methodname).__doc__ + def __call__(self, x, *args, **params): + if isinstance(x, MaskedArray): + return getattr(x, self._methodname).__call__(*args, **params) + #FIXME: As x is not a MaskedArray, we transform it to a ndarray with asarray + #FIXME: ... and call the corresponding method. + #FIXME: Except that sometimes it doesn't work (try reshape([1,2,3,4],(2,2))) + #FIXME: we end up with a "SystemError: NULL result without error in PyObject_Call" + #FIXME: A dirty trick is then to call the initial numpy function... + method = getattr(fromnumeric.asarray(x), self._methodname) + try: + return method(*args, **params) + except SystemError: + return getattr(numpy,self._methodname).__call__(x, *args, **params) + +all = _frommethod('all') +anomalies = anom = _frommethod('anom') +any = _frommethod('any') +conjugate = _frommethod('conjugate') +ids = _frommethod('ids') +nonzero = _frommethod('nonzero') +diagonal = _frommethod('diagonal') +maximum = _maximum_operation() +mean = _frommethod('mean') +minimum = _minimum_operation () +product = _frommethod('prod') +ptp = _frommethod('ptp') +ravel = _frommethod('ravel') +repeat = _frommethod('repeat') +std = _frommethod('std') +sum = _frommethod('sum') +swapaxes = _frommethod('swapaxes') +take = _frommethod('take') +var = _frommethod('var') + +#.............................................................................. +def power(a, b, third=None): + """Computes a**b elementwise. + Masked values are set to 1.""" + if third is not None: + raise MAError, "3-argument power not supported." + ma = getmask(a) + mb = getmask(b) + m = mask_or(ma, mb) + fa = filled(a, 1) + fb = filled(b, 1) + if fb.dtype.char in typecodes["Integer"]: + return masked_array(umath.power(fa, fb), m) + md = make_mask((fa < 0), small_mask=1) + m = mask_or(m, md) + if m is nomask: + return masked_array(umath.power(fa, fb)) + else: + fa[m] = 1 + return masked_array(umath.power(fa, fb), m) + +#.............................................................................. +def argsort(a, axis=None, kind='quicksort', fill_value=None): + """Returns an array of indices that sort 'a' along the specified axis. + Masked values are filled beforehand to `fill_value`. + If `fill_value` is None, uses the default for the data type. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `kind` : String *['quicksort']* + Sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + + Returns: array of indices that sort 'a' along the specified axis. + + This method executes an indirect sort along the given axis using the + algorithm specified by the kind keyword. It returns an array of indices of + the same shape as 'a' that index data along the given axis in sorted order. + + The various sorts are characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order. The three + available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is not + along the last axis. Consequently, sorts along the last axis are faster and use + less space than sorts along other axis. + """ + if fill_value is None: + fill_value = default_fill_value(a) + d = filled(a, fill_value) + if axis is None: + return d.argsort(kind=kind) + return d.argsort(axis, kind) + +def argmin(a, axis=None, fill_value=None): + """Returns the array of indices for the minimum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = default_fill_value(a) + d = filled(a, fill_value) + if axis is None: + return d.argmin(axis=None) + return d.argmin(axis=axis) + +def argmax(a, axis=None, fill_value=None): + """Returns the array of indices for the maximum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = default_fill_value(a) + try: + fill_value = - fill_value + except: + pass + d = filled(a, fill_value) + if axis is None: + return d.argmax(axis=None) + return d.argmax(axis=axis) + +def sort(a, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None): + """ + Sort a along the given axis. + +Keyword arguments: + +axis -- axis to be sorted (default -1) +kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. +order -- If a has fields defined, then the order keyword can be the + field name to sort on or a list (or tuple) of field names + to indicate the order that fields should be used to define + the sort. +endwith--Boolean flag indicating whether missing values (if any) should + be forced in the upper indices (at the end of the array) or + lower indices (at the beginning). + +Returns: None. + +This method sorts 'a' in place along the given axis using the algorithm +specified by the kind keyword. + +The various sorts may characterized by average speed, worst case +performance, need for work space, and whether they are stable. A stable +sort keeps items with the same key in the same relative order and is most +useful when used with argsort where the key might differ from the items +being sorted. The three available algorithms have the following properties: + +|------------------------------------------------------| +| kind | speed | worst case | work space | stable| +|------------------------------------------------------| +|'quicksort'| 1 | O(n^2) | 0 | no | +|'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | +|'heapsort' | 3 | O(n*log(n)) | 0 | no | +|------------------------------------------------------| + +All the sort algorithms make temporary copies of the data when the sort is +not along the last axis. Consequently, sorts along the last axis are faster +and use less space than sorts along other axis. + +""" + a = numeric.asanyarray(a) + if fill_value is None: + if endwith: + filler = minimum_fill_value(a) + else: + filler = maximum_fill_value(a) + else: + filler = fill_value +# return + indx = numpy.indices(a.shape).tolist() + indx[axis] = filled(a,filler).argsort(axis=axis,kind=kind,order=order) + return a[indx] + +def compressed(x): + """Returns a compressed version of a masked array (or just the array if it + wasn't masked first).""" + if getmask(x) is None: + return x + else: + return x.compressed() + +def count(a, axis = None): + "Count of the non-masked elements in a, or along a certain axis." + a = masked_array(a) + return a.count(axis) + +def concatenate(arrays, axis=0): + "Concatenates the arrays along the given axis" + #TODO: We lose the subclass, here! We should keep track of the classes... + #TODO: ...and find the max ? the lowest according to MRO? + d = [] + for x in arrays: + d.append(filled(x)) + d = numeric.concatenate(d, axis) + for x in arrays: + if getmask(x) is not nomask: + break + else: + return masked_array(d) + dm = [] + for x in arrays: + dm.append(getmaskarray(x)) + dm = make_mask(numeric.concatenate(dm, axis), copy=False, small_mask=True) + return masked_array(d, mask=dm) + +def expand_dims(x,axis): + """Expand the shape of a by including newaxis before given axis.""" + if isinstance(x, MaskedArray): + (d,m) = (x._data, x._mask) + if m is nomask: + return masked_array(n_expand_dims(d,axis), + dtype=d.dtype, fill_value=x._fill_value) + else: + return masked_array(n_expand_dims(d,axis), + mask=n_expand_dims(m,axis), + dtype=d.dtype, fill_value=x._fill_value) + else: + return n_expand_dims(x,axis) + +#...................................... +def left_shift (a, n): + "Left shift n bits" + m = getmask(a) + if m is nomask: + d = umath.left_shift(filled(a), n) + return masked_array(d) + else: + d = umath.left_shift(filled(a, 0), n) + return masked_array(d, mask=m) + +def right_shift (a, n): + "Right shift n bits" + m = getmask(a) + if m is nomask: + d = umath.right_shift(filled(a), n) + return masked_array(d) + else: + d = umath.right_shift(filled(a, 0), n) + return masked_array(d, mask=m) +#...................................... +def put(a, indices, values, mode='raise'): + """Sets storage-indexed locations to corresponding values. + Values and indices are filled if necessary.""" + # We can't use 'frommethod', the order of arguments is different + try: + return a.put(indices, values, mode=mode) + except AttributeError: + return fromnumeric.asarray(a).put(indices, values, mode=mode) + +def putmask(a, mask, values): #, mode='raise'): + """`putmask(a, mask, v)` results in `a = v` for all places where `mask` is true. +If `v` is shorter than `mask`, it will be repeated as necessary. +In particular `v` can be a scalar or length 1 array.""" + # We can't use 'frommethod', the order of arguments is different + try: + return a.putmask(values, mask) + except AttributeError: + return fromnumeric.asarray(a).putmask(values, mask) + +def transpose(a,axes=None): + """Returns a view of the array with dimensions permuted according to axes. +If `axes` is None (default), returns array with dimensions reversed. + """ + #We can't use 'frommethod', as 'transpose' doesn't take keywords + try: + return a.transpose(axes) + except AttributeError: + return fromnumeric.asarray(a).transpose(axes) + +def reshape(a, new_shape): + """Changes the shape of the array `a` to `new_shape`.""" + #We can't use 'frommethod', it whine about some parameters. Dmmit. + try: + return a.reshape(new_shape) + except AttributeError: + return fromnumeric.asarray(a).reshape(new_shape) + +def resize(x, new_shape): + """resize(a,new_shape) returns a new array with the specified shape. + The total size of the original array can be any size. + The new array is filled with repeated copies of a. If a was masked, the new + array will be masked, and the new mask will be a repetition of the old one. + """ + # We can't use _frommethods here, as N.resize is notoriously whiny. + m = getmask(x) + if m is not nomask: + m = fromnumeric.resize(m, new_shape) + if isinstance(x, MaskedArray): + result = x.__class__(fromnumeric.resize(filled(x), new_shape), mask=m) + else: + result = masked_array(fromnumeric.resize(filled(x), new_shape), mask=m) + result.set_fill_value(get_fill_value(x)) + return result + + +#................................................ +def rank(obj): + """Gets the rank of sequence a (the number of dimensions, not a matrix rank) +The rank of a scalar is zero.""" + return fromnumeric.rank(filled(obj)) +# +def shape(obj): + """Returns the shape of `a` (as a function call which also works on nested sequences). + """ + return fromnumeric.shape(filled(obj)) +# +def size(obj, axis=None): + """Returns the number of elements in the array along the given axis, +or in the sequence if `axis` is None. + """ + return fromnumeric.size(filled(obj), axis) +#................................................ + +#####-------------------------------------------------------------------------- +#---- --- Extra functions --- +#####-------------------------------------------------------------------------- +def where (condition, x, y): + """where(condition, x, y) is x where condition is nonzero, y otherwise. + condition must be convertible to an integer array. + Answer is always the shape of condition. + The type depends on x and y. It is integer if both x and y are + the value masked. + """ + fc = filled(not_equal(condition, 0), 0) + xv = filled(x) + xm = getmask(x) + yv = filled(y) + ym = getmask(y) + d = numeric.choose(fc, (yv, xv)) + md = numeric.choose(fc, (ym, xm)) + m = getmask(condition) + m = make_mask(mask_or(m, md), copy=False, small_mask=True) + return masked_array(d, mask=m) + +def choose (indices, t, out=None, mode='raise'): + "Returns array shaped like indices with elements chosen from t" + #TODO: implement options `out` and `mode`, if possible. + def fmask (x): + "Returns the filled array, or True if ``masked``." + if x is masked: + return 1 + return filled(x) + def nmask (x): + "Returns the mask, True if ``masked``, False if ``nomask``." + if x is masked: + return 1 + m = getmask(x) + if m is nomask: + return 0 + return m + c = filled(indices, 0) + masks = [nmask(x) for x in t] + a = [fmask(x) for x in t] + d = numeric.choose(c, a) + m = numeric.choose(c, masks) + m = make_mask(mask_or(m, getmask(indices)), copy=0, small_mask=1) + return masked_array(d, mask=m) + +def round_(a, decimals=0, out=None): + """Returns reference to result. Copies a and rounds to 'decimals' places. + + Keyword arguments: + decimals -- number of decimals to round to (default 0). May be negative. + out -- existing array to use for output (default copy of a). + + Return: + Reference to out, where None specifies a copy of the original array a. + + Round to the specified number of decimals. When 'decimals' is negative it + specifies the number of positions to the left of the decimal point. The + real and imaginary parts of complex numbers are rounded separately. + Nothing is done if the array is not of float type and 'decimals' is greater + than or equal to 0.""" + if not hasattr(a, "_mask"): + mask = nomask + else: + mask = a._mask + if out is None: + return a.__class__(fromnumeric.round_(a, decimals, None), mask=mask) + else: + out = a.__class__(fromnumeric.round_(a, decimals, out), mask=mask) + return out + +def arange(start, stop=None, step=1, dtype=None): + """Just like range() except it returns a array whose type can be specified + by the keyword argument dtype. + """ + return array(numeric.arange(start, stop, step, dtype), mask=nomask) + +def inner(a, b): + """inner(a,b) returns the dot product of two arrays, which has + shape a.shape[:-1] + b.shape[:-1] with elements computed by summing the + product of the elements from the last dimensions of a and b. + Masked elements are replace by zeros. + """ + fa = filled(a, 0) + fb = filled(b, 0) + if len(fa.shape) == 0: + fa.shape = (1,) + if len(fb.shape) == 0: + fb.shape = (1,) + return masked_array(numeric.inner(fa, fb)) +innerproduct = inner + +def outer(a, b): + """outer(a,b) = {a[i]*b[j]}, has shape (len(a),len(b))""" + fa = filled(a, 0).ravel() + fb = filled(b, 0).ravel() + d = numeric.outer(fa, fb) + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + return masked_array(d) + ma = getmaskarray(a) + mb = getmaskarray(b) + m = make_mask(1-numeric.outer(1-ma, 1-mb), copy=0) + return masked_array(d, mask=m) +outerproduct = outer + +def allequal (a, b, fill_value=True): + """ +Returns `True` if all entries of a and b are equal, using +fill_value as a truth value where either or both are masked. + """ + m = mask_or(getmask(a), getmask(b)) + if m is nomask: + x = filled(a) + y = filled(b) + d = umath.equal(x, y) + return d.all() + elif fill_value: + x = filled(a) + y = filled(b) + d = umath.equal(x, y) + dm = array(d, mask=m, copy=False) + return dm.filled(True).all(None) + else: + return False + +def allclose (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8): + """ Returns `True` if all elements of `a` and `b` are equal subject to given tolerances. +If `fill_value` is True, masked values are considered equal. +If `fill_value` is False, masked values considered unequal. +The relative error rtol should be positive and << 1.0 +The absolute error `atol` comes into play for those elements of `b` + that are very small or zero; it says how small `a` must be also. + """ + m = mask_or(getmask(a), getmask(b)) + d1 = filled(a) + d2 = filled(b) + x = filled(array(d1, copy=0, mask=m), fill_value).astype(float) + y = filled(array(d2, copy=0, mask=m), 1).astype(float) + d = umath.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y)) + return fromnumeric.alltrue(fromnumeric.ravel(d)) + +#.............................................................................. +def asarray(a, dtype=None): + """asarray(data, dtype) = array(data, dtype, copy=0) +Returns `a` as an masked array. +No copy is performed if `a` is already an array. +Subclasses are converted to base class MaskedArray. + """ + return masked_array(a, dtype=dtype, copy=False, keep_mask=True) + +def empty(new_shape, dtype=float): + """empty((d1,...,dn),dtype=float,order='C') +Returns a new array of shape (d1,...,dn) and given type with all its +entries uninitialized. This can be faster than zeros.""" + return masked_array(numeric.empty(new_shape, dtype), mask=nomask) + +def empty_like(a): + """empty_like(a) +Returns an empty (uninitialized) array of the shape and typecode of a. +Note that this does NOT initialize the returned array. +If you require your array to be initialized, you should use zeros_like().""" + return masked_array(numeric.empty_like(a), mask=nomask) + +def ones(new_shape, dtype=float): + """ones(shape, dtype=None) +Returns an array of the given dimensions, initialized to all ones.""" + return masked_array(numeric.ones(new_shape, dtype), mask=nomask) + +def zeros(new_shape, dtype=float): + """zeros(new_shape, dtype=None) +Returns an array of the given dimensions, initialized to all zeros.""" + return masked_array(numeric.zeros(new_shape, dtype), mask=nomask) + +#####-------------------------------------------------------------------------- +#---- --- Pickling --- +#####-------------------------------------------------------------------------- +#FIXME: We're kinda stuck with forcing the mask to have the same shape as the data +def _mareconstruct(subtype, baseshape, basetype,): + """Internal function that builds a new MaskedArray from the information stored +in a pickle.""" + _data = ndarray.__new__(ndarray, baseshape, basetype) + _mask = ndarray.__new__(ndarray, baseshape, basetype) + return MaskedArray.__new__(subtype, _data, mask=_mask, dtype=basetype, small_mask=False) + +def _getstate(a): + "Returns the internal state of the masked array, for pickling purposes." + state = (1, + a.shape, + a.dtype, + a.flags.fnc, + (a._data).__reduce__()[-1][-1], + getmaskarray(a).__reduce__()[-1][-1]) + return state + +def _setstate(a, state): + """Restores the internal state of the masked array, for pickling purposes. +`state` is typically the output of the ``__getstate__`` output, and is a 5-tuple: + + - class name + - a tuple giving the shape of the data + - a typecode for the data + - a binary string for the data + - a binary string for the mask. + """ + (ver, shp, typ, isf, raw, msk) = state + (a._data).__setstate__((shp, typ, isf, raw)) + (a._mask).__setstate__((shp, dtype('|b1'), isf, msk)) + +def _reduce(a): + """Returns a 3-tuple for pickling a MaskedArray.""" + return (_mareconstruct, + (a.__class__, (0,), 'b', ), + a.__getstate__()) + +def dump(a,F): + """Pickles the MaskedArray `a` to the file `F`. +`F` can either be the handle of an exiting file, or a string representing a file name. + """ + if not hasattr(F,'readline'): + F = open(F,'w') + return cPickle.dump(a,F) + +def dumps(a): + """Returns 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.""" + if not hasattr(F, 'readline'): + F = open(F,'r') + return cPickle.load(F) + +def loads(strg): + "Loads a pickle from the current string.""" + return cPickle.loads(strg) + +MaskedArray.__getstate__ = _getstate +MaskedArray.__setstate__ = _setstate +MaskedArray.__reduce__ = _reduce +MaskedArray.__dump__ = dump +MaskedArray.__dumps__ = dumps + +################################################################################ + +if __name__ == '__main__': + import numpy as N + if 1: + x = N.array([[ 0.13, 0.26, 0.90], + [ 0.28, 0.33, 0.63], + [ 0.31, 0.87, 0.70]]) + m = N.array([[ True, False, False], + [False, False, False], + [True, True, False]], dtype=N.bool_) + X = N.asmatrix(x) + mX = masked_array(X, mask=m) Added: trunk/scipy/sandbox/maskedarray/alternative_versions/core_initial.py =================================================================== --- trunk/scipy/sandbox/maskedarray/alternative_versions/core_initial.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/alternative_versions/core_initial.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,2708 @@ +# pylint: disable-msg=E1002 +"""MA: a facility for dealing with missing observations +MA is generally used as a numpy.array look-alike. +by Paul F. Dubois. + +Copyright 1999, 2000, 2001 Regents of the University of California. +Released for unlimited redistribution. +Adapted for numpy_core 2005 by Travis Oliphant and +(mainly) Paul Dubois. + +Subclassing of the base ndarray 2006 by Pierre Gerard-Marchant. +pgmdevlist_AT_gmail_DOT_com +Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com) + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: core.py 254 2007-08-15 04:11:52Z backtopop $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: backtopop $)" +__version__ = '1.0' +__revision__ = "$Revision: 254 $" +__date__ = '$Date: 2007-08-15 00:11:52 -0400 (Wed, 15 Aug 2007) $' + +__all__ = ['MAError', 'MaskType', 'MaskedArray', + 'bool_', 'complex_', 'float_', 'int_', 'object_', + 'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue', + 'amax', 'amin', 'anom', 'anomalies', 'any', 'arange', + 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', + 'arctanh', 'argmax', 'argmin', 'argsort', 'around', + 'array', 'asarray', + 'bitwise_and', 'bitwise_or', 'bitwise_xor', + 'ceil', 'choose', 'compressed', 'concatenate', 'conjugate', + 'cos', 'cosh', 'count', + 'diagonal', 'divide', 'dump', 'dumps', + 'empty', 'empty_like', 'equal', 'exp', + 'fabs', 'fmod', 'filled', 'floor', 'floor_divide', + 'getmask', 'getmaskarray', 'greater', 'greater_equal', 'hypot', + 'ids', 'inner', 'innerproduct', + 'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', + 'left_shift', 'less', 'less_equal', 'load', 'loads', 'log', 'log10', + 'logical_and', 'logical_not', 'logical_or', 'logical_xor', + 'make_mask', 'make_mask_none', 'mask_or', 'masked', + 'masked_array', 'masked_equal', 'masked_greater', + 'masked_greater_equal', 'masked_inside', 'masked_less', + 'masked_less_equal', 'masked_not_equal', 'masked_object', + 'masked_outside', 'masked_print_option', 'masked_singleton', + 'masked_values', 'masked_where', 'max', 'maximum', 'mean', 'min', + 'minimum', 'multiply', + 'negative', 'nomask', 'nonzero', 'not_equal', + 'ones', 'outer', 'outerproduct', + 'power', 'product', 'ptp', 'put', 'putmask', + 'rank', 'ravel', 'remainder', 'repeat', 'reshape', 'resize', + 'right_shift', 'round_', + 'shape', 'sin', 'sinh', 'size', 'sometrue', 'sort', 'sqrt', 'std', + 'subtract', 'sum', 'swapaxes', + 'take', 'tan', 'tanh', 'transpose', 'true_divide', + 'var', 'where', + 'zeros'] + +import sys +import types +import cPickle +import operator +# +import numpy +from numpy import bool_, complex_, float_, int_, object_, str_ + +import numpy.core.umath as umath +import numpy.core.fromnumeric as fromnumeric +import numpy.core.numeric as numeric +import numpy.core.numerictypes as ntypes +from numpy import bool_, dtype, typecodes, amax, amin, ndarray +from numpy import expand_dims as n_expand_dims +import warnings + + +MaskType = bool_ +nomask = MaskType(0) + +divide_tolerance = 1.e-35 +numpy.seterr(all='ignore') + +# TODO: There's still a problem with N.add.reduce not working... +# TODO: ...neither does N.add.accumulate + +#####-------------------------------------------------------------------------- +#---- --- Exceptions --- +#####-------------------------------------------------------------------------- +class MAError(Exception): + "Class for MA related errors." + def __init__ (self, args=None): + "Creates an exception." + Exception.__init__(self,args) + self.args = args + def __str__(self): + "Calculates the string representation." + return str(self.args) + __repr__ = __str__ + +#####-------------------------------------------------------------------------- +#---- --- Filling options --- +#####-------------------------------------------------------------------------- +# b: boolean - c: complex - f: floats - i: integer - O: object - S: string +default_filler = {'b': True, + 'c' : 1.e20 + 0.0j, + 'f' : 1.e20, + 'i' : 999999, + 'O' : '?', + 'S' : 'N/A', + 'u' : 999999, + 'V' : '???', + } +max_filler = ntypes._minvals +max_filler.update([(k,-numeric.inf) for k in [numpy.float32, numpy.float64]]) +min_filler = ntypes._maxvals +min_filler.update([(k,numeric.inf) for k in [numpy.float32, numpy.float64]]) +if 'float128' in ntypes.typeDict: + max_filler.update([(numpy.float128,-numeric.inf)]) + min_filler.update([(numpy.float128, numeric.inf)]) + + +def default_fill_value(obj): + "Calculates the default fill value for an object `obj`." + if hasattr(obj,'dtype'): + defval = default_filler[obj.dtype.kind] + elif isinstance(obj, numeric.dtype): + defval = default_filler[obj.kind] + elif isinstance(obj, float): + defval = default_filler['f'] + elif isinstance(obj, int) or isinstance(obj, long): + defval = default_filler['i'] + elif isinstance(obj, str): + defval = default_filler['S'] + elif isinstance(obj, complex): + defval = default_filler['c'] + else: + defval = default_filler['O'] + return defval + +def minimum_fill_value(obj): + "Calculates the default fill value suitable for taking the minimum of `obj`." + if hasattr(obj, 'dtype'): + objtype = obj.dtype + filler = min_filler[objtype] + if filler is None: + raise TypeError, 'Unsuitable type for calculating minimum.' + return filler + elif isinstance(obj, float): + return min_filler[ntypes.typeDict['float_']] + elif isinstance(obj, int): + return min_filler[ntypes.typeDict['int_']] + elif isinstance(obj, long): + return min_filler[ntypes.typeDict['uint']] + elif isinstance(obj, numeric.dtype): + return min_filler[obj] + else: + raise TypeError, 'Unsuitable type for calculating minimum.' + +def maximum_fill_value(obj): + "Calculates the default fill value suitable for taking the maximum of `obj`." + if hasattr(obj, 'dtype'): + objtype = obj.dtype + filler = max_filler[objtype] + if filler is None: + raise TypeError, 'Unsuitable type for calculating minimum.' + return filler + elif isinstance(obj, float): + return max_filler[ntypes.typeDict['float_']] + elif isinstance(obj, int): + return max_filler[ntypes.typeDict['int_']] + elif isinstance(obj, long): + return max_filler[ntypes.typeDict['uint']] + elif isinstance(obj, numeric.dtype): + return max_filler[obj] + else: + raise TypeError, 'Unsuitable type for calculating minimum.' + +def set_fill_value(a, fill_value): + "Sets the fill value of `a` if it is a masked array." + if isinstance(a, MaskedArray): + a.set_fill_value(fill_value) + +def get_fill_value(a): + """Returns the fill value of `a`, if any. + Otherwise, returns the default fill value for that type. + """ + if isinstance(a, MaskedArray): + result = a.fill_value + else: + result = default_fill_value(a) + return result + +def common_fill_value(a, b): + "Returns the common fill_value of `a` and `b`, if any, or `None`." + t1 = get_fill_value(a) + t2 = get_fill_value(b) + if t1 == t2: + return t1 + return None + +#................................................ +def filled(a, value = None): + """Returns `a` as an array with masked data replaced by `value`. +If `value` is `None` or the special element `masked`, `get_fill_value(a)` +is used instead. + +If `a` is already a contiguous numeric array, `a` itself is returned. + +`filled(a)` can be used to be sure that the result is numeric when passing +an object a to other software ignorant of MA, in particular to numpy itself. + """ + if hasattr(a, 'filled'): + return a.filled(value) + elif isinstance(a, ndarray): # and a.flags['CONTIGUOUS']: + return a + elif isinstance(a, dict): + return numeric.array(a, 'O') + else: + return numeric.array(a) + +def get_masked_subclass(*arrays): + """Returns the youngest subclass of MaskedArray from a list of arrays, + or MaskedArray. In case of siblings, the first takes over.""" + if len(arrays) == 1: + arr = arrays[0] + if isinstance(arr, MaskedArray): + rcls = type(arr) + else: + rcls = MaskedArray + else: + arrcls = [type(a) for a in arrays] + rcls = arrcls[0] + if not issubclass(rcls, MaskedArray): + rcls = MaskedArray + for cls in arrcls[1:]: + if issubclass(cls, rcls): + rcls = cls + return rcls + +#####-------------------------------------------------------------------------- +#---- --- Ufuncs --- +#####-------------------------------------------------------------------------- +ufunc_domain = {} +ufunc_fills = {} + +class domain_check_interval: + """Defines a valid interval, +so that `domain_check_interval(a,b)(x) = true` where `x < a` or `x > b`.""" + def __init__(self, a, b): + "domain_check_interval(a,b)(x) = true where x < a or y > b" + if (a > b): + (a, b) = (b, a) + self.a = a + self.b = b + + def __call__ (self, x): + "Execute the call behavior." + return umath.logical_or(umath.greater (x, self.b), + umath.less(x, self.a)) +#............................ +class domain_tan: + """Defines a valid interval for the `tan` function, +so that `domain_tan(eps) = True where `abs(cos(x)) < eps`""" + def __init__(self, eps): + "domain_tan(eps) = true where abs(cos(x)) < eps)" + self.eps = eps + def __call__ (self, x): + "Execute the call behavior." + return umath.less(umath.absolute(umath.cos(x)), self.eps) +#............................ +class domain_safe_divide: + """defines a domain for safe division.""" + def __init__ (self, tolerance=divide_tolerance): + self.tolerance = tolerance + def __call__ (self, a, b): + return umath.absolute(a) * self.tolerance >= umath.absolute(b) +#............................ +class domain_greater: + "domain_greater(v)(x) = true where x <= v" + def __init__(self, critical_value): + "domain_greater(v)(x) = true where x <= v" + self.critical_value = critical_value + + def __call__ (self, x): + "Execute the call behavior." + return umath.less_equal(x, self.critical_value) +#............................ +class domain_greater_equal: + "domain_greater_equal(v)(x) = true where x < v" + def __init__(self, critical_value): + "domain_greater_equal(v)(x) = true where x < v" + self.critical_value = critical_value + + def __call__ (self, x): + "Execute the call behavior." + return umath.less(x, self.critical_value) +#.............................................................................. +class masked_unary_operation: + """Defines masked version of unary operations, +where invalid values are pre-masked. + +:IVariables: + - `f` : function. + - `fill` : Default filling value *[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, mufunc, fill=0, domain=None): + """ masked_unary_operation(aufunc, fill=0, domain=None) + aufunc(fill) must be defined + self(x) returns aufunc(x) + with masked values where domain(x) is true or getmask(x) is true. + """ + self.f = mufunc + self.fill = fill + self.domain = domain + self.__doc__ = getattr(mufunc, "__doc__", str(mufunc)) + self.__name__ = getattr(mufunc, "__name__", str(mufunc)) + ufunc_domain[mufunc] = domain + ufunc_fills[mufunc] = fill + # + def __call__ (self, a, *args, **kwargs): + "Execute the call behavior." +# numeric tries to return scalars rather than arrays when given scalars. + m = getmask(a) + d1 = filled(a, self.fill) + if self.domain is not None: + m = mask_or(m, numeric.asarray(self.domain(d1))) + # Take care of the masked singletong first ... + if m.ndim == 0 and m: + return masked + # Get the result.... + if isinstance(a, MaskedArray): + result = self.f(d1, *args, **kwargs).view(type(a)) + else: + result = self.f(d1, *args, **kwargs).view(MaskedArray) + # Fix the mask if we don't have a scalar + if result.ndim > 0: + result._mask = m + return result + # + def __str__ (self): + return "Masked version of %s. [Invalid values are masked]" % str(self.f) +#.............................................................................. +class masked_binary_operation: + """Defines masked version of binary operations, +where invalid values are pre-masked. + +:IVariables: + - `f` : function. + - `fillx` : Default filling value for first array*[0]*. + - `filly` : Default filling value for second array*[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, mbfunc, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + self.f = mbfunc + self.fillx = fillx + self.filly = filly + self.__doc__ = getattr(mbfunc, "__doc__", str(mbfunc)) + self.__name__ = getattr(mbfunc, "__name__", str(mbfunc)) + ufunc_domain[mbfunc] = None + ufunc_fills[mbfunc] = (fillx, filly) + # + def __call__ (self, a, b, *args, **kwargs): + "Execute the call behavior." + m = mask_or(getmask(a), getmask(b)) + if (not m.ndim) and m: + return masked + d1 = filled(a, self.fillx) + d2 = filled(b, self.filly) +# CHECK : Do we really need to fill the arguments ? Pro'ly not +# result = self.f(a, b, *args, **kwargs).view(get_masked_subclass(a,b)) + result = self.f(d1, d2, *args, **kwargs).view(get_masked_subclass(a,b)) + if result.ndim > 0: + result._mask = m + return result + # + def reduce (self, target, axis=0, dtype=None): + """Reduces `target` along the given `axis`.""" + if isinstance(target, MaskedArray): + tclass = type(target) + else: + tclass = MaskedArray + m = getmask(target) + t = filled(target, self.filly) + if t.shape == (): + t = t.reshape(1) + if m is not nomask: + m = make_mask(m, copy=1) + m.shape = (1,) + if m is nomask: + return self.f.reduce(t, axis).view(tclass) + t = t.view(tclass) + t._mask = m + # XXX: "or t.dtype" below is a workaround for what appears + # XXX: to be a bug in reduce. + tr = self.f.reduce(filled(t, self.filly), axis, dtype=dtype or t.dtype) + mr = umath.logical_and.reduce(m, axis) + tr = tr.view(tclass) + if mr.ndim > 0: + tr._mask = mr + return tr + elif mr: + return masked + return tr + + def outer (self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = umath.logical_or.outer(ma, mb) + if (not m.ndim) and m: + return masked + rcls = get_masked_subclass(a,b) + d = self.f.outer(filled(a, self.fillx), filled(b, self.filly)).view(rcls) + if d.ndim > 0: + d._mask = m + return d + + def accumulate (self, target, axis=0): + """Accumulates `target` along `axis` after filling with y fill value.""" + if isinstance(target, MaskedArray): + tclass = type(target) + else: + tclass = masked_array + t = filled(target, self.filly) + return self.f.accumulate(t, axis).view(tclass) + + def __str__ (self): + return "Masked version of " + str(self.f) +#.............................................................................. +class domained_binary_operation: + """Defines binary operations that have a domain, like divide. + +These are complicated so they are a separate class. +They have no reduce, outer or accumulate. + +:IVariables: + - `f` : function. + - `fillx` : Default filling value for first array*[0]*. + - `filly` : Default filling value for second array*[0]*. + - `domain` : Default domain *[None]*. + """ + def __init__ (self, dbfunc, domain, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + self.f = dbfunc + self.domain = domain + self.fillx = fillx + self.filly = filly + self.__doc__ = getattr(dbfunc, "__doc__", str(dbfunc)) + self.__name__ = getattr(dbfunc, "__name__", str(dbfunc)) + ufunc_domain[dbfunc] = domain + ufunc_fills[dbfunc] = (fillx, filly) + + def __call__(self, a, b): + "Execute the call behavior." + ma = getmask(a) + mb = getmask(b) + d1 = filled(a, self.fillx) + d2 = filled(b, self.filly) + t = numeric.asarray(self.domain(d1, d2)) + + if fromnumeric.sometrue(t, None): + d2 = numeric.where(t, self.filly, d2) + mb = mask_or(mb, t) + m = mask_or(ma, mb) + if (not m.ndim) and m: + return masked + result = self.f(d1, d2).view(get_masked_subclass(a,b)) + if result.ndim > 0: + result._mask = m + return result + + def __str__ (self): + return "Masked version of " + str(self.f) + +#.............................................................................. +# Unary ufuncs +exp = masked_unary_operation(umath.exp) +conjugate = masked_unary_operation(umath.conjugate) +sin = masked_unary_operation(umath.sin) +cos = masked_unary_operation(umath.cos) +tan = masked_unary_operation(umath.tan) +arctan = masked_unary_operation(umath.arctan) +arcsinh = masked_unary_operation(umath.arcsinh) +sinh = masked_unary_operation(umath.sinh) +cosh = masked_unary_operation(umath.cosh) +tanh = masked_unary_operation(umath.tanh) +abs = absolute = masked_unary_operation(umath.absolute) +fabs = masked_unary_operation(umath.fabs) +negative = masked_unary_operation(umath.negative) +floor = masked_unary_operation(umath.floor) +ceil = masked_unary_operation(umath.ceil) +around = masked_unary_operation(fromnumeric.round_) +logical_not = masked_unary_operation(umath.logical_not) +# Domained unary ufuncs +sqrt = masked_unary_operation(umath.sqrt, 0.0, domain_greater_equal(0.0)) +log = masked_unary_operation(umath.log, 1.0, domain_greater(0.0)) +log10 = masked_unary_operation(umath.log10, 1.0, domain_greater(0.0)) +tan = masked_unary_operation(umath.tan, 0.0, domain_tan(1.e-35)) +arcsin = masked_unary_operation(umath.arcsin, 0.0, + domain_check_interval(-1.0, 1.0)) +arccos = masked_unary_operation(umath.arccos, 0.0, + domain_check_interval(-1.0, 1.0)) +arccosh = masked_unary_operation(umath.arccosh, 1.0, domain_greater_equal(1.0)) +arctanh = masked_unary_operation(umath.arctanh, 0.0, + domain_check_interval(-1.0+1e-15, 1.0-1e-15)) +# Binary ufuncs +add = masked_binary_operation(umath.add) +subtract = masked_binary_operation(umath.subtract) +multiply = masked_binary_operation(umath.multiply, 1, 1) +arctan2 = masked_binary_operation(umath.arctan2, 0.0, 1.0) +equal = masked_binary_operation(umath.equal) +equal.reduce = None +not_equal = masked_binary_operation(umath.not_equal) +not_equal.reduce = None +less_equal = masked_binary_operation(umath.less_equal) +less_equal.reduce = None +greater_equal = masked_binary_operation(umath.greater_equal) +greater_equal.reduce = None +less = masked_binary_operation(umath.less) +less.reduce = None +greater = masked_binary_operation(umath.greater) +greater.reduce = None +logical_and = masked_binary_operation(umath.logical_and) +alltrue = masked_binary_operation(umath.logical_and, 1, 1).reduce +logical_or = masked_binary_operation(umath.logical_or) +sometrue = logical_or.reduce +logical_xor = masked_binary_operation(umath.logical_xor) +bitwise_and = masked_binary_operation(umath.bitwise_and) +bitwise_or = masked_binary_operation(umath.bitwise_or) +bitwise_xor = masked_binary_operation(umath.bitwise_xor) +hypot = masked_binary_operation(umath.hypot) +# Domained binary ufuncs +divide = domained_binary_operation(umath.divide, domain_safe_divide(), 0, 1) +true_divide = domained_binary_operation(umath.true_divide, + domain_safe_divide(), 0, 1) +floor_divide = domained_binary_operation(umath.floor_divide, + domain_safe_divide(), 0, 1) +remainder = domained_binary_operation(umath.remainder, + domain_safe_divide(), 0, 1) +fmod = domained_binary_operation(umath.fmod, domain_safe_divide(), 0, 1) + + +#####-------------------------------------------------------------------------- +#---- --- Mask creation functions --- +#####-------------------------------------------------------------------------- +def getmask(a): + """Returns the mask of `a`, if any, or `nomask`. +Returns `nomask` if `a` is not a masked array. +To get an array for sure use getmaskarray.""" + if hasattr(a, "_mask"): + return a._mask + else: + return nomask + +def getmaskarray(a): + """Returns the mask of `a`, if any. +Otherwise, returns an array of `False`, with the same shape as `a`. + """ + m = getmask(a) + if m is nomask: + return make_mask_none(fromnumeric.shape(a)) + else: + return m + +def is_mask(m): + """Returns `True` if `m` is a legal mask. +Does not check contents, only type. + """ + try: + return m.dtype.type is MaskType + except AttributeError: + return False +# +def make_mask(m, copy=False, small_mask=True, flag=None): + """make_mask(m, copy=0, small_mask=0) +Returns `m` as a mask, creating a copy if necessary or requested. +The function can accept any sequence of integers or `nomask`. +Does not check that contents must be 0s and 1s. +If `small_mask=True`, returns `nomask` if `m` contains no true elements. + +:Parameters: + - `m` (ndarray) : Mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + - `small_mask` (boolean, *[False]*): Flattens mask to `nomask` if `m` is all false. + """ + if flag is not None: + warnings.warn("The flag 'flag' is now called 'small_mask'!", + DeprecationWarning) + small_mask = flag + if m is nomask: + return nomask + elif isinstance(m, ndarray): + m = filled(m, True) + if m.dtype.type is MaskType: + if copy: + result = numeric.array(m, dtype=MaskType, copy=copy) + else: + result = m + else: + result = numeric.array(m, dtype=MaskType) + else: + result = numeric.array(filled(m, True), dtype=MaskType) + # Bas les masques ! + if small_mask and not result.any(): + return nomask + else: + return result + +def make_mask_none(s): + "Returns a mask of shape `s`, filled with `False`." + result = numeric.zeros(s, dtype=MaskType) + return result + +def mask_or (m1, m2, copy=False, small_mask=True): + """Returns the combination of two masks `m1` and `m2`. +The masks are combined with the `logical_or` operator, treating `nomask` as false. +The result may equal m1 or m2 if the other is nomask. + +:Parameters: + - `m` (ndarray) : Mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + - `small_mask` (boolean, *[False]*): Flattens mask to `nomask` if `m` is all false. + """ + if m1 is nomask: + return make_mask(m2, copy=copy, small_mask=small_mask) + if m2 is nomask: + return make_mask(m1, copy=copy, small_mask=small_mask) + if m1 is m2 and is_mask(m1): + return m1 + return make_mask(umath.logical_or(m1, m2), copy=copy, small_mask=small_mask) + +#####-------------------------------------------------------------------------- +#--- --- Masking functions --- +#####-------------------------------------------------------------------------- +def masked_where(condition, a, copy=True): + """Returns `x` as an array masked where `condition` is true. +Masked values of `x` or `condition` are kept. + +:Parameters: + - `condition` (ndarray) : Masking condition. + - `x` (ndarray) : Array to mask. + - `copy` (boolean, *[False]*) : Returns a copy of `m` if true. + """ + cond = filled(condition,1) + a = numeric.array(a, copy=copy, subok=True) + if hasattr(a, '_mask'): + cond = mask_or(cond, a._mask) + cls = type(a) + else: + cls = MaskedArray + result = a.view(cls) + result._mask = cond + return result + +def masked_greater(x, value, copy=1): + "Shortcut to `masked_where`, with ``condition = (x > value)``." + return masked_where(greater(x, value), x, copy=copy) + +def masked_greater_equal(x, value, copy=1): + "Shortcut to `masked_where`, with ``condition = (x >= value)``." + return masked_where(greater_equal(x, value), x, copy=copy) + +def masked_less(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x < value)``." + return masked_where(less(x, value), x, copy=copy) + +def masked_less_equal(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x <= value)``." + return masked_where(less_equal(x, value), x, copy=copy) + +def masked_not_equal(x, value, copy=True): + "Shortcut to `masked_where`, with ``condition = (x != value)``." + return masked_where((x != value), x, copy=copy) + +# +def masked_equal(x, value, copy=True): + """Shortcut to `masked_where`, with ``condition = (x == value)``. +For floating point, consider `masked_values(x, value)` instead. + """ + return masked_where((x == value), x, copy=copy) +# d = filled(x, 0) +# c = umath.equal(d, value) +# m = mask_or(c, getmask(x)) +# return array(d, mask=m, copy=copy) + +def masked_inside(x, v1, v2, copy=True): + """Shortcut to `masked_where`, where `condition` is True for x inside +the interval `[v1,v2]` ``(v1 <= x <= v2)``. +The boundaries `v1` and `v2` can be given in either order. + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf >= v1) & (xf <= v2) + return masked_where(condition, x, copy=copy) + +def masked_outside(x, v1, v2, copy=True): + """Shortcut to `masked_where`, where `condition` is True for x outside +the interval `[v1,v2]` ``(x < v1)|(x > v2)``. +The boundaries `v1` and `v2` can be given in either order. + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf < v1) | (xf > v2) + return masked_where(condition, x, copy=copy) + +# +def masked_object(x, value, copy=True): + """Masks the array `x` where the data are exactly equal to `value`. +This function is suitable only for `object` arrays: for floating point, +please use `masked_values` instead. +The mask is set to `nomask` if posible. + +:parameter copy (Boolean, *[True]*): Returns a copy of `x` if true. """ + if isMaskedArray(x): + condition = umath.equal(x._data, value) + mask = x._mask + else: + condition = umath.equal(fromnumeric.asarray(x), value) + mask = nomask + mask = mask_or(mask, make_mask(condition, small_mask=True)) + return masked_array(x, mask=mask, copy=copy, fill_value=value) + +def masked_values(x, value, rtol=1.e-5, atol=1.e-8, copy=True): + """Masks the array `x` where the data are approximately equal to `value` +(that is, ``abs(x - value) <= atol+rtol*abs(value)``). +Suitable only for floating points. For integers, please use `masked_equal`. +The mask is set to `nomask` if posible. + +:Parameters: + - `rtol` (Float, *[1e-5]*): Tolerance parameter. + - `atol` (Float, *[1e-8]*): Tolerance parameter. + - `copy` (boolean, *[False]*) : Returns a copy of `x` if True. + """ + abs = umath.absolute + xnew = filled(x, value) + if issubclass(xnew.dtype.type, numeric.floating): + condition = umath.less_equal(abs(xnew-value), atol+rtol*abs(value)) + try: + mask = x._mask + except AttributeError: + mask = nomask + else: + condition = umath.equal(xnew, value) + mask = nomask + mask = mask_or(mask, make_mask(condition, small_mask=True)) + return masked_array(xnew, mask=mask, copy=copy, fill_value=value) + +#####-------------------------------------------------------------------------- +#---- --- Printing options --- +#####-------------------------------------------------------------------------- +class _MaskedPrintOption: + """Handles the string used to represent missing data in a masked array.""" + def __init__ (self, display): + "Creates the masked_print_option object." + self._display = display + self._enabled = True + + def display(self): + "Displays the string to print for masked values." + return self._display + + def set_display (self, s): + "Sets the string to print for masked values." + self._display = s + + def enabled(self): + "Is the use of the display value enabled?" + return self._enabled + + def enable(self, small_mask=1): + "Set the enabling small_mask to `small_mask`." + self._enabled = small_mask + + def __str__ (self): + return str(self._display) + + __repr__ = __str__ + +#if you single index into a masked location you get this object. +masked_print_option = _MaskedPrintOption('--') + +#####-------------------------------------------------------------------------- +#---- --- MaskedArray class --- +#####-------------------------------------------------------------------------- +##def _getoptions(a_out, a_in): +## "Copies standards options of a_in to a_out." +## for att in ['] +#class _mathmethod(object): +# """Defines a wrapper for arithmetic methods. +#Instead of directly calling a ufunc, the corresponding method of the `array._data` +#object is called instead. +# """ +# def __init__ (self, methodname, fill_self=0, fill_other=0, domain=None): +# """ +#:Parameters: +# - `methodname` (String) : Method name. +# - `fill_self` (Float *[0]*) : Fill value for the instance. +# - `fill_other` (Float *[0]*) : Fill value for the target. +# - `domain` (Domain object *[None]*) : Domain of non-validity. +# """ +# self.methodname = methodname +# self.fill_self = fill_self +# self.fill_other = fill_other +# self.domain = domain +# self.obj = None +# self.__doc__ = self.getdoc() +# # +# def getdoc(self): +# "Returns the doc of the function (from the doc of the method)." +# try: +# return getattr(MaskedArray, self.methodname).__doc__ +# except: +# return getattr(ndarray, self.methodname).__doc__ +# # +# def __get__(self, obj, objtype=None): +# self.obj = obj +# return self +# # +# def __call__ (self, other, *args): +# "Execute the call behavior." +# instance = self.obj +# m_self = instance._mask +# m_other = getmask(other) +# base = instance.filled(self.fill_self) +# target = filled(other, self.fill_other) +# if self.domain is not None: +# # We need to force the domain to a ndarray only. +# if self.fill_other > self.fill_self: +# domain = self.domain(base, target) +# else: +# domain = self.domain(target, base) +# if domain.any(): +# #If `other` is a subclass of ndarray, `filled` must have the +# # same subclass, else we'll lose some info. +# #The easiest then is to fill `target` instead of creating +# # a pure ndarray. +# #Oh, and we better make a copy! +# if isinstance(other, ndarray): +# # We don't want to modify other: let's copy target, then +# target = target.copy() +# target[fromnumeric.asarray(domain)] = self.fill_other +# else: +# target = numeric.where(fromnumeric.asarray(domain), +# self.fill_other, target) +# m_other = mask_or(m_other, domain) +# m = mask_or(m_self, m_other) +# method = getattr(base, self.methodname) +# result = method(target, *args).view(type(instance)) +# try: +# result._mask = m +# except AttributeError: +# if m: +# result = masked +# return result +#............................................................................... +class _arraymethod(object): + """Defines a wrapper for basic array methods. +Upon call, returns a masked array, where the new `_data` array is the output +of the corresponding method called on the original `_data`. + +If `onmask` is True, the new mask is the output of the method calld on the initial mask. +If `onmask` is False, the new mask is just a reference to the initial mask. + +:Parameters: + `funcname` : String + Name of the function to apply on data. + `onmask` : Boolean *[True]* + Whether the mask must be processed also (True) or left alone (False). + """ + def __init__(self, funcname, onmask=True): + self._name = funcname + self._onmask = onmask + self.obj = None + self.__doc__ = self.getdoc() + # + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + methdoc = getattr(ndarray, self._name, None) + methdoc = getattr(numpy, self._name, methdoc) +# methdoc = getattr(MaskedArray, self._name, methdoc) + if methdoc is not None: + return methdoc.__doc__ +# try: +# return getattr(MaskedArray, self._name).__doc__ +# except: +# try: +# return getattr(numpy, self._name).__doc__ +# except: +# return getattr(ndarray, self._name).__doc + # + def __get__(self, obj, objtype=None): + self.obj = obj + return self + # + def __call__(self, *args, **params): + methodname = self._name + data = self.obj._data + mask = self.obj._mask + cls = type(self.obj) + result = getattr(data, methodname)(*args, **params).view(cls) + result._smallmask = self.obj._smallmask + if result.ndim: + if not self._onmask: + result._mask = mask + elif mask is not nomask: + result.__setmask__(getattr(mask, methodname)(*args, **params)) + return result +#.......................................................... + +class flatiter(object): + "Defines an interator." + def __init__(self, ma): + self.ma = ma + self.ma_iter = numpy.asarray(ma).flat + + if ma._mask is nomask: + self.maskiter = None + else: + self.maskiter = ma._mask.flat + + def __iter__(self): + return self + + ### This won't work is ravel makes a copy + def __setitem__(self, index, value): + a = self.ma.ravel() + a[index] = value + + def next(self): + d = self.ma_iter.next() + if self.maskiter is not None and self.maskiter.next(): + d = masked + return d + + +class MaskedArray(numeric.ndarray): + """Arrays with possibly masked values. +Masked values of True exclude the corresponding element from any computation. + +Construction: + x = array(data, dtype=None, copy=True, order=False, + mask = nomask, fill_value=None, small_mask=True) + +If copy=False, every effort is made not to copy the data: +If `data` is a MaskedArray, and argument mask=nomask, then the candidate data +is `data._data` and the mask used is `data._mask`. +If `data` is a numeric array, it is used as the candidate raw data. +If `dtype` is not None and is different from data.dtype.char then a data copy is required. +Otherwise, the candidate is used. + +If a data copy is required, the raw (unmasked) data stored is the result of: +numeric.array(data, dtype=dtype.char, copy=copy) + +If `mask` is `nomask` there are no masked values. +Otherwise mask must be convertible to an array of booleans with the same shape as x. +If `small_mask` is True, a mask consisting of zeros (False) only is compressed to `nomask`. +Otherwise, the mask is not compressed. + +fill_value is used to fill in masked values when necessary, such as when +printing and in method/function filled(). +The fill_value is not used for computation within this module. + """ + __array_priority__ = 10.1 + _defaultmask = nomask + _defaulthardmask = False + _baseclass = numeric.ndarray + def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, fill_value=None, + keep_mask=True, small_mask=True, hard_mask=False, flag=None, + subok=True, **options): + """array(data, dtype=None, copy=True, mask=nomask, fill_value=None) + +If `data` is already a ndarray, its dtype becomes the default value of dtype. + """ + if flag is not None: + warnings.warn("The flag 'flag' is now called 'small_mask'!", + DeprecationWarning) + small_mask = flag + # Process data............ + _data = numeric.array(data, dtype=dtype, copy=copy, subok=subok) + _baseclass = getattr(data, '_baseclass', type(_data)) + _basedict = getattr(data, '_basedict', getattr(data, '__dict__', None)) + if not isinstance(data, MaskedArray): + _data = _data.view(cls) + elif not subok: + _data = data.view(cls) + else: + _data = _data.view(type(data)) + # Backwards compat ....... + if hasattr(data,'_mask') and not isinstance(data, ndarray): + _data._mask = data._mask + _sharedmask = True + # Process mask ........... + if mask is nomask: + if not keep_mask: + _data._mask = nomask + if copy: + _data._mask = _data._mask.copy() + else: + mask = numeric.array(mask, dtype=MaskType, copy=copy) + if mask.shape != _data.shape: + (nd, nm) = (_data.size, mask.size) + if nm == 1: + mask = numeric.resize(mask, _data.shape) + elif nm == nd: + mask = fromnumeric.reshape(mask, _data.shape) + else: + msg = "Mask and data not compatible: data size is %i, "+\ + "mask size is %i." + raise MAError, msg % (nd, nm) + if _data._mask is nomask: + _data._mask = mask + _data._sharedmask = True + else: + # Make a copy of the mask to avoid propagation + _data._sharedmask = False + if not keep_mask: + _data._mask = mask + else: + _data._mask = umath.logical_or(mask, _data._mask) + + + # Update fill_value....... + _data._fill_value = getattr(data, '_fill_value', fill_value) + if _data._fill_value is None: + _data._fill_value = default_fill_value(_data) + # Process extra options .. + _data._hardmask = hard_mask + _data._smallmask = small_mask + _data._baseclass = _baseclass + _data._basedict = _basedict + return _data + #........................ + def __array_finalize__(self,obj): + """Finalizes the masked array. + """ + # Finalize mask ............... + self._mask = getattr(obj, '_mask', nomask) + if self._mask is not nomask: + self._mask.shape = self.shape + # Get the remaining options ... + self._hardmask = getattr(obj, '_hardmask', self._defaulthardmask) + self._smallmask = getattr(obj, '_smallmask', True) + self._sharedmask = True + self._baseclass = getattr(obj, '_baseclass', type(obj)) + self._fill_value = getattr(obj, '_fill_value', None) + # Update special attributes ... + self._basedict = getattr(obj, '_basedict', getattr(obj, '__dict__', None)) + if self._basedict is not None: + self.__dict__.update(self._basedict) + return + #.................................. + def __array_wrap__(self, obj, context=None): + """Special hook for ufuncs. +Wraps the numpy array and sets the mask according to context. + """ + #TODO : Should we check for type result + result = obj.view(type(self)) + #.......... + if context is not None: + result._mask = result._mask.copy() + (func, args, _) = context + m = reduce(mask_or, [getmask(arg) for arg in args]) + # Get domain mask + domain = ufunc_domain.get(func, None) + if domain is not None: + if len(args) > 2: + d = reduce(domain, args) + else: + d = domain(*args) + if m is nomask: + if d is not nomask: + m = d + else: + m |= d + if not m.ndim and m: + if m: + if result.shape == (): + return masked + result._mask = numeric.ones(result.shape, bool_) + else: + result._mask = m + #.... +# result._mask = m + result._fill_value = self._fill_value + result._hardmask = self._hardmask + result._smallmask = self._smallmask + result._baseclass = self._baseclass + return result + #............................................. + def __getitem__(self, indx): + """x.__getitem__(y) <==> x[y] +Returns the item described by i. Not a copy as in previous versions. + """ + # This test is useful, but we should keep things light... +# if getmask(indx) is not nomask: +# msg = "Masked arrays must be filled before they can be used as indices!" +# raise IndexError, msg + # super() can't work here if the underlying data is a matrix... + dout = (self._data).__getitem__(indx) + m = self._mask + if hasattr(dout, 'shape') and len(dout.shape) > 0: + # Not a scalar: make sure that dout is a MA + dout = dout.view(type(self)) + dout._smallmask = self._smallmask + if m is not nomask: + # use _set_mask to take care of the shape + dout.__setmask__(m[indx]) + elif m is not nomask and m[indx]: + return masked + return dout + #........................ + def __setitem__(self, indx, value): + """x.__setitem__(i, y) <==> x[i]=y +Sets item described by index. If value is masked, masks those locations. + """ + if self is masked: + raise MAError, 'Cannot alter the masked element.' +# if getmask(indx) is not nomask: +# msg = "Masked arrays must be filled before they can be used as indices!" +# raise IndexError, msg + #.... + if value is masked: + m = self._mask + if m is nomask: + m = make_mask_none(self.shape) +# else: +# m = m.copy() + m[indx] = True + self.__setmask__(m) + return + #.... + dval = numeric.asarray(value).astype(self.dtype) + valmask = getmask(value) + if self._mask is nomask: + if valmask is not nomask: + self._mask = make_mask_none(self.shape) + self._mask[indx] = valmask + elif not self._hardmask: + _mask = self._mask.copy() + if valmask is nomask: + _mask[indx] = False + else: + _mask[indx] = valmask + self._set_mask(_mask) + elif hasattr(indx, 'dtype') and (indx.dtype==bool_): + indx = indx * umath.logical_not(self._mask) + else: + mindx = mask_or(self._mask[indx], valmask, copy=True) + dindx = self._data[indx] + if dindx.size > 1: + dindx[~mindx] = dval + elif mindx is nomask: + dindx = dval + dval = dindx + self._mask[indx] = mindx + # Set data .......... + #dval = filled(value).astype(self.dtype) + ndarray.__setitem__(self._data,indx,dval) + #............................................ + def __getslice__(self, i, j): + """x.__getslice__(i, j) <==> x[i:j] +Returns the slice described by i, j. +The use of negative indices is not supported.""" + return self.__getitem__(slice(i,j)) + #........................ + def __setslice__(self, i, j, value): + """x.__setslice__(i, j, value) <==> x[i:j]=value +Sets a slice i:j to `value`. +If `value` is masked, masks those locations.""" + self.__setitem__(slice(i,j), value) + #............................................ + def __setmask__(self, mask, copy=False): + newmask = make_mask(mask, copy=copy, small_mask=self._smallmask) +# self.unshare_mask() + if self._mask is nomask: + self._mask = newmask + elif self._hardmask: + if newmask is not nomask: + self._mask.__ior__(newmask) + else: + # This one is tricky: if we set the mask that way, we may break the + # propagation. But if we don't, we end up with a mask full of False + # and a test on nomask fails... + if newmask is nomask: + self._mask = nomask + else: + self._mask.flat = newmask + if self._mask.shape: + self._mask = numeric.reshape(self._mask, self.shape) + _set_mask = __setmask__ + + def _get_mask(self): + """Returns the current mask.""" + return self._mask + + mask = property(fget=_get_mask, fset=__setmask__, doc="Mask") + #............................................ + def harden_mask(self): + "Forces the mask to hard." + self._hardmask = True + + def soften_mask(self): + "Forces the mask to soft." + self._hardmask = False + + def unshare_mask(self): + "Copies the mask and set the sharedmask flag to False." + if self._sharedmask: + self._mask = self._mask.copy() + self._sharedmask = False + + #............................................ + def _get_data(self): + "Returns the current data (as a view of the original underlying data)>" + return self.view(self._baseclass) + _data = property(fget=_get_data) + #............................................ + def _get_flat(self): + """Calculates the flat value. + """ + return flatiter(self) + # + def _set_flat (self, value): + "x.flat = value" + y = self.ravel() + y[:] = value + # + flat = property(fget=_get_flat, fset=_set_flat, doc="Flat version") + #............................................ + def get_fill_value(self): + "Returns the filling value." + if self._fill_value is None: + self._fill_value = default_fill_value(self) + return self._fill_value + + def set_fill_value(self, value=None): + """Sets the filling value to `value`. +If None, uses the default, based on the data type.""" + if value is None: + value = default_fill_value(self) + self._fill_value = value + + fill_value = property(fget=get_fill_value, fset=set_fill_value, + doc="Filling value") + + def filled(self, fill_value=None): + """Returns an array of the same class as `_data`, + with masked values filled with `fill_value`. +Subclassing is preserved. + +If `fill_value` is None, uses self.fill_value. + """ + m = self._mask + if m is nomask or not m.any(): + return self._data + # + if fill_value is None: + fill_value = self.fill_value + # + if self is masked_singleton: + result = numeric.asanyarray(fill_value) + else: + result = self._data.copy() + try: + numpy.putmask(result, m, fill_value) + #result[m] = fill_value + except (TypeError, AttributeError): + fill_value = numeric.array(fill_value, dtype=object) + d = result.astype(object) + result = fromnumeric.choose(m, (d, fill_value)) + except IndexError: + #ok, if scalar + if self._data.shape: + raise + elif m: + result = numeric.array(fill_value, dtype=self.dtype) + else: + result = self._data + return result + + def compressed(self): + "A 1-D array of all the non-masked data." + d = self.ravel() + if self._mask is nomask: + return d + elif not self._smallmask and not self._mask.any(): + return d + else: + return d[numeric.logical_not(d._mask)] + #............................................ + def __str__(self): + """x.__str__() <==> str(x) +Calculates the string representation, using masked for fill if it is enabled. +Otherwise, fills with fill value. + """ + if masked_print_option.enabled(): + f = masked_print_option + if self is masked: + return str(f) + m = self._mask + if m is nomask: + res = self._data + else: + if m.shape == (): + if m: + return str(f) + else: + return str(self._data) + # convert to object array to make filled work +#CHECK: the two lines below seem more robust than the self._data.astype +# res = numeric.empty(self._data.shape, object_) +# numeric.putmask(res,~m,self._data) + res = self._data.astype("|O8") + res[m] = f + else: + res = self.filled(self.fill_value) + return str(res) + + def __repr__(self): + """x.__repr__() <==> repr(x) +Calculates the repr representation, using masked for fill if it is enabled. +Otherwise fill with fill value. + """ + with_mask = """\ +masked_%(name)s(data = + %(data)s, + mask = + %(mask)s, + fill_value=%(fill)s) +""" + with_mask1 = """\ +masked_%(name)s(data = %(data)s, + mask = %(mask)s, + fill_value=%(fill)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), + } + #............................................ + def __iadd__(self, other): + "Adds other to self in place." + ndarray.__iadd__(self._data,other) + m = getmask(other) + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + #.... + def __isub__(self, other): + "Subtracts other from self in place." + ndarray.__isub__(self._data,other) + m = getmask(other) + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + #.... + def __imul__(self, other): + "Multiplies self by other in place." + ndarray.__imul__(self._data,other) + m = getmask(other) + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + #.... + def __idiv__(self, other): + "Divides self by other in place." + dom_mask = domain_safe_divide().__call__(self, filled(other,1)) + other_mask = getmask(other) + new_mask = mask_or(other_mask, dom_mask) + ndarray.__idiv__(self._data, other) + self._mask = mask_or(self._mask, new_mask) + return self + #............................................ + def __float__(self): + "Converts self to float." + if self._mask is not nomask: + warnings.warn("Warning: converting a masked element to nan.") + return numpy.nan + #raise MAError, 'Cannot convert masked element to a Python float.' + return float(self.item()) + + def __int__(self): + "Converts self to int." + if self._mask is not nomask: + raise MAError, 'Cannot convert masked element to a Python int.' + return int(self.item()) + #............................................ + def count(self, axis=None): + """Counts the non-masked elements of the array along a given axis, +and returns a masked array where the mask is True where all data are masked. +If `axis` is None, counts all the non-masked elements, and returns either a +scalar or the masked singleton.""" + m = self._mask + s = self.shape + ls = len(s) + if m is nomask: + if ls == 0: + return 1 + if ls == 1: + return s[0] + if axis is None: + return self.size + else: + n = s[axis] + t = list(s) + del t[axis] + return numeric.ones(t) * n + n1 = fromnumeric.size(m, axis) + n2 = m.astype(int_).sum(axis) + if axis is None: + return (n1-n2) + else: + return masked_array(n1 - n2) + #............................................ + def reshape (self, *s): + """Reshapes the array to shape s. +Returns a new masked array. +If you want to modify the shape in place, please use `a.shape = s`""" + result = self._data.reshape(*s).view(type(self)) + result.__dict__.update(self.__dict__) + if result._mask is not nomask: + result._mask = self._mask.copy() + result._mask.shape = result.shape + return result + # + repeat = _arraymethod('repeat') + # + def resize(self, newshape, refcheck=True, order=False): + """Attempts to modify size and shape of self inplace. + The array must own its own memory and not be referenced by other arrays. + Returns None. + """ + try: + self._data.resize(newshape, refcheck, order) + if self.mask is not nomask: + self._mask.resize(newshape, refcheck, order) + except ValueError: + raise ValueError("Cannot resize an array that has been referenced " + "or is referencing another array in this way.\n" + "Use the resize function.") + return None + # + flatten = _arraymethod('flatten') + # + def put(self, indices, values, mode='raise'): + """Sets storage-indexed locations to corresponding values. +a.put(values, indices, mode) sets a.flat[n] = values[n] for each n in indices. +`values` can be scalar or an array shorter than indices, and it will be repeated, +if necessary. +If `values` has some masked values, the initial mask is updated in consequence, +else the corresponding values are unmasked. + """ + m = self._mask + # Hard mask: Get rid of the values/indices that fall on masked data + if self._hardmask and self._mask is not nomask: + mask = self._mask[indices] + indices = numeric.asarray(indices) + values = numeric.asanyarray(values) + values.resize(indices.shape) + indices = indices[~mask] + values = values[~mask] + #.... + self._data.put(indices, values, mode=mode) + #.... + if m is nomask: + m = getmask(values) + else: + m = m.copy() + if getmask(values) is nomask: + m.put(indices, False, mode=mode) + else: + m.put(indices, values._mask, mode=mode) + m = make_mask(m, copy=False, small_mask=True) + self._mask = m + #............................................ + def ids (self): + """Return the address of the data and mask areas.""" + return (self.ctypes.data, self._mask.ctypes.data) + #............................................ + def all(self, axis=None, out=None): + """a.all(axis) returns True if all entries along the axis are True. + Returns False otherwise. If axis is None, uses the flatten array. + Masked data are considered as True during computation. + Outputs a masked array, where the mask is True if all data are masked along the axis. + Note: the out argument is not really operational... + """ + d = self.filled(True).all(axis=axis, out=out).view(type(self)) + if d.ndim > 0: + d.__setmask__(self._mask.all(axis)) + return d + + def any(self, axis=None, out=None): + """a.any(axis) returns True if some or all entries along the axis are True. + Returns False otherwise. If axis is None, uses the flatten array. + Masked data are considered as False during computation. + Outputs a masked array, where the mask is True if all data are masked along the axis. + Note: the out argument is not really operational... + """ + d = self.filled(False).any(axis=axis, out=out).view(type(self)) + if d.ndim > 0: + d.__setmask__(self._mask.all(axis)) + return d + + def nonzero(self): + """a.nonzero() returns a tuple of arrays + + Returns a tuple of arrays, one for each dimension of a, + containing the indices of the non-zero elements in that + dimension. The corresponding non-zero values can be obtained + with + a[a.nonzero()]. + + To group the indices by element, rather than dimension, use + transpose(a.nonzero()) + instead. The result of this is always a 2d array, with a row for + each non-zero element.""" + return numeric.asarray(self.filled(0)).nonzero() + #............................................ + def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): + """a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) +Returns the sum along the offset diagonal of the array's indicated `axis1` and `axis2`. + """ + # TODO: What are we doing with `out`? + m = self._mask + if m is nomask: + result = super(MaskedArray, self).trace(offset=offset, axis1=axis1, + axis2=axis2, out=out) + return result.astype(dtype) + else: + D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) + return D.astype(dtype).sum(axis=None) + #............................................ + def sum(self, axis=None, dtype=None): + """a.sum(axis=None, dtype=None) +Sums the array `a` over the given axis `axis`. +Masked values are set to 0. +If `axis` is None, applies to a flattened version of the array. + """ + if self._mask is nomask: + mask = nomask + else: + mask = self._mask.all(axis) + if (not mask.ndim) and mask: + return masked + result = self.filled(0).sum(axis, dtype=dtype).view(type(self)) + if result.ndim > 0: + result.__setmask__(mask) + return result + + def cumsum(self, axis=None, dtype=None): + """a.cumprod(axis=None, dtype=None) +Returns the cumulative sum of the elements of array `a` along the given axis `axis`. +Masked values are set to 0. +If `axis` is None, applies to a flattened version of the array. + """ + result = self.filled(0).cumsum(axis=axis, dtype=dtype).view(type(self)) + result.__setmask__(self.mask) + return result + + def prod(self, axis=None, dtype=None): + """a.prod(axis=None, dtype=None) +Returns the product of the elements of array `a` along the given axis `axis`. +Masked elements are set to 1. +If `axis` is None, applies to a flattened version of the array. + """ + if self._mask is nomask: + mask = nomask + else: + mask = self._mask.all(axis) + if (not mask.ndim) and mask: + return masked + result = self.filled(1).prod(axis=axis, dtype=dtype).view(type(self)) + if result.ndim: + result.__setmask__(mask) + return result + product = prod + + def cumprod(self, axis=None, dtype=None): + """a.cumprod(axis=None, dtype=None) +Returns the cumulative product of ethe lements of array `a` along the given axis `axis`. +Masked values are set to 1. +If `axis` is None, applies to a flattened version of the array. + """ + result = self.filled(1).cumprod(axis=axis, dtype=dtype).view(type(self)) + result.__setmask__(self.mask) + return result + + def mean(self, axis=None, dtype=None): + """a.mean(axis=None, dtype=None) + + Averages the array over the given axis. If the axis is None, + averages over all dimensions of the array. Equivalent to + + a.sum(axis, dtype) / size(a, axis). + + The optional dtype argument is the data type for intermediate + calculations in the sum. + + Returns a masked array, of the same class as a. + """ + if self._mask is nomask: + return super(MaskedArray, self).mean(axis=axis, dtype=dtype) + else: + dsum = self.sum(axis=axis, dtype=dtype) + cnt = self.count(axis=axis) + return dsum*1./cnt + + def anom(self, axis=None, dtype=None): + """a.anom(axis=None, dtype=None) + Returns the anomalies, or deviation from the average. + """ + m = self.mean(axis, dtype) + if not axis: + return (self - m) + else: + return (self - expand_dims(m,axis)) + + def var(self, axis=None, dtype=None): + """a.var(axis=None, dtype=None) +Returns the variance, a measure of the spread of a distribution. + +The variance is the average of the squared deviations from the mean, +i.e. var = mean((x - x.mean())**2). + """ + if self._mask is nomask: + # TODO: Do we keep super, or var _data and take a view ? + return super(MaskedArray, self).var(axis=axis, dtype=dtype) + else: + cnt = self.count(axis=axis) + danom = self.anom(axis=axis, dtype=dtype) + danom *= danom + dvar = numeric.array(danom.sum(axis) / cnt).view(type(self)) + if axis is not None: + dvar._mask = mask_or(self._mask.all(axis), (cnt==1)) + return dvar + + def std(self, axis=None, dtype=None): + """a.std(axis=None, dtype=None) +Returns the standard deviation, a measure of the spread of a distribution. + +The standard deviation is the square root of the average of the squared +deviations from the mean, i.e. std = sqrt(mean((x - x.mean())**2)). + """ + dvar = self.var(axis,dtype) + if axis is not None or dvar is not masked: + dvar = sqrt(dvar) + return dvar + #............................................ + def argsort(self, axis=None, fill_value=None, kind='quicksort', + order=None): + """Returns an array of indices that sort 'a' along the specified axis. + Masked values are filled beforehand to `fill_value`. + If `fill_value` is None, uses the default for the data type. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `kind` : String *['quicksort']* + Sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + + Returns: array of indices that sort 'a' along the specified axis. + + This method executes an indirect sort along the given axis using the + algorithm specified by the kind keyword. It returns an array of indices of + the same shape as 'a' that index data along the given axis in sorted order. + + The various sorts are characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order. The three + available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is not + along the last axis. Consequently, sorts along the last axis are faster and use + less space than sorts along other axis. + """ + if fill_value is None: + fill_value = default_fill_value(self) + d = self.filled(fill_value).view(ndarray) + return d.argsort(axis=axis, kind=kind, order=order) + #........................ + def argmin(self, axis=None, fill_value=None): + """Returns a ndarray of indices for the minimum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the minimum default for the data type. + """ + if fill_value is None: + fill_value = minimum_fill_value(self) + d = self.filled(fill_value).view(ndarray) + return d.argmin(axis) + #........................ + def argmax(self, axis=None, fill_value=None): + """Returns the array of indices for the maximum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the maximum default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = maximum_fill_value(self._data) + d = self.filled(fill_value).view(ndarray) + return d.argmax(axis) + + def sort(self, axis=-1, kind='quicksort', order=None, + endwith=True, fill_value=None): + """ + Sort a along the given axis. + + Keyword arguments: + + axis -- axis to be sorted (default -1) + kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. + order -- If a has fields defined, then the order keyword can be the + field name to sort on or a list (or tuple) of field names + to indicate the order that fields should be used to define + the sort. + endwith--Boolean flag indicating whether missing values (if any) should + be forced in the upper indices (at the end of the array) or + lower indices (at the beginning). + + Returns: None. + + This method sorts 'a' in place along the given axis using the algorithm + specified by the kind keyword. + + The various sorts may characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order and is most + useful when used with argsort where the key might differ from the items + being sorted. The three available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + """ + if self._mask is nomask: + ndarray.sort(self,axis=axis, kind=kind, order=order) + else: + if fill_value is None: + if endwith: + filler = minimum_fill_value(self) + else: + filler = maximum_fill_value(self) + else: + filler = fill_value + idx = numpy.indices(self.shape) + idx[axis] = self.filled(filler).argsort(axis=axis,kind=kind,order=order) + idx_l = idx.tolist() + tmp_mask = self._mask[idx_l].flat + tmp_data = self._data[idx_l].flat + self.flat = tmp_data + self._mask.flat = tmp_mask + return + #............................................ + def min(self, axis=None, fill_value=None): + """Returns the minimum/a along the given axis. +If `axis` is None, applies to the flattened array. Masked values are filled +with `fill_value` during processing. If `fill_value is None, it is set to the +maximum_fill_value corresponding to the data type.""" + mask = self._mask + # Check all/nothing case ...... + if mask is nomask: + return super(MaskedArray, self).min(axis=axis) + elif (not mask.ndim) and mask: + return masked + # Get the mask ................ + if axis is None: + mask = umath.logical_and.reduce(mask.flat) + else: + mask = umath.logical_and.reduce(mask, axis=axis) + # Get the fil value ........... + if fill_value is None: + fill_value = minimum_fill_value(self) + # Get the data ................ + result = self.filled(fill_value).min(axis=axis).view(type(self)) + if result.ndim > 0: + result._mask = mask + return result + #........................ + def max(self, axis=None, fill_value=None): + """Returns the maximum/a along the given axis. +If `axis` is None, applies to the flattened array. Masked values are filled +with `fill_value` during processing. If `fill_value is None, it is set to the +maximum_fill_value corresponding to the data type.""" + mask = self._mask + # Check all/nothing case ...... + if mask is nomask: + return super(MaskedArray, self).max(axis=axis) + elif (not mask.ndim) and mask: + return masked + # Check the mask .............. + if axis is None: + mask = umath.logical_and.reduce(mask.flat) + else: + mask = umath.logical_and.reduce(mask, axis=axis) + # Get the fill value .......... + if fill_value is None: + fill_value = maximum_fill_value(self) + # Get the data ................ + result = self.filled(fill_value).max(axis=axis).view(type(self)) + if result.ndim > 0: + result._mask = mask + return result + #........................ + def ptp(self, axis=None, fill_value=None): + """Returns the visible data range (max-min) along the given axis. +If the axis is `None`, applies on a flattened array. Masked values are filled +with `fill_value` for processing. If `fill_value` is None, the maximum is uses +the maximum default, the minimum uses the minimum default.""" + return self.max(axis, fill_value) - self.min(axis, fill_value) + + # Array methods --------------------------------------- + conj = conjugate = _arraymethod('conjugate') + copy = _arraymethod('copy') + diagonal = _arraymethod('diagonal') + take = _arraymethod('take') + ravel = _arraymethod('ravel') + transpose = _arraymethod('transpose') + T = property(fget=lambda self:self.transpose()) + swapaxes = _arraymethod('swapaxes') + clip = _arraymethod('clip', onmask=False) + compress = _arraymethod('compress') + copy = _arraymethod('copy') + squeeze = _arraymethod('squeeze') + #-------------------------------------------- + def tolist(self, fill_value=None): + """Copies the data portion of the array to a hierarchical python list and + returns that list. Data items are converted to the nearest compatible Python + type. + Masked values are converted to `fill_value`. If `fill_value` is None, the + corresponding entries in the output list will be None. + """ + if fill_value is not None: + return self.filled(fill_value).tolist() + result = self.filled().tolist() + if self._mask is nomask: + return result + if self.ndim == 0: + return [None] + elif self.ndim == 1: + maskedidx = self._mask.nonzero()[0].tolist() + [operator.setitem(result,i,None) for i in maskedidx] + else: + for idx in zip(*[i.tolist() for i in self._mask.nonzero()]): + tmp = result + for i in idx[:-1]: + tmp = tmp[i] + tmp[idx[-1]] = None + return result + + + #........................ + def tostring(self, fill_value=None): + """a.tostring(order='C', fill_value=None) -> raw copy of array data as a Python string. + + Keyword arguments: + order : order of the data item in the copy {"C","F","A"} (default "C") + fill_value : value used in lieu of missing data + + Construct a Python string containing the raw bytes in the array. The order + of the data in arrays with ndim > 1 is specified by the 'order' keyword and + this keyword overrides the order of the array. The + choices are: + + "C" -- C order (row major) + "Fortran" -- Fortran order (column major) + "Any" -- Current order of array. + None -- Same as "Any" + + Masked data are filled with fill_value. If fill_value is None, the data-type- + dependent default is used.""" + return self.filled(fill_value).tostring() + #-------------------------------------------- + # Backwards Compatibility. Heck... + @property + def data(self): + """Returns the `_data` part of the MaskedArray.""" + return self._data + def raw_data(self): + """Returns the `_data` part of the MaskedArray. +You should really use `data` instead...""" + return self._data + #-------------------------------------------- + # Pickling + def __getstate__(self): + "Returns the internal state of the masked array, for pickling purposes." + state = (1, + self.shape, + self.dtype, + self.flags.fnc, + self._data.tostring(), + getmaskarray(self).tostring(), + self._fill_value, + ) + return state + # + def __setstate__(self, state): + """Restores the internal state of the masked array, for pickling purposes. + `state` is typically the output of the ``__getstate__`` output, and is a 5-tuple: + + - class name + - a tuple giving the shape of the data + - a typecode for the data + - a binary string for the data + - a binary string for the mask. + """ + (ver, shp, typ, isf, raw, msk, flv) = state + ndarray.__setstate__(self, (shp, typ, isf, raw)) + self._mask.__setstate__((shp, dtype(bool), isf, msk)) + self.fill_value = flv + # + def __reduce__(self): + """Returns a 3-tuple for pickling a MaskedArray.""" + return (_mareconstruct, + (self.__class__, self._baseclass, (0,), 'b', ), + self.__getstate__()) + + +def _mareconstruct(subtype, baseclass, baseshape, basetype,): + """Internal function that builds a new MaskedArray from the information stored +in a pickle.""" + _data = ndarray.__new__(baseclass, baseshape, basetype) + _mask = ndarray.__new__(ndarray, baseshape, 'b1') + return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype, small_mask=False) +#MaskedArray.__dump__ = dump +#MaskedArray.__dumps__ = dumps + + + +#####-------------------------------------------------------------------------- +#---- --- Shortcuts --- +#####--------------------------------------------------------------------------- +def isMaskedArray(x): + "Is x a masked array, that is, an instance of MaskedArray?" + return isinstance(x, MaskedArray) +isarray = isMaskedArray +isMA = isMaskedArray #backward compatibility +#masked = MaskedArray(0, int, mask=1) +masked_singleton = MaskedArray(0, dtype=int_, mask=True) +masked = masked_singleton + +masked_array = MaskedArray +def array(data, dtype=None, copy=False, order=False, mask=nomask, subok=True, + keep_mask=True, small_mask=True, hard_mask=None, fill_value=None): + """array(data, dtype=None, copy=True, order=False, mask=nomask, + keep_mask=True, small_mask=True, fill_value=None) +Acts as shortcut to MaskedArray, with options in a different order for convenience. +And backwards compatibility... + """ + #TODO: we should try to put 'order' somwehere + return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, + keep_mask=keep_mask, small_mask=small_mask, + hard_mask=hard_mask, fill_value=fill_value) + +def is_masked(x): + """Returns whether x has some masked values.""" + m = getmask(x) + if m is nomask: + return False + elif m.any(): + return True + return False + + +#####--------------------------------------------------------------------------- +#---- --- Extrema functions --- +#####--------------------------------------------------------------------------- +class _extrema_operation(object): + "Generic class for maximum/minimum functions." + def __call__(self, a, b=None): + "Executes the call behavior." + if b is None: + return self.reduce(a) + return where(self.compare(a, b), a, b) + #......... + def reduce(self, target, axis=None): + """Reduces target along the given axis.""" + m = getmask(target) + if axis is not None: + kargs = { 'axis' : axis } + else: + kargs = {} + target = target.ravel() + if not (m is nomask): + m = m.ravel() + if m is nomask: + t = self.ufunc.reduce(target, **kargs) + else: + target = target.filled(self.fill_value_func(target)).view(type(target)) + t = self.ufunc.reduce(target, **kargs) + m = umath.logical_and.reduce(m, **kargs) + if hasattr(t, '_mask'): + t._mask = m + elif m: + t = masked + return t + #......... + def outer (self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = logical_or.outer(ma, mb) + result = self.ufunc.outer(filled(a), filled(b)) + result._mask = m + return result +#............................ +class _minimum_operation(_extrema_operation): + "Object to calculate minima" + def __init__ (self): + """minimum(a, b) or minimum(a) +In one argument case, returns the scalar minimum. + """ + self.ufunc = umath.minimum + self.afunc = amin + self.compare = less + self.fill_value_func = minimum_fill_value +#............................ +class _maximum_operation(_extrema_operation): + "Object to calculate maxima" + def __init__ (self): + """maximum(a, b) or maximum(a) + In one argument case returns the scalar maximum. + """ + self.ufunc = umath.maximum + self.afunc = amax + self.compare = greater + self.fill_value_func = maximum_fill_value +#.......................................................... +def min(array, axis=None, out=None): + """Returns the minima along the given axis. +If `axis` is None, applies to the flattened array.""" + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") + if axis is None: + return minimum(array) + else: + return minimum.reduce(array, axis) +#............................ +def max(obj, axis=None, out=None): + """Returns the maxima along the given axis. +If `axis` is None, applies to the flattened array.""" + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") + if axis is None: + return maximum(obj) + else: + return maximum.reduce(obj, axis) +#............................. +def ptp(obj, axis=None): + """a.ptp(axis=None) = a.max(axis)-a.min(axis)""" + try: + return obj.max(axis)-obj.min(axis) + except AttributeError: + return max(obj, axis=axis) - min(obj, axis=axis) + + +#####--------------------------------------------------------------------------- +#---- --- Definition of functions from the corresponding methods --- +#####--------------------------------------------------------------------------- +class _frommethod: + """Defines functions from existing MaskedArray methods. +:ivar _methodname (String): Name of the method to transform. + """ + def __init__(self, methodname): + self._methodname = methodname + self.__doc__ = self.getdoc() + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + try: + return getattr(MaskedArray, self._methodname).__doc__ + except: + return getattr(numpy, self._methodname).__doc__ + def __call__(self, a, *args, **params): + if isinstance(a, MaskedArray): + return getattr(a, self._methodname).__call__(*args, **params) + #FIXME ---- + #As x is not a MaskedArray, we transform it to a ndarray with asarray + #... and call the corresponding method. + #Except that sometimes it doesn't work (try reshape([1,2,3,4],(2,2))) + #we end up with a "SystemError: NULL result without error in PyObject_Call" + #A dirty trick is then to call the initial numpy function... + method = getattr(fromnumeric.asarray(a), self._methodname) + try: + return method(*args, **params) + except SystemError: + return getattr(numpy,self._methodname).__call__(a, *args, **params) + +all = _frommethod('all') +anomalies = anom = _frommethod('anom') +any = _frommethod('any') +conjugate = _frommethod('conjugate') +ids = _frommethod('ids') +nonzero = _frommethod('nonzero') +diagonal = _frommethod('diagonal') +maximum = _maximum_operation() +mean = _frommethod('mean') +minimum = _minimum_operation () +product = _frommethod('prod') +ptp = _frommethod('ptp') +ravel = _frommethod('ravel') +repeat = _frommethod('repeat') +std = _frommethod('std') +sum = _frommethod('sum') +swapaxes = _frommethod('swapaxes') +take = _frommethod('take') +var = _frommethod('var') + +#.............................................................................. +def power(a, b, third=None): + """Computes a**b elementwise. + Masked values are set to 1.""" + if third is not None: + raise MAError, "3-argument power not supported." + ma = getmask(a) + mb = getmask(b) + m = mask_or(ma, mb) + fa = filled(a, 1) + fb = filled(b, 1) + if fb.dtype.char in typecodes["Integer"]: + return masked_array(umath.power(fa, fb), m) + md = make_mask((fa < 0), small_mask=1) + m = mask_or(m, md) + if m is nomask: + return masked_array(umath.power(fa, fb)) + else: + fa[m] = 1 + return masked_array(umath.power(fa, fb), m) + +#.............................................................................. +def argsort(a, axis=None, kind='quicksort', order=None, fill_value=None): + """Returns an array of indices that sort 'a' along the specified axis. + Masked values are filled beforehand to `fill_value`. + If `fill_value` is None, uses the default for the data type. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `kind` : String *['quicksort']* + Sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + + Returns: array of indices that sort 'a' along the specified axis. + + This method executes an indirect sort along the given axis using the + algorithm specified by the kind keyword. It returns an array of indices of + the same shape as 'a' that index data along the given axis in sorted order. + + The various sorts are characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order. The three + available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is not + along the last axis. Consequently, sorts along the last axis are faster and use + less space than sorts along other axis. + """ + if fill_value is None: + fill_value = default_fill_value(a) + d = filled(a, fill_value) + if axis is None: + return d.argsort(kind=kind, order=order) + return d.argsort(axis, kind=kind, order=order) + +def argmin(a, axis=None, fill_value=None): + """Returns the array of indices for the minimum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = default_fill_value(a) + d = filled(a, fill_value) + return d.argmin(axis=axis) + +def argmax(a, axis=None, fill_value=None): + """Returns the array of indices for the maximum values of `a` along the + specified axis. + Masked values are treated as if they had the value `fill_value`. + If `fill_value` is None, the default for the data type is used. + Returns a numpy array. + +:Keywords: + `axis` : Integer *[None]* + Axis to be indirectly sorted (default -1) + `fill_value` : var *[None]* + Default filling value. If None, uses the data type default. + """ + if fill_value is None: + fill_value = default_fill_value(a) + try: + fill_value = - fill_value + except: + pass + d = filled(a, fill_value) + return d.argmax(axis=axis) + +def sort(a, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None): + """ + Sort a along the given axis. + +Keyword arguments: + +axis -- axis to be sorted (default -1) +kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. +order -- If a has fields defined, then the order keyword can be the + field name to sort on or a list (or tuple) of field names + to indicate the order that fields should be used to define + the sort. +endwith--Boolean flag indicating whether missing values (if any) should + be forced in the upper indices (at the end of the array) or + lower indices (at the beginning). + +Returns: None. + +This method sorts 'a' in place along the given axis using the algorithm +specified by the kind keyword. + +The various sorts may characterized by average speed, worst case +performance, need for work space, and whether they are stable. A stable +sort keeps items with the same key in the same relative order and is most +useful when used with argsort where the key might differ from the items +being sorted. The three available algorithms have the following properties: + +|------------------------------------------------------| +| kind | speed | worst case | work space | stable| +|------------------------------------------------------| +|'quicksort'| 1 | O(n^2) | 0 | no | +|'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | +|'heapsort' | 3 | O(n*log(n)) | 0 | no | +|------------------------------------------------------| + +All the sort algorithms make temporary copies of the data when the sort is +not along the last axis. Consequently, sorts along the last axis are faster +and use less space than sorts along other axis. + +""" + a = numeric.asanyarray(a) + if fill_value is None: + if endwith: + filler = minimum_fill_value(a) + else: + filler = maximum_fill_value(a) + else: + filler = fill_value +# return + indx = numpy.indices(a.shape).tolist() + indx[axis] = filled(a,filler).argsort(axis=axis,kind=kind,order=order) + return a[indx] + +def compressed(x): + """Returns a compressed version of a masked array (or just the array if it + wasn't masked first).""" + if getmask(x) is None: + return x + else: + return x.compressed() + +def count(a, axis = None): + "Count of the non-masked elements in a, or along a certain axis." + a = masked_array(a) + return a.count(axis) + +def concatenate(arrays, axis=0): + "Concatenates the arrays along the given axis" + d = numeric.concatenate([filled(a) for a in arrays], axis) + rcls = get_masked_subclass(*arrays) + data = d.view(rcls) + for x in arrays: + if getmask(x) is not nomask: + break + else: + return data + dm = numeric.concatenate([getmaskarray(a) for a in arrays], axis) + dm = make_mask(dm, copy=False, small_mask=True) + data._mask = dm + return data + +def expand_dims(x,axis): + """Expand the shape of a by including newaxis before given axis.""" + result = n_expand_dims(x,axis) + if isinstance(x, MaskedArray): + new_shape = result.shape + result = x.view() + result.shape = new_shape + if result._mask is not nomask: + result._mask.shape = new_shape + return result + +#...................................... +def left_shift (a, n): + "Left shift n bits" + m = getmask(a) + if m is nomask: + d = umath.left_shift(filled(a), n) + return masked_array(d) + else: + d = umath.left_shift(filled(a, 0), n) + return masked_array(d, mask=m) + +def right_shift (a, n): + "Right shift n bits" + m = getmask(a) + if m is nomask: + d = umath.right_shift(filled(a), n) + return masked_array(d) + else: + d = umath.right_shift(filled(a, 0), n) + return masked_array(d, mask=m) +#...................................... +def put(a, indices, values, mode='raise'): + """Sets storage-indexed locations to corresponding values. + Values and indices are filled if necessary.""" + # We can't use 'frommethod', the order of arguments is different + try: + return a.put(indices, values, mode=mode) + except AttributeError: + return fromnumeric.asarray(a).put(indices, values, mode=mode) + +def putmask(a, mask, values): #, mode='raise'): + """`putmask(a, mask, v)` results in `a = v` for all places where `mask` is true. +If `v` is shorter than `mask`, it will be repeated as necessary. +In particular `v` can be a scalar or length 1 array.""" + # We can't use 'frommethod', the order of arguments is different + try: + return a.putmask(values, mask) + except AttributeError: + return fromnumeric.asarray(a).putmask(values, mask) + +def transpose(a,axes=None): + """Returns a view of the array with dimensions permuted according to axes. +If `axes` is None (default), returns array with dimensions reversed. + """ + #We can't use 'frommethod', as 'transpose' doesn't take keywords + try: + return a.transpose(axes) + except AttributeError: + return fromnumeric.asarray(a).transpose(axes) + +def reshape(a, new_shape): + """Changes the shape of the array `a` to `new_shape`.""" + #We can't use 'frommethod', it whine about some parameters. Dmmit. + try: + return a.reshape(new_shape) + except AttributeError: + return fromnumeric.asarray(a).reshape(new_shape) + +def resize(x, new_shape): + """resize(a,new_shape) returns a new array with the specified shape. + The total size of the original array can be any size. + The new array is filled with repeated copies of a. If a was masked, the new + array will be masked, and the new mask will be a repetition of the old one. + """ + # We can't use _frommethods here, as N.resize is notoriously whiny. + m = getmask(x) + if m is not nomask: + m = fromnumeric.resize(m, new_shape) + result = fromnumeric.resize(x, new_shape).view(get_masked_subclass(x)) + if result.ndim: + result._mask = m + return result + + +#................................................ +def rank(obj): + """Gets the rank of sequence a (the number of dimensions, not a matrix rank) +The rank of a scalar is zero.""" + return fromnumeric.rank(filled(obj)) +# +def shape(obj): + """Returns the shape of `a` (as a function call which also works on nested sequences). + """ + return fromnumeric.shape(filled(obj)) +# +def size(obj, axis=None): + """Returns the number of elements in the array along the given axis, +or in the sequence if `axis` is None. + """ + return fromnumeric.size(filled(obj), axis) +#................................................ + +#####-------------------------------------------------------------------------- +#---- --- Extra functions --- +#####-------------------------------------------------------------------------- +def where (condition, x, y): + """where(condition, x, y) is x where condition is nonzero, y otherwise. + condition must be convertible to an integer array. + Answer is always the shape of condition. + The type depends on x and y. It is integer if both x and y are + the value masked. + """ + fc = filled(not_equal(condition, 0), 0) + xv = filled(x) + xm = getmask(x) + yv = filled(y) + ym = getmask(y) + d = numeric.choose(fc, (yv, xv)) + md = numeric.choose(fc, (ym, xm)) + m = getmask(condition) + m = make_mask(mask_or(m, md), copy=False, small_mask=True) + return masked_array(d, mask=m) + +def choose (indices, t, out=None, mode='raise'): + "Returns array shaped like indices with elements chosen from t" + #TODO: implement options `out` and `mode`, if possible. + def fmask (x): + "Returns the filled array, or True if ``masked``." + if x is masked: + return 1 + return filled(x) + def nmask (x): + "Returns the mask, True if ``masked``, False if ``nomask``." + if x is masked: + return 1 + m = getmask(x) + if m is nomask: + return 0 + return m + c = filled(indices, 0) + masks = [nmask(x) for x in t] + a = [fmask(x) for x in t] + d = numeric.choose(c, a) + m = numeric.choose(c, masks) + m = make_mask(mask_or(m, getmask(indices)), copy=0, small_mask=1) + return masked_array(d, mask=m) + +def round_(a, decimals=0, out=None): + """Returns reference to result. Copies a and rounds to 'decimals' places. + + Keyword arguments: + decimals -- number of decimals to round to (default 0). May be negative. + out -- existing array to use for output (default copy of a). + + Return: + Reference to out, where None specifies a copy of the original array a. + + Round to the specified number of decimals. When 'decimals' is negative it + specifies the number of positions to the left of the decimal point. The + real and imaginary parts of complex numbers are rounded separately. + Nothing is done if the array is not of float type and 'decimals' is greater + than or equal to 0.""" + result = fromnumeric.round_(filled(a), decimals, out) + if isinstance(a,MaskedArray): + result = result.view(type(a)) + result._mask = a._mask + else: + result = result.view(MaskedArray) + return result + +def arange(start, stop=None, step=1, dtype=None): + """Just like range() except it returns a array whose type can be specified + by the keyword argument dtype. + """ + return array(numeric.arange(start, stop, step, dtype),mask=nomask) + +def inner(a, b): + """inner(a,b) returns the dot product of two arrays, which has + shape a.shape[:-1] + b.shape[:-1] with elements computed by summing the + product of the elements from the last dimensions of a and b. + Masked elements are replace by zeros. + """ + fa = filled(a, 0) + fb = filled(b, 0) + if len(fa.shape) == 0: + fa.shape = (1,) + if len(fb.shape) == 0: + fb.shape = (1,) + return masked_array(numeric.inner(fa, fb)) +innerproduct = inner + +def outer(a, b): + """outer(a,b) = {a[i]*b[j]}, has shape (len(a),len(b))""" + fa = filled(a, 0).ravel() + fb = filled(b, 0).ravel() + d = numeric.outer(fa, fb) + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + return masked_array(d) + ma = getmaskarray(a) + mb = getmaskarray(b) + m = make_mask(1-numeric.outer(1-ma, 1-mb), copy=0) + return masked_array(d, mask=m) +outerproduct = outer + +def allequal (a, b, fill_value=True): + """ +Returns `True` if all entries of a and b are equal, using +fill_value as a truth value where either or both are masked. + """ + m = mask_or(getmask(a), getmask(b)) + if m is nomask: + x = filled(a) + y = filled(b) + d = umath.equal(x, y) + return d.all() + elif fill_value: + x = filled(a) + y = filled(b) + d = umath.equal(x, y) + dm = array(d, mask=m, copy=False) + return dm.filled(True).all(None) + else: + return False + +def allclose (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8): + """ Returns `True` if all elements of `a` and `b` are equal subject to given tolerances. +If `fill_value` is True, masked values are considered equal. +If `fill_value` is False, masked values considered unequal. +The relative error rtol should be positive and << 1.0 +The absolute error `atol` comes into play for those elements of `b` + that are very small or zero; it says how small `a` must be also. + """ + m = mask_or(getmask(a), getmask(b)) + d1 = filled(a) + d2 = filled(b) + x = filled(array(d1, copy=0, mask=m), fill_value).astype(float) + y = filled(array(d2, copy=0, mask=m), 1).astype(float) + d = umath.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y)) + return fromnumeric.alltrue(fromnumeric.ravel(d)) + +#.............................................................................. +def asarray(a, dtype=None): + """asarray(data, dtype) = array(data, dtype, copy=0) +Returns `a` as an masked array. +No copy is performed if `a` is already an array. +Subclasses are converted to base class MaskedArray. + """ + return masked_array(a, dtype=dtype, copy=False, keep_mask=True) + +def empty(new_shape, dtype=float): + """empty((d1,...,dn),dtype=float,order='C') +Returns a new array of shape (d1,...,dn) and given type with all its +entries uninitialized. This can be faster than zeros.""" + return numeric.empty(new_shape, dtype).view(MaskedArray) + +def empty_like(a): + """empty_like(a) +Returns an empty (uninitialized) array of the shape and typecode of a. +Note that this does NOT initialize the returned array. +If you require your array to be initialized, you should use zeros_like().""" + return numeric.empty_like(a).view(MaskedArray) + +def ones(new_shape, dtype=float): + """ones(shape, dtype=None) +Returns an array of the given dimensions, initialized to all ones.""" + return numeric.ones(new_shape, dtype).view(MaskedArray) + +def zeros(new_shape, dtype=float): + """zeros(new_shape, dtype=None) +Returns an array of the given dimensions, initialized to all zeros.""" + return numeric.zeros(new_shape, dtype).view(MaskedArray) + +#####-------------------------------------------------------------------------- +#---- --- Pickling --- +#####-------------------------------------------------------------------------- +def dump(a,F): + """Pickles the MaskedArray `a` to the file `F`. +`F` can either be the handle of an exiting file, or a string representing a file name. + """ + if not hasattr(F,'readline'): + F = open(F,'w') + return cPickle.dump(a,F) + +def dumps(a): + """Returns 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.""" + if not hasattr(F, 'readline'): + F = open(F,'r') + return cPickle.load(F) + +def loads(strg): + "Loads a pickle from the current string.""" + return cPickle.loads(strg) + + +################################################################################ + +if __name__ == '__main__': + from testutils import assert_equal, assert_almost_equal + if 1: + narray = numpy.array + pi = numpy.pi + x = narray([1.,1.,1.,-2., pi/2., 4., 5., -10., 10., 1., 2., 3.]) + y = narray([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 = masked_array(x, mask=m1) + ym = masked_array(y, mask=m2) + + # + if 1: + n = [0,0,1,0,1] + m = make_mask(n) + m2 = make_mask(m) + assert(m is m2) + m3 = make_mask(m, copy=1) + assert(m is not m3) + + x1 = numpy.arange(5) + y1 = array(x1, mask=m) + #assert( y1._data is x1) + assert_equal(y1._data.__array_interface__, x1.__array_interface__) + assert( allequal(x1,y1.raw_data())) + #assert( y1.mask is m) + assert_equal(y1._mask.__array_interface__, m.__array_interface__) + + 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) + + 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) + 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)) Added: trunk/scipy/sandbox/maskedarray/alternative_versions/test_mrecarray.py =================================================================== --- trunk/scipy/sandbox/maskedarray/alternative_versions/test_mrecarray.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/alternative_versions/test_mrecarray.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,128 @@ +# pylint: disable-msg=W0611, W0612, W0511,R0201 +"""Tests suite for mrecarray. + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: test_mrecarray.py 68 2007-01-10 17:46:04Z backtopop $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: backtopop $)" +__version__ = '1.0' +__revision__ = "$Revision: 68 $" +__date__ = '$Date: 2007-01-10 12:46:04 -0500 (Wed, 10 Jan 2007) $' + +import types + +import numpy as N +import numpy.core.fromnumeric as fromnumeric +from numpy.testing import NumpyTest, NumpyTestCase +from numpy.testing.utils import build_err_msg + +import maskedarray.testutils +from maskedarray.testutils import * + +import maskedarray.core as MA +import maskedarray.mrecords +from maskedarray.mrecords import mrecarray, fromarrays, fromtextfile, fromrecords + + +#.............................................................................. +class TestMrecarray(NumpyTestCase): + "Base test class for MaskedArrays." + def __init__(self, *args, **kwds): + NumpyTestCase.__init__(self, *args, **kwds) + self.setup() + + def setup(self): + "Generic setup" + d = N.arange(5) + m = MA.make_mask([1,0,0,1,1]) + base_d = N.r_[d,d[::-1]].reshape(2,-1).T + base_m = N.r_[[m, m[::-1]]].T + base = MA.array(base_d, mask=base_m) + mrec = fromarrays(base.T,) + self.data = [d, m, mrec] + + def test_get(self): + "Tests fields retrieval" + [d, m, mrec] = self.data + assert_equal(mrec.f0, MA.array(d,mask=m)) + assert_equal(mrec.f1, MA.array(d[::-1],mask=m[::-1])) + assert((mrec._fieldmask == N.core.records.fromarrays([m, m[::-1]])).all()) + assert_equal(mrec._mask, N.r_[[m,m[::-1]]].all(0)) + assert_equal(mrec.f0, mrec['f0']) + + def test_set(self): + "Tests setting fields/attributes." + [d, m, mrec] = self.data + mrec.f0_data = 5 + assert_equal(mrec['f0_data'], [5,5,5,5,5]) + mrec.f0 = 1 + assert_equal(mrec['f0_data'], [1]*5) + assert_equal(mrec['f0_mask'], [0]*5) + mrec.f1 = MA.masked + assert_equal(mrec.f1.mask, [1]*5) + assert_equal(mrec['f1_mask'], [1]*5) + mrec._mask = MA.masked + assert_equal(mrec['f1_mask'], [1]*5) + assert_equal(mrec['f0_mask'],mrec['f1_mask']) + mrec._mask = MA.nomask + assert_equal(mrec['f1_mask'], [0]*5) + assert_equal(mrec['f0_mask'],mrec['f1_mask']) + + def test_hardmask(self): + "Test hardmask" + [d, m, mrec] = self.data + print mrec._mask + mrec.harden_mask() + assert(mrec._hardmask) + mrec._mask = nomask + assert_equal(mrec._mask, N.r_[[m,m[::-1]]].all(0)) + mrec.soften_mask() + assert(not mrec._hardmask) + mrec._mask = nomask + assert_equal(mrec['f1_mask'], [0]*5) + assert_equal(mrec['f0_mask'],mrec['f1_mask']) + + def test_fromtextfile(self): + "Tests reading from a text file." + fcontent = """# +'One (S)','Two (I)','Three (F)','Four (M)','Five (-)','Six (C)' +'strings',1,1.0,'mixed column',,1 +'with embedded "double quotes"',2,2.0,1.0,,1 +'strings',3,3.0E5,3,,1 +'strings',4,-1e-10,,,1 +""" + import os + from datetime import datetime + fname = 'tmp%s' % datetime.now().strftime("%y%m%d%H%M%S%s") + f = open(fname, 'w') + f.write(fcontent) + f.close() + mrectxt = fromtextfile(fname,delimitor=',',varnames='ABCDEFG') + os.unlink(fname) + # + assert(isinstance(mrectxt, mrecarray)) + 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]) + + def test_fromrecords(self): + "Test from recarray." + [d, m, mrec] = self.data + nrec = N.core.records.fromarrays(N.r_[[d,d[::-1]]]) + mrecfr = fromrecords(nrec.tolist()) + assert_equal(mrecfr.f0, mrec.f0) + assert_equal(mrecfr.dtype, mrec.dtype) + #.................... + mrecfr = fromrecords(nrec) + assert_equal(mrecfr.f0, mrec.f0) + assert_equal(mrecfr.dtype, mrec.dtype) + #.................... + tmp = mrec[::-1] #.tolist() + mrecfr = fromrecords(tmp) + assert_equal(mrecfr.f0, mrec.f0[::-1]) + +############################################################################### +#------------------------------------------------------------------------------ +if __name__ == "__main__": + NumpyTest().run() Added: trunk/scipy/sandbox/maskedarray/bench.py =================================================================== --- trunk/scipy/sandbox/maskedarray/bench.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/bench.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,198 @@ +#! python + +import timeit +#import IPython.ipapi +#ip = IPython.ipapi.get() +#from IPython import ipmagic +import numpy +import maskedarray +from maskedarray import filled +from maskedarray.testutils import assert_equal + + +#####--------------------------------------------------------------------------- +#---- --- Global variables --- +#####--------------------------------------------------------------------------- + +# Small arrays .................................. +xs = numpy.random.uniform(-1,1,6).reshape(2,3) +ys = numpy.random.uniform(-1,1,6).reshape(2,3) +zs = xs + 1j * ys +m1 = [[True, False, False], [False, False, True]] +m2 = [[True, False, True], [False, False, True]] +nmxs = numpy.ma.array(xs, mask=m1) +nmys = numpy.ma.array(ys, mask=m2) +nmzs = numpy.ma.array(zs, mask=m1) +mmxs = maskedarray.array(xs, mask=m1) +mmys = maskedarray.array(ys, mask=m2) +mmzs = maskedarray.array(zs, mask=m1) +# Big arrays .................................... +xl = numpy.random.uniform(-1,1,100*100).reshape(100,100) +yl = numpy.random.uniform(-1,1,100*100).reshape(100,100) +zl = xl + 1j * yl +maskx = xl > 0.8 +masky = yl < -0.8 +nmxl = numpy.ma.array(xl, mask=maskx) +nmyl = numpy.ma.array(yl, mask=masky) +nmzl = numpy.ma.array(zl, mask=maskx) +mmxl = maskedarray.array(xl, mask=maskx, shrink=True) +mmyl = maskedarray.array(yl, mask=masky, shrink=True) +mmzl = maskedarray.array(zl, mask=maskx, shrink=True) + +#####--------------------------------------------------------------------------- +#---- --- Functions --- +#####--------------------------------------------------------------------------- + +def timer(s, v='', nloop=500, nrep=3): + units = ["s", "ms", "\xb5s", "ns"] + scaling = [1, 1e3, 1e6, 1e9] + print "%s : %-50s : " % (v,s), + varnames = ["%ss,nm%ss,mm%ss,%sl,nm%sl,mm%sl" % tuple(x*6) for x in 'xyz'] + setup = 'from __main__ import numpy, maskedarray, %s' % ','.join(varnames) + Timer = timeit.Timer(stmt=s, setup=setup) + best = min(Timer.repeat(nrep, nloop)) / nloop + if best > 0.0: + order = min(-int(numpy.floor(numpy.log10(best)) // 3), 3) + else: + order = 3 + print "%d loops, best of %d: %.*g %s per loop" % (nloop, nrep, + 3, + best * scaling[order], + units[order]) +# ip.magic('timeit -n%i %s' % (nloop,s)) + + + +def compare_functions_1v(func, nloop=500, test=True, + xs=xs, nmxs=nmxs, mmxs=mmxs, + xl=xl, nmxl=nmxl, mmxl=mmxl): + funcname = func.__name__ + print "-"*50 + print "%s on small arrays" % funcname + if test: + assert_equal(filled(eval("numpy.ma.%s(nmxs)" % funcname),0), + filled(eval("maskedarray.%s(mmxs)" % funcname),0)) + for (module, data) in zip(("numpy", "numpy.ma","maskedarray"), + ("xs","nmxs","mmxs")): + timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop) + # + print "%s on large arrays" % funcname + if test: + assert_equal(filled(eval("numpy.ma.%s(nmxl)" % funcname),0), + filled(eval("maskedarray.%s(mmxl)" % funcname),0)) + for (module, data) in zip(("numpy", "numpy.ma","maskedarray"), + ("xl","nmxl","mmxl")): + timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop) + return + +def compare_methods(methodname, args, vars='x', nloop=500, test=True, + xs=xs, nmxs=nmxs, mmxs=mmxs, + xl=xl, nmxl=nmxl, mmxl=mmxl): + print "-"*50 + print "%s on small arrays" % methodname + if test: + assert_equal(filled(eval("nm%ss.%s(%s)" % (vars,methodname,args)),0), + filled(eval("mm%ss.%s(%s)" % (vars,methodname,args)),0)) + for (data, ver) in zip(["nm%ss" % vars, "mm%ss" % vars], ('numpy.ma ','maskedarray')): + timer("%(data)s.%(methodname)s(%(args)s)" % locals(), v=ver, nloop=nloop) + # + print "%s on large arrays" % methodname + if test: + assert_equal(filled(eval("nm%sl.%s(%s)" % (vars,methodname,args)),0), + filled(eval("mm%sl.%s(%s)" % (vars,methodname,args)),0)) + for (data, ver) in zip(["nm%sl" % vars, "mm%sl" % vars], ('numpy.ma ','maskedarray')): + timer("%(data)s.%(methodname)s(%(args)s)" % locals(), v=ver, nloop=nloop) + return + +def compare_functions_2v(func, nloop=500, test=True, + xs=xs, nmxs=nmxs, mmxs=mmxs, + ys=ys, nmys=nmys, mmys=mmys, + xl=xl, nmxl=nmxl, mmxl=mmxl, + yl=yl, nmyl=nmyl, mmyl=mmyl): + funcname = func.__name__ + print "-"*50 + print "%s on small arrays" % funcname + if test: + assert_equal(filled(eval("numpy.ma.%s(nmxs,nmys)" % funcname),0), + filled(eval("maskedarray.%s(mmxs,mmys)" % funcname),0)) + for (module, data) in zip(("numpy", "numpy.ma","maskedarray"), + ("xs,ys","nmxs,nmys","mmxs,mmys")): + timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop) + # + print "%s on large arrays" % funcname + if test: + assert_equal(filled(eval("numpy.ma.%s(nmxl, nmyl)" % funcname),0), + filled(eval("maskedarray.%s(mmxl, mmyl)" % funcname),0)) + for (module, data) in zip(("numpy", "numpy.ma","maskedarray"), + ("xl,yl","nmxl,nmyl","mmxl,mmyl")): + timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop) + return + + +############################################################################### + + +################################################################################ +if __name__ == '__main__': +# # Small arrays .................................. +# xs = numpy.random.uniform(-1,1,6).reshape(2,3) +# ys = numpy.random.uniform(-1,1,6).reshape(2,3) +# zs = xs + 1j * ys +# m1 = [[True, False, False], [False, False, True]] +# m2 = [[True, False, True], [False, False, True]] +# nmxs = numpy.ma.array(xs, mask=m1) +# nmys = numpy.ma.array(ys, mask=m2) +# nmzs = numpy.ma.array(zs, mask=m1) +# mmxs = maskedarray.array(xs, mask=m1) +# mmys = maskedarray.array(ys, mask=m2) +# mmzs = maskedarray.array(zs, mask=m1) +# # Big arrays .................................... +# xl = numpy.random.uniform(-1,1,100*100).reshape(100,100) +# yl = numpy.random.uniform(-1,1,100*100).reshape(100,100) +# zl = xl + 1j * yl +# maskx = xl > 0.8 +# masky = yl < -0.8 +# nmxl = numpy.ma.array(xl, mask=maskx) +# nmyl = numpy.ma.array(yl, mask=masky) +# nmzl = numpy.ma.array(zl, mask=maskx) +# mmxl = maskedarray.array(xl, mask=maskx, shrink=True) +# mmyl = maskedarray.array(yl, mask=masky, shrink=True) +# mmzl = maskedarray.array(zl, mask=maskx, shrink=True) +# + compare_functions_1v(numpy.sin) + compare_functions_1v(numpy.log) + compare_functions_1v(numpy.sqrt) + #.................................................................... + compare_functions_2v(numpy.multiply) + compare_functions_2v(numpy.divide) + compare_functions_2v(numpy.power) + #.................................................................... + compare_methods('ravel','', nloop=1000) + compare_methods('conjugate','','z', nloop=1000) + compare_methods('transpose','', nloop=1000) + compare_methods('compressed','', nloop=1000) + compare_methods('__getitem__','0', nloop=1000) + compare_methods('__getitem__','(0,0)', nloop=1000) + compare_methods('__getitem__','[0,-1]', nloop=1000) + compare_methods('__setitem__','0, 17', nloop=1000, test=False) + compare_methods('__setitem__','(0,0), 17', nloop=1000, test=False) + #.................................................................... + print "-"*50 + print "__setitem__ on small arrays" + timer('nmxs.__setitem__((-1,0),numpy.ma.masked)', 'numpy.ma ',nloop=10000) + timer('mmxs.__setitem__((-1,0),maskedarray.masked)', 'maskedarray',nloop=10000) + print "-"*50 + print "__setitem__ on large arrays" + timer('nmxl.__setitem__((-1,0),numpy.ma.masked)', 'numpy.ma ',nloop=10000) + timer('mmxl.__setitem__((-1,0),maskedarray.masked)', 'maskedarray',nloop=10000) + #.................................................................... + print "-"*50 + print "where on small arrays" + assert_equal(eval("numpy.ma.where(nmxs>2,nmxs,nmys)"), + eval("maskedarray.where(mmxs>2, mmxs,mmys)")) + timer('numpy.ma.where(nmxs>2,nmxs,nmys)', 'numpy.ma ',nloop=1000) + timer('maskedarray.where(mmxs>2, mmxs,mmys)', 'maskedarray',nloop=1000) + print "-"*50 + print "where on large arrays" + timer('numpy.ma.where(nmxl>2,nmxl,nmyl)', 'numpy.ma ',nloop=100) + timer('maskedarray.where(mmxl>2, mmxl,mmyl)', 'maskedarray',nloop=100) Added: trunk/scipy/sandbox/maskedarray/core.py =================================================================== --- trunk/scipy/sandbox/maskedarray/core.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/core.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,2979 @@ +# pylint: disable-msg=E1002 +"""MA: a facility for dealing with missing observations +MA is generally used as a numpy.array look-alike. +by Paul F. Dubois. + +Copyright 1999, 2000, 2001 Regents of the University of California. +Released for unlimited redistribution. +Adapted for numpy_core 2005 by Travis Oliphant and +(mainly) Paul Dubois. + +Subclassing of the base ndarray 2006 by Pierre Gerard-Marchant. +pgmdevlist_AT_gmail_DOT_com +Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com) + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: core.py 3639 2007-12-13 03:39:17Z pierregm $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: pierregm $)" +__version__ = '1.0' +__revision__ = "$Revision: 3639 $" +__date__ = '$Date: 2007-12-12 19:39:17 -0800 (Wed, 12 Dec 2007) $' + +__docformat__ = "restructuredtext en" + +__all__ = ['MAError', 'MaskType', 'MaskedArray', + 'bool_', 'complex_', 'float_', 'int_', 'object_', + 'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue', + 'amax', 'amin', 'anom', 'anomalies', 'any', 'arange', + 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', + 'arctanh', 'argmax', 'argmin', 'argsort', 'around', + 'array', 'asarray','asanyarray', + 'bitwise_and', 'bitwise_or', 'bitwise_xor', + 'ceil', 'choose', 'compressed', 'concatenate', 'conjugate', + 'cos', 'cosh', 'count', + 'default_fill_value', 'diagonal', 'divide', 'dump', 'dumps', + 'empty', 'empty_like', 'equal', 'exp', + 'fabs', 'fmod', 'filled', 'floor', 'floor_divide','fix_invalid', + 'getmask', 'getmaskarray', 'greater', 'greater_equal', 'hypot', + 'ids', 'inner', 'innerproduct', + 'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', + 'left_shift', 'less', 'less_equal', 'load', 'loads', 'log', 'log10', + 'logical_and', 'logical_not', 'logical_or', 'logical_xor', + 'make_mask', 'make_mask_none', 'mask_or', 'masked', + 'masked_array', 'masked_equal', 'masked_greater', + 'masked_greater_equal', 'masked_inside', 'masked_less', + 'masked_less_equal', 'masked_not_equal', 'masked_object', + 'masked_outside', 'masked_print_option', 'masked_singleton', + 'masked_values', 'masked_where', 'max', 'maximum', 'mean', 'min', + 'minimum', 'multiply', + 'negative', 'nomask', 'nonzero', 'not_equal', + 'ones', 'outer', 'outerproduct', + 'power', 'product', 'ptp', 'put', 'putmask', + 'rank', 'ravel', 'remainder', 'repeat', 'reshape', 'resize', + 'right_shift', 'round_', + 'shape', 'sin', 'sinh', 'size', 'sometrue', 'sort', 'sqrt', 'std', + 'subtract', 'sum', 'swapaxes', + 'take', 'tan', 'tanh', 'transpose', 'true_divide', + 'var', 'where', + 'zeros'] + +import sys +import types +import cPickle +import operator +# +import numpy +from numpy import bool_, complex_, float_, int_, object_, str_ + +import numpy.core.umath as umath +import numpy.core.fromnumeric as fromnumeric +import numpy.core.numeric as numeric +import numpy.core.numerictypes as ntypes +from numpy import bool_, dtype, typecodes, amax, amin, ndarray +from numpy import expand_dims as n_expand_dims +from numpy import array as narray +import warnings + + +MaskType = bool_ +nomask = MaskType(0) + +divide_tolerance = 1.e-35 +numpy.seterr(all='ignore') + + + +#####-------------------------------------------------------------------------- +#---- --- Exceptions --- +#####-------------------------------------------------------------------------- +class MAError(Exception): + "Class for MA related errors." + def __init__ (self, args=None): + "Creates an exception." + Exception.__init__(self,args) + self.args = args + def __str__(self): + "Calculates the string representation." + return str(self.args) + __repr__ = __str__ + +#####-------------------------------------------------------------------------- +#---- --- Filling options --- +#####-------------------------------------------------------------------------- +# b: boolean - c: complex - f: floats - i: integer - O: object - S: string +default_filler = {'b': True, + 'c' : 1.e20 + 0.0j, + 'f' : 1.e20, + 'i' : 999999, + 'O' : '?', + 'S' : 'N/A', + 'u' : 999999, + 'V' : '???', + } +max_filler = ntypes._minvals +max_filler.update([(k,-numpy.inf) for k in [numpy.float32, numpy.float64]]) +min_filler = ntypes._maxvals +min_filler.update([(k,numpy.inf) for k in [numpy.float32, numpy.float64]]) +if 'float128' in ntypes.typeDict: + max_filler.update([(numpy.float128,-numpy.inf)]) + min_filler.update([(numpy.float128, numpy.inf)]) + +def default_fill_value(obj): + """Calculates the default fill value for the argument object. + """ + if hasattr(obj,'dtype'): + defval = default_filler[obj.dtype.kind] + elif isinstance(obj, numeric.dtype): + defval = default_filler[obj.kind] + elif isinstance(obj, float): + defval = default_filler['f'] + elif isinstance(obj, int) or isinstance(obj, long): + defval = default_filler['i'] + elif isinstance(obj, str): + defval = default_filler['S'] + elif isinstance(obj, complex): + defval = default_filler['c'] + else: + defval = default_filler['O'] + return defval + +def minimum_fill_value(obj): + "Calculates the default fill value suitable for taking the minimum of ``obj``." + if hasattr(obj, 'dtype'): + objtype = obj.dtype + filler = min_filler[objtype] + if filler is None: + raise TypeError, 'Unsuitable type for calculating minimum.' + return filler + elif isinstance(obj, float): + return min_filler[ntypes.typeDict['float_']] + elif isinstance(obj, int): + return min_filler[ntypes.typeDict['int_']] + elif isinstance(obj, long): + return min_filler[ntypes.typeDict['uint']] + elif isinstance(obj, numeric.dtype): + return min_filler[obj] + else: + raise TypeError, 'Unsuitable type for calculating minimum.' + +def maximum_fill_value(obj): + "Calculates the default fill value suitable for taking the maximum of ``obj``." + if hasattr(obj, 'dtype'): + objtype = obj.dtype + filler = max_filler[objtype] + if filler is None: + raise TypeError, 'Unsuitable type for calculating minimum.' + return filler + elif isinstance(obj, float): + return max_filler[ntypes.typeDict['float_']] + elif isinstance(obj, int): + return max_filler[ntypes.typeDict['int_']] + elif isinstance(obj, long): + return max_filler[ntypes.typeDict['uint']] + elif isinstance(obj, numeric.dtype): + return max_filler[obj] + else: + raise TypeError, 'Unsuitable type for calculating minimum.' + +def set_fill_value(a, fill_value): + """Sets the filling value of a, if a is a masked array. +Otherwise, does nothing. + +*Returns*: + None + """ + if isinstance(a, MaskedArray): + a.set_fill_value(fill_value) + return + +def get_fill_value(a): + """Returns the filling value of a, if any. +Otherwise, returns the default filling value for that type. + """ + if isinstance(a, MaskedArray): + result = a.fill_value + else: + result = default_fill_value(a) + return result + +def common_fill_value(a, b): + """Returns the common filling value of a and b, if any. + If a and b have different filling values, returns None.""" + t1 = get_fill_value(a) + t2 = get_fill_value(b) + if t1 == t2: + return t1 + return None + +#####-------------------------------------------------------------------------- +def filled(a, value = None): + """Returns a as an array with masked data replaced by value. +If value is None, get_fill_value(a) is used instead. +If a is already a ndarray, a itself is returned. + +*Parameters*: + a : {var} + An input object. + value : {var}, optional + Filling value. If not given, the output of get_fill_value(a) is used instead. + +*Returns*: + A ndarray. + + """ + if hasattr(a, 'filled'): + return a.filled(value) + elif isinstance(a, ndarray): # and a.flags['CONTIGUOUS']: + return a + elif isinstance(a, dict): + return narray(a, 'O') + else: + return narray(a) + +#####-------------------------------------------------------------------------- +def get_masked_subclass(*arrays): + """Returns the youngest subclass of MaskedArray from a list of (masked) arrays. +In case of siblings, the first takes over.""" + if len(arrays) == 1: + arr = arrays[0] + if isinstance(arr, MaskedArray): + rcls = type(arr) + else: + rcls = MaskedArray + else: + arrcls = [type(a) for a in arrays] + rcls = arrcls[0] + if not issubclass(rcls, MaskedArray): + rcls = MaskedArray + for cls in arrcls[1:]: + if issubclass(cls, rcls): + rcls = cls + return rcls + +#####-------------------------------------------------------------------------- +def get_data(a, subok=True): + """Returns the _data part of a (if any), or a as a ndarray. + +*Parameters* : + a : {ndarray} + A ndarray or a subclass of. + subok : {boolean} + Whether to force the output to a 'pure' ndarray (False) or to return a subclass + of ndarray if approriate (True). + """ + data = getattr(a, '_data', numpy.array(a, subok=subok)) + if not subok: + return data.view(ndarray) + return data +getdata = get_data + +def fix_invalid(a, copy=True, fill_value=None): + """Returns (a copy of) a where invalid data (nan/inf) are masked and replaced +by fill_value. +Note that a copy is performed by default (just in case...). + +*Parameters*: + a : {ndarray} + A (subclass of) ndarray. + copy : {boolean} + Whether to use a copy of a (True) or to fix a in place (False). + fill_value : {var}, optional + Value used for fixing invalid data. + If not given, the output of get_fill_value(a) is used instead. + +*Returns* : + MaskedArray object + """ + a = masked_array(a, copy=copy, subok=True) + invalid = (numpy.isnan(a._data) | numpy.isinf(a._data)) + a._mask |= invalid + if fill_value is None: + fill_value = a.fill_value + a._data[invalid] = fill_value + return a + + + +#####-------------------------------------------------------------------------- +#---- --- Ufuncs --- +#####-------------------------------------------------------------------------- +ufunc_domain = {} +ufunc_fills = {} + +class _DomainCheckInterval: + """Defines a valid interval, so that : +``domain_check_interval(a,b)(x) = true`` where ``x < a`` or ``x > b``.""" + def __init__(self, a, b): + "domain_check_interval(a,b)(x) = true where x < a or y > b" + if (a > b): + (a, b) = (b, a) + self.a = a + self.b = b + + def __call__ (self, x): + "Executes the call behavior." + return umath.logical_or(umath.greater (x, self.b), + umath.less(x, self.a)) +#............................ +class _DomainTan: + """Defines a valid interval for the `tan` function, so that: +``domain_tan(eps) = True`` where ``abs(cos(x)) < eps``""" + def __init__(self, eps): + "domain_tan(eps) = true where abs(cos(x)) < eps)" + self.eps = eps + def __call__ (self, x): + "Executes the call behavior." + return umath.less(umath.absolute(umath.cos(x)), self.eps) +#............................ +class _DomainSafeDivide: + """Defines a domain for safe division.""" + def __init__ (self, tolerance=divide_tolerance): + self.tolerance = tolerance + def __call__ (self, a, b): + return umath.absolute(a) * self.tolerance >= umath.absolute(b) +#............................ +class _DomainGreater: + "DomainGreater(v)(x) = true where x <= v" + def __init__(self, critical_value): + "DomainGreater(v)(x) = true where x <= v" + self.critical_value = critical_value + + def __call__ (self, x): + "Executes the call behavior." + return umath.less_equal(x, self.critical_value) +#............................ +class _DomainGreaterEqual: + "DomainGreaterEqual(v)(x) = true where x < v" + def __init__(self, critical_value): + "DomainGreaterEqual(v)(x) = true where x < v" + self.critical_value = critical_value + + def __call__ (self, x): + "Executes the call behavior." + return umath.less(x, self.critical_value) + +#.............................................................................. +class _MaskedUnaryOperation: + """Defines masked version of unary operations, where invalid values are pre-masked. + +:IVariables: + f : function. + fill : Default filling value *[0]*. + domain : Default domain *[None]*. + """ + def __init__ (self, mufunc, fill=0, domain=None): + """ _MaskedUnaryOperation(aufunc, fill=0, domain=None) + aufunc(fill) must be defined + self(x) returns aufunc(x) + with masked values where domain(x) is true or getmask(x) is true. + """ + self.f = mufunc + self.fill = fill + self.domain = domain + self.__doc__ = getattr(mufunc, "__doc__", str(mufunc)) + self.__name__ = getattr(mufunc, "__name__", str(mufunc)) + ufunc_domain[mufunc] = domain + ufunc_fills[mufunc] = fill + # + def __call__ (self, a, *args, **kwargs): + "Executes the call behavior." + m = getmask(a) + d1 = get_data(a) + if self.domain is not None: + dm = narray(self.domain(d1), copy=False) + m = numpy.logical_or(m, dm) + # The following two lines control the domain filling methods. + d1 = d1.copy() +# d1[dm] = self.fill + numpy.putmask(d1, dm, self.fill) + # Take care of the masked singletong first ... + if not m.ndim and m: + return masked + # Get the result.............................. + if isinstance(a, MaskedArray): + result = self.f(d1, *args, **kwargs).view(type(a)) + else: + result = self.f(d1, *args, **kwargs).view(MaskedArray) + # Fix the mask if we don't have a scalar + if result.ndim > 0: + result._mask = m + return result + # + def __str__ (self): + return "Masked version of %s. [Invalid values are masked]" % str(self.f) + +#.............................................................................. +class _MaskedBinaryOperation: + """Defines masked version of binary operations, +where invalid values are pre-masked. + +:IVariables: + f : function. + fillx : Default filling value for the first argument *[0]*. + filly : Default filling value for the second argument *[0]*. + domain : Default domain *[None]*. + """ + def __init__ (self, mbfunc, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + self.f = mbfunc + self.fillx = fillx + self.filly = filly + self.__doc__ = getattr(mbfunc, "__doc__", str(mbfunc)) + self.__name__ = getattr(mbfunc, "__name__", str(mbfunc)) + ufunc_domain[mbfunc] = None + ufunc_fills[mbfunc] = (fillx, filly) + # + def __call__ (self, a, b, *args, **kwargs): + "Execute the call behavior." + m = mask_or(getmask(a), getmask(b)) + (d1, d2) = (get_data(a), get_data(b)) + result = self.f(d1, d2, *args, **kwargs).view(get_masked_subclass(a,b)) + if result.size > 1: + if m is not nomask: + result._mask = make_mask_none(result.shape) + result._mask.flat = m + elif m: + return masked + return result + # + def reduce (self, target, axis=0, dtype=None): + """Reduces `target` along the given `axis`.""" + if isinstance(target, MaskedArray): + tclass = type(target) + else: + tclass = MaskedArray + m = getmask(target) + t = filled(target, self.filly) + if t.shape == (): + t = t.reshape(1) + if m is not nomask: + m = make_mask(m, copy=1) + m.shape = (1,) + if m is nomask: + return self.f.reduce(t, axis).view(tclass) + t = t.view(tclass) + t._mask = m + tr = self.f.reduce(getdata(t), axis, dtype=dtype or t.dtype) + mr = umath.logical_and.reduce(m, axis) + tr = tr.view(tclass) + if mr.ndim > 0: + tr._mask = mr + return tr + elif mr: + return masked + return tr + + def outer (self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = umath.logical_or.outer(ma, mb) + if (not m.ndim) and m: + return masked + rcls = get_masked_subclass(a,b) +# d = self.f.outer(filled(a, self.fillx), filled(b, self.filly)).view(rcls) + d = self.f.outer(getdata(a), getdata(b)).view(rcls) + if d.ndim > 0: + d._mask = m + return d + + def accumulate (self, target, axis=0): + """Accumulates `target` along `axis` after filling with y fill value.""" + if isinstance(target, MaskedArray): + tclass = type(target) + else: + tclass = masked_array + t = filled(target, self.filly) + return self.f.accumulate(t, axis).view(tclass) + + def __str__ (self): + return "Masked version of " + str(self.f) + +#.............................................................................. +class _DomainedBinaryOperation: + """Defines binary operations that have a domain, like divide. + +They have no reduce, outer or accumulate. + +:IVariables: + f : function. + domain : Default domain. + fillx : Default filling value for the first argument *[0]*. + filly : Default filling value for the second argument *[0]*. + """ + def __init__ (self, dbfunc, domain, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + self.f = dbfunc + self.domain = domain + self.fillx = fillx + self.filly = filly + self.__doc__ = getattr(dbfunc, "__doc__", str(dbfunc)) + self.__name__ = getattr(dbfunc, "__name__", str(dbfunc)) + ufunc_domain[dbfunc] = domain + ufunc_fills[dbfunc] = (fillx, filly) + + def __call__(self, a, b): + "Execute the call behavior." + ma = getmask(a) + mb = getmask(b) + d1 = getdata(a) + d2 = get_data(b) + t = narray(self.domain(d1, d2), copy=False) + if t.any(None): + mb = mask_or(mb, t) + # The following two lines control the domain filling + d2 = d2.copy() + numpy.putmask(d2, t, self.filly) + m = mask_or(ma, mb) + if (not m.ndim) and m: + return masked + result = self.f(d1, d2).view(get_masked_subclass(a,b)) + if result.ndim > 0: + result._mask = m + return result + + def __str__ (self): + return "Masked version of " + str(self.f) + +#.............................................................................. +# Unary ufuncs +exp = _MaskedUnaryOperation(umath.exp) +conjugate = _MaskedUnaryOperation(umath.conjugate) +sin = _MaskedUnaryOperation(umath.sin) +cos = _MaskedUnaryOperation(umath.cos) +tan = _MaskedUnaryOperation(umath.tan) +arctan = _MaskedUnaryOperation(umath.arctan) +arcsinh = _MaskedUnaryOperation(umath.arcsinh) +sinh = _MaskedUnaryOperation(umath.sinh) +cosh = _MaskedUnaryOperation(umath.cosh) +tanh = _MaskedUnaryOperation(umath.tanh) +abs = absolute = _MaskedUnaryOperation(umath.absolute) +fabs = _MaskedUnaryOperation(umath.fabs) +negative = _MaskedUnaryOperation(umath.negative) +floor = _MaskedUnaryOperation(umath.floor) +ceil = _MaskedUnaryOperation(umath.ceil) +around = _MaskedUnaryOperation(fromnumeric.round_) +logical_not = _MaskedUnaryOperation(umath.logical_not) +# Domained unary ufuncs ....................................................... +sqrt = _MaskedUnaryOperation(umath.sqrt, 0.0, + _DomainGreaterEqual(0.0)) +log = _MaskedUnaryOperation(umath.log, 1.0, + _DomainGreater(0.0)) +log10 = _MaskedUnaryOperation(umath.log10, 1.0, + _DomainGreater(0.0)) +tan = _MaskedUnaryOperation(umath.tan, 0.0, + _DomainTan(1.e-35)) +arcsin = _MaskedUnaryOperation(umath.arcsin, 0.0, + _DomainCheckInterval(-1.0, 1.0)) +arccos = _MaskedUnaryOperation(umath.arccos, 0.0, + _DomainCheckInterval(-1.0, 1.0)) +arccosh = _MaskedUnaryOperation(umath.arccosh, 1.0, + _DomainGreaterEqual(1.0)) +arctanh = _MaskedUnaryOperation(umath.arctanh, 0.0, + _DomainCheckInterval(-1.0+1e-15, 1.0-1e-15)) +# Binary ufuncs ............................................................... +add = _MaskedBinaryOperation(umath.add) +subtract = _MaskedBinaryOperation(umath.subtract) +multiply = _MaskedBinaryOperation(umath.multiply, 1, 1) +arctan2 = _MaskedBinaryOperation(umath.arctan2, 0.0, 1.0) +equal = _MaskedBinaryOperation(umath.equal) +equal.reduce = None +not_equal = _MaskedBinaryOperation(umath.not_equal) +not_equal.reduce = None +less_equal = _MaskedBinaryOperation(umath.less_equal) +less_equal.reduce = None +greater_equal = _MaskedBinaryOperation(umath.greater_equal) +greater_equal.reduce = None +less = _MaskedBinaryOperation(umath.less) +less.reduce = None +greater = _MaskedBinaryOperation(umath.greater) +greater.reduce = None +logical_and = _MaskedBinaryOperation(umath.logical_and) +alltrue = _MaskedBinaryOperation(umath.logical_and, 1, 1).reduce +logical_or = _MaskedBinaryOperation(umath.logical_or) +sometrue = logical_or.reduce +logical_xor = _MaskedBinaryOperation(umath.logical_xor) +bitwise_and = _MaskedBinaryOperation(umath.bitwise_and) +bitwise_or = _MaskedBinaryOperation(umath.bitwise_or) +bitwise_xor = _MaskedBinaryOperation(umath.bitwise_xor) +hypot = _MaskedBinaryOperation(umath.hypot) +# Domained binary ufuncs ...................................................... +divide = _DomainedBinaryOperation(umath.divide, _DomainSafeDivide(), 0, 1) +true_divide = _DomainedBinaryOperation(umath.true_divide, + _DomainSafeDivide(), 0, 1) +floor_divide = _DomainedBinaryOperation(umath.floor_divide, + _DomainSafeDivide(), 0, 1) +remainder = _DomainedBinaryOperation(umath.remainder, + _DomainSafeDivide(), 0, 1) +fmod = _DomainedBinaryOperation(umath.fmod, _DomainSafeDivide(), 0, 1) + + +#####-------------------------------------------------------------------------- +#---- --- Mask creation functions --- +#####-------------------------------------------------------------------------- +def get_mask(a): + """Returns the mask of a, if any, or nomask. +To get a full array of booleans of the same shape as a, use getmaskarray. + """ + return getattr(a, '_mask', nomask) +getmask = get_mask + +def getmaskarray(a): + """Returns the mask of a, if any, or a boolean array of the shape of a, full of False. + """ + m = getmask(a) + if m is nomask: + m = make_mask_none(fromnumeric.shape(a)) + return m + +def is_mask(m): + """Returns True if m is a legal mask. +Does not check contents, only type. + """ + try: + return m.dtype.type is MaskType + except AttributeError: + return False +# +def make_mask(m, copy=False, shrink=True, flag=None): + """Returns m as a mask, creating a copy if necessary or requested. +The function can accept any sequence of integers or nomask. +Does not check that contents must be 0s and 1s. + +*Parameters*: + m : {ndarray} + Potential mask. + copy : {boolean} + Whether to return a copy of m (True) or m itself (False). + shrink : {boolean} + Whether to shrink m to nomask if all its values are False. + """ + if flag is not None: + warnings.warn("The flag 'flag' is now called 'shrink'!", + DeprecationWarning) + shrink = flag + if m is nomask: + return nomask + elif isinstance(m, ndarray): + m = filled(m, True) + if m.dtype.type is MaskType: + if copy: + result = narray(m, dtype=MaskType, copy=copy) + else: + result = m + else: + result = narray(m, dtype=MaskType) + else: + result = narray(filled(m, True), dtype=MaskType) + # Bas les masques ! + if shrink and not result.any(): + return nomask + else: + return result + +def make_mask_none(s): + """Returns a mask of shape s, filled with False. + +*Parameters*: + s : {tuple} + A tuple indicating the shape of the final mask. + """ + result = numeric.zeros(s, dtype=MaskType) + return result + +def mask_or (m1, m2, copy=False, shrink=True): + """Returns the combination of two masks m1 and m2. +The masks are combined with the *logical_or* operator, treating nomask as False. +The result may equal m1 or m2 if the other is nomask. + +*Parameters*: + m1 : {ndarray} + First mask. + m2 : {ndarray} + Second mask + copy : {boolean} + Whether to return a copy. + shrink : {boolean} + Whether to shrink m to nomask if all its values are False. + """ + if m1 is nomask: + return make_mask(m2, copy=copy, shrink=shrink) + if m2 is nomask: + return make_mask(m1, copy=copy, shrink=shrink) + if m1 is m2 and is_mask(m1): + return m1 + return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink) + +#####-------------------------------------------------------------------------- +#--- --- Masking functions --- +#####-------------------------------------------------------------------------- +def masked_where(condition, a, copy=True): + """Returns a as an array masked where condition is true. +Masked values of a or condition are kept. + +*Parameters*: + condition : {ndarray} + Masking condition. + a : {ndarray} + Array to mask. + copy : {boolean} + Whether to return a copy of a (True) or modify a in place. + """ + cond = filled(condition,1) + a = narray(a, copy=copy, subok=True) + if hasattr(a, '_mask'): + cond = mask_or(cond, a._mask) + cls = type(a) + else: + cls = MaskedArray + result = a.view(cls) + result._mask = cond + return result + +def masked_greater(x, value, copy=True): + "Shortcut to masked_where, with condition = (x > value)." + return masked_where(greater(x, value), x, copy=copy) + +def masked_greater_equal(x, value, copy=True): + "Shortcut to masked_where, with condition = (x >= value)." + return masked_where(greater_equal(x, value), x, copy=copy) + +def masked_less(x, value, copy=True): + "Shortcut to masked_where, with condition = (x < value)." + return masked_where(less(x, value), x, copy=copy) + +def masked_less_equal(x, value, copy=True): + "Shortcut to masked_where, with condition = (x <= value)." + return masked_where(less_equal(x, value), x, copy=copy) + +def masked_not_equal(x, value, copy=True): + "Shortcut to masked_where, with condition = (x != value)." + return masked_where((x != value), x, copy=copy) + +# +def masked_equal(x, value, copy=True): + """Shortcut to masked_where, with condition = (x == value). +For floating point, consider `masked_values(x, value)` instead. + """ + return masked_where((x == value), x, copy=copy) +# d = filled(x, 0) +# c = umath.equal(d, value) +# m = mask_or(c, getmask(x)) +# return array(d, mask=m, copy=copy) + +def masked_inside(x, v1, v2, copy=True): + """Shortcut to masked_where, where condition is True for x inside the interval +[v1,v2] (v1 <= x <= v2). +The boundaries v1 and v2 can be given in either order. + +*Note*: + The array x is prefilled with its filling value. + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf >= v1) & (xf <= v2) + return masked_where(condition, x, copy=copy) + +def masked_outside(x, v1, v2, copy=True): + """Shortcut to masked_where, where condition is True for x outside the interval +[v1,v2] (x < v1)|(x > v2). +The boundaries v1 and v2 can be given in either order. + +*Note*: + The array x is prefilled with its filling value. + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf < v1) | (xf > v2) + return masked_where(condition, x, copy=copy) + +# +def masked_object(x, value, copy=True): + """Masks the array x where the data are exactly equal to value. + +This function is suitable only for object arrays: for floating point, please use +``masked_values`` instead. + +*Notes*: + The mask is set to `nomask` if posible. + """ + if isMaskedArray(x): + condition = umath.equal(x._data, value) + mask = x._mask + else: + condition = umath.equal(fromnumeric.asarray(x), value) + mask = nomask + mask = mask_or(mask, make_mask(condition, shrink=True)) + return masked_array(x, mask=mask, copy=copy, fill_value=value) + +def masked_values(x, value, rtol=1.e-5, atol=1.e-8, copy=True): + """Masks the array x where the data are approximately equal to value +(abs(x - value) <= atol+rtol*abs(value)). +Suitable only for floating points. For integers, please use ``masked_equal``. +The mask is set to nomask if posible. + +*Parameters*: + x : {ndarray} + Array to fill. + value : {float} + Masking value. + rtol : {float} + Tolerance parameter. + atol : {float}, *[1e-8]* + Tolerance parameter. + copy : {boolean} + Whether to return a copy of x. + """ + abs = umath.absolute + xnew = filled(x, value) + if issubclass(xnew.dtype.type, numeric.floating): + condition = umath.less_equal(abs(xnew-value), atol+rtol*abs(value)) + mask = getattr(x, '_mask', nomask) + else: + condition = umath.equal(xnew, value) + mask = nomask + mask = mask_or(mask, make_mask(condition, shrink=True)) + return masked_array(xnew, mask=mask, copy=copy, fill_value=value) + +def masked_invalid(a, copy=True): + """Masks the array for invalid values (nans or infs). + Any preexisting mask is conserved.""" + a = narray(a, copy=copy, subok=True) + condition = (numpy.isnan(a) | numpy.isinf(a)) + if hasattr(a, '_mask'): + condition = mask_or(condition, a._mask) + cls = type(a) + else: + cls = MaskedArray + result = a.view(cls) + result._mask = cond + return result + + +#####-------------------------------------------------------------------------- +#---- --- Printing options --- +#####-------------------------------------------------------------------------- +class _MaskedPrintOption: + """Handles the string used to represent missing data in a masked array.""" + def __init__ (self, display): + "Creates the masked_print_option object." + self._display = display + self._enabled = True + + def display(self): + "Displays the string to print for masked values." + return self._display + + def set_display (self, s): + "Sets the string to print for masked values." + self._display = s + + def enabled(self): + "Is the use of the display value enabled?" + return self._enabled + + def enable(self, shrink=1): + "Set the enabling shrink to `shrink`." + self._enabled = shrink + + def __str__ (self): + return str(self._display) + + __repr__ = __str__ + +#if you single index into a masked location you get this object. +masked_print_option = _MaskedPrintOption('--') + +#####-------------------------------------------------------------------------- +#---- --- MaskedArray class --- +#####-------------------------------------------------------------------------- + +#............................................................................... +class _arraymethod(object): + """Defines a wrapper for basic array methods. +Upon call, returns a masked array, where the new _data array is the output of +the corresponding method called on the original _data. + +If onmask is True, the new mask is the output of the method called on the initial +mask. Otherwise, the new mask is just a reference to the initial mask. + +:IVariables: + _name : String + Name of the function to apply on data. + _onmask : {boolean} *[True]* + Whether the mask must be processed also (True) or left alone (False). + obj : Object + The object calling the arraymethod + """ + def __init__(self, funcname, onmask=True): + self._name = funcname + self._onmask = onmask + self.obj = None + self.__doc__ = self.getdoc() + # + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + methdoc = getattr(ndarray, self._name, None) + methdoc = getattr(numpy, self._name, methdoc) + if methdoc is not None: + return methdoc.__doc__ + # + def __get__(self, obj, objtype=None): + self.obj = obj + return self + # + def __call__(self, *args, **params): + methodname = self._name + data = self.obj._data + mask = self.obj._mask + cls = type(self.obj) + result = getattr(data, methodname)(*args, **params).view(cls) + result._update_from(self.obj) + #result._shrinkmask = self.obj._shrinkmask + if result.ndim: + if not self._onmask: + result.__setmask__(mask) + elif mask is not nomask: + result.__setmask__(getattr(mask, methodname)(*args, **params)) + else: + if mask.ndim and mask.all(): + return masked + return result +#.......................................................... + +class FlatIter(object): + "Defines an interator." + def __init__(self, ma): + self.ma = ma + self.ma_iter = numpy.asarray(ma).flat + + if ma._mask is nomask: + self.maskiter = None + else: + self.maskiter = ma._mask.flat + + def __iter__(self): + return self + + ### This won't work is ravel makes a copy + def __setitem__(self, index, value): + a = self.ma.ravel() + a[index] = value + + def next(self): + d = self.ma_iter.next() + if self.maskiter is not None and self.maskiter.next(): + d = masked + return d + + +class MaskedArray(numeric.ndarray): + """Arrays with possibly masked values. +Masked values of True exclude the corresponding element from any computation. + +Construction: + x = MaskedArray(data, mask=nomask, dtype=None, copy=True, fill_value=None, + mask = nomask, fill_value=None, shrink=True) + +*Parameters*: + data : {var} + Input data. + mask : {nomask, sequence} + Mask. + Must be convertible to an array of booleans with the same shape as data: + True indicates a masked (eg., invalid) data. + dtype : {dtype} + Data type of the output. If None, the type of the data argument is used. + If dtype is not None and different from data.dtype, a copy is performed. + copy : {boolean} + Whether to copy the input data (True), or to use a reference instead. + Note: data are NOT copied by default. + fill_value : {var} + Value used to fill in the masked values when necessary. If None, a default + based on the datatype is used. + keep_mask : {True, boolean} + Whether to combine mask with the mask of the input data, if any (True), + or to use only mask for the output (False). + hard_mask : {False, boolean} + Whether to use a hard mask or not. With a hard mask, masked values cannot + be unmasked. + subok : {True, boolean} + Whether to return a subclass of MaskedArray (if possible) or a plain + MaskedArray. + """ + + __array_priority__ = 15 + _defaultmask = nomask + _defaulthardmask = False + _baseclass = numeric.ndarray + + def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, fill_value=None, + keep_mask=True, hard_mask=False, flag=None, + subok=True, **options): + """Creates a new masked array from scratch. + Note: you can also create an array with the .view(MaskedArray) method... + """ + if flag is not None: + warnings.warn("The flag 'flag' is now called 'shrink'!", + DeprecationWarning) + shrink = flag + # Process data............ + _data = narray(data, dtype=dtype, copy=copy, subok=True) + _baseclass = getattr(data, '_baseclass', type(_data)) + _basedict = getattr(data, '_basedict', getattr(data, '__dict__', None)) + if not isinstance(data, MaskedArray) or not subok: + _data = _data.view(cls) + else: + _data = _data.view(type(data)) + # Backwards compatibility w/ numpy.core.ma ....... + if hasattr(data,'_mask') and not isinstance(data, ndarray): + _data._mask = data._mask + _sharedmask = True + # Process mask ........... + if mask is nomask: + if not keep_mask: + _data._mask = nomask + if copy: + _data._mask = _data._mask.copy() + _data._sharedmask = False + else: + _data._sharedmask = True + else: + mask = narray(mask, dtype=MaskType, copy=copy) + if mask.shape != _data.shape: + (nd, nm) = (_data.size, mask.size) + if nm == 1: + mask = numeric.resize(mask, _data.shape) + elif nm == nd: + mask = fromnumeric.reshape(mask, _data.shape) + else: + msg = "Mask and data not compatible: data size is %i, "+\ + "mask size is %i." + raise MAError, msg % (nd, nm) + copy = True + if _data._mask is nomask: + _data._mask = mask + _data._sharedmask = not copy + else: + if not keep_mask: + _data._mask = mask + _data._sharedmask = not copy + else: + _data._mask = umath.logical_or(mask, _data._mask) + _data._sharedmask = False + + # Update fill_value....... + if fill_value is None: + _data._fill_value = getattr(data, '_fill_value', + default_fill_value(_data)) + else: + _data._fill_value = fill_value + # Process extra options .. + _data._hardmask = hard_mask + _data._baseclass = _baseclass + _data._basedict = _basedict + return _data + # + def _update_from(self, obj): + """Copies some attributes of obj to self. + """ + self._hardmask = getattr(obj, '_hardmask', self._defaulthardmask) + self._sharedmask = getattr(obj, '_sharedmask', False) + if obj is not None: + self._baseclass = getattr(obj, '_baseclass', type(obj)) + else: + self._baseclass = ndarray + self._fill_value = getattr(obj, '_fill_value', None) + return + #........................ + def __array_finalize__(self,obj): + """Finalizes the masked array. + """ + # Get main attributes ......... + self._mask = getattr(obj, '_mask', nomask) + self._update_from(obj) + # Update special attributes ... + self._basedict = getattr(obj, '_basedict', getattr(obj, '__dict__', None)) + if self._basedict is not None: + self.__dict__.update(self._basedict) + # Finalize the mask ........... + if self._mask is not nomask: + self._mask.shape = self.shape + return + #.................................. + def __array_wrap__(self, obj, context=None): + """Special hook for ufuncs. +Wraps the numpy array and sets the mask according to context. + """ + result = obj.view(type(self)) + result._update_from(self) + #.......... + if context is not None: + result._mask = result._mask.copy() + (func, args, _) = context + m = reduce(mask_or, [getmask(arg) for arg in args]) + # Get the domain mask................ + domain = ufunc_domain.get(func, None) + if domain is not None: + if len(args) > 2: + d = reduce(domain, args) + else: + d = domain(*args) + # Fill the result where the domain is wrong + try: + # Binary domain: take the last value + fill_value = ufunc_fills[func][-1] + except TypeError: + # Unary domain: just use this one + fill_value = ufunc_fills[func] + except KeyError: + # Domain not recognized, use fill_value instead + fill_value = self.fill_value + result = result.copy() + numpy.putmask(result, d, fill_value) + # Update the mask + if m is nomask: + if d is not nomask: + m = d + else: + m |= d + # Make sure the mask has the proper size + if result.shape == () and m: + return masked + else: + result._mask = m + result._sharedmask = False + #.... + return result + #............................................. + def __getitem__(self, indx): + """x.__getitem__(y) <==> x[y] +Returns the item described by i, as a masked array. + """ + # This test is useful, but we should keep things light... +# 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) + m = self._mask + if not getattr(dout,'ndim', False): + # Just a scalar............ + if m is not nomask and m[indx]: + return masked + else: + # Force dout to MA ........ + dout = dout.view(type(self)) + # Inherit attributes from self + dout._update_from(self) + # Update the mask if needed + if m is not nomask: + dout._mask = ndarray.__getitem__(m, indx).reshape(dout.shape) +# Note: Don't try to check for m.any(), that'll take too long... +# mask = ndarray.__getitem__(m, indx).reshape(dout.shape) +# if self._shrinkmask and not m.any(): +# dout._mask = nomask +# else: +# dout._mask = mask + return dout + #........................ + def __setitem__(self, indx, value): + """x.__setitem__(i, y) <==> x[i]=y +Sets item described by index. If value is masked, masks those locations. + """ + if self is masked: + raise MAError, 'Cannot alter the masked element.' +# if getmask(indx) is not nomask: +# msg = "Masked arrays must be filled before they can be used as indices!" +# raise IndexError, msg + #.... + if value is masked: + m = self._mask + if m is nomask: + m = numpy.zeros(self.shape, dtype=MaskType) + m[indx] = True + self._mask = m + self._sharedmask = False + return + #.... + dval = getdata(value).astype(self.dtype) + valmask = getmask(value) + if self._mask is nomask: + if valmask is not nomask: + self._mask = numpy.zeros(self.shape, dtype=MaskType) + self._mask[indx] = valmask + elif not self._hardmask: + # Unshare the mask if necessary to avoid propagation + self.unshare_mask() + self._mask[indx] = valmask + elif hasattr(indx, 'dtype') and (indx.dtype==bool_): + indx = indx * umath.logical_not(self._mask) + else: + mindx = mask_or(self._mask[indx], valmask, copy=True) + dindx = self._data[indx] + if dindx.size > 1: + dindx[~mindx] = dval + elif mindx is nomask: + dindx = dval + dval = dindx + self._mask[indx] = mindx + # Set data .......... + ndarray.__setitem__(self._data,indx,dval) + #............................................ + def __getslice__(self, i, j): + """x.__getslice__(i, j) <==> x[i:j] +Returns the slice described by (i, j). +The use of negative indices is not supported.""" + return self.__getitem__(slice(i,j)) + #........................ + def __setslice__(self, i, j, value): + """x.__setslice__(i, j, value) <==> x[i:j]=value +Sets the slice (i,j) of a to value. If value is masked, masks those locations. + """ + self.__setitem__(slice(i,j), value) + #............................................ + def __setmask__(self, mask, copy=False): + """Sets the mask.""" + if mask is not nomask: + mask = narray(mask, copy=copy, dtype=MaskType) +# if self._shrinkmask and not mask.any(): +# mask = nomask + if self._mask is nomask: + self._mask = mask + elif self._hardmask: + if mask is not nomask: + self._mask.__ior__(mask) + else: + # This one is tricky: if we set the mask that way, we may break the + # propagation. But if we don't, we end up with a mask full of False + # and a test on nomask fails... + if mask is nomask: + self._mask = nomask + else: + self.unshare_mask() + self._mask.flat = mask + if self._mask.shape: + self._mask = numeric.reshape(self._mask, self.shape) + _set_mask = __setmask__ + #.... + def _get_mask(self): + """Returns the current mask.""" + return self._mask +# return self._mask.reshape(self.shape) + mask = property(fget=_get_mask, fset=__setmask__, doc="Mask") + #............................................ + def harden_mask(self): + "Forces the mask to hard." + self._hardmask = True + + def soften_mask(self): + "Forces the mask to soft." + self._hardmask = False + + def unshare_mask(self): + "Copies the mask and set the sharedmask flag to False." + if self._sharedmask: + self._mask = self._mask.copy() + self._sharedmask = False + + def shrink_mask(self): + "Reduces a mask to nomask when possible." + m = self._mask + if m.ndim and not m.any(): + self._mask = nomask + + #............................................ + def _get_data(self): + "Returns the current data, as a view of the original underlying data." + return self.view(self._baseclass) + _data = property(fget=_get_data) + data = property(fget=_get_data) + + def raw_data(self): + """Returns the _data part of the MaskedArray. +DEPRECATED: You should really use ``.data`` instead...""" + return self._data + #............................................ + def _get_flat(self): + "Returns a flat iterator." + return FlatIter(self) + # + def _set_flat (self, value): + "Sets a flattened version of self to value." + y = self.ravel() + y[:] = value + # + flat = property(fget=_get_flat, fset=_set_flat, + doc="Flat version of the array.") + #............................................ + def get_fill_value(self): + "Returns the filling value." + if self._fill_value is None: + self._fill_value = default_fill_value(self) + return self._fill_value + + def set_fill_value(self, value=None): + """Sets the filling value to value. +If value is None, uses a default based on the data type.""" + if value is None: + value = default_fill_value(self) + self._fill_value = value + + fill_value = property(fget=get_fill_value, fset=set_fill_value, + doc="Filling value.") + + def filled(self, fill_value=None): + """Returns a copy of self._data, where masked values are filled with +fill_value. + +If fill_value is None, self.fill_value is used instead. + +*Note*: + + Subclassing is preserved + + The result is NOT a MaskedArray ! + +*Examples*: + >>> x = array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999) + >>> x.filled() + array([1,2,-999,4,-999]) + >>> type(x.filled()) + + """ + m = self._mask + if m is nomask or not m.any(): + return self._data + # + if fill_value is None: + fill_value = self.fill_value + # + if self is masked_singleton: + result = numeric.asanyarray(fill_value) + else: + result = self._data.copy() + try: + numpy.putmask(result, m, fill_value) + except (TypeError, AttributeError): + fill_value = narray(fill_value, dtype=object) + d = result.astype(object) + result = fromnumeric.choose(m, (d, fill_value)) + except IndexError: + #ok, if scalar + if self._data.shape: + raise + elif m: + result = narray(fill_value, dtype=self.dtype) + else: + result = self._data + return result + + def compressed(self): + """Returns a 1-D array of all the non-masked data.""" + data = ndarray.ravel(self._data).view(type(self)) + data._update_from(self) + if self._mask is not nomask: + data = data[numpy.logical_not(ndarray.ravel(self._mask))] +# if not self._shrinkmask: +# data._mask = numpy.zeros(data.shape, dtype=MaskType) + return data + + #............................................ + def __str__(self): + """Calculates the string representation. + """ + if masked_print_option.enabled(): + f = masked_print_option + if self is masked: + return str(f) + m = self._mask + if m is nomask: + res = self._data + else: + if m.shape == (): + if m: + return str(f) + else: + return str(self._data) + # convert to object array to make filled work +#CHECK: the two lines below seem more robust than the self._data.astype +# res = numeric.empty(self._data.shape, object_) +# numeric.putmask(res,~m,self._data) + res = self._data.astype("|O8") + res[m] = f + else: + res = self.filled(self.fill_value) + return str(res) + + def __repr__(self): + """Calculates the repr representation. + """ + with_mask = """\ +masked_%(name)s(data = + %(data)s, + mask = + %(mask)s, + fill_value=%(fill)s) +""" + with_mask1 = """\ +masked_%(name)s(data = %(data)s, + mask = %(mask)s, + fill_value=%(fill)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), + } + #............................................ + def __add__(self, other): + "Adds other to self, and returns a new masked array." + return add(self, other) + # + def __sub__(self, other): + "Subtracts other to self, and returns a new masked array." + return subtract(self, other) + # + def __mul__(self, other): + "Multiplies other to self, and returns a new masked array." + return multiply(self, other) + # + def __div__(self, other): + "Divides other to self, and returns a new masked array." + return divide(self, other) + # + def __truediv__(self, other): + "Divides other to self, and returns a new masked array." + return true_divide(self, other) + # + def __floordiv__(self, other): + "Divides other to self, and returns a new masked array." + return floor_divide(self, other) + + #............................................ + def __iadd__(self, other): + "Adds other to self in place." + ndarray.__iadd__(self._data, getdata(other)) + m = getmask(other) + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + #.... + def __isub__(self, other): + "Subtracts other from self in place." + ndarray.__isub__(self._data, getdata(other)) + m = getmask(other) + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + #.... + def __imul__(self, other): + "Multiplies self by other in place." + ndarray.__imul__(self._data, getdata(other)) + m = getmask(other) + if self._mask is nomask: + self._mask = m + elif m is not nomask: + self._mask += m + return self + #.... + def __idiv__(self, other): + "Divides self by other in place." + other_data = getdata(other) + dom_mask = _DomainSafeDivide().__call__(self._data, other_data) + other_mask = getmask(other) + new_mask = mask_or(other_mask, dom_mask) + # The following 3 lines control the domain filling + if dom_mask.any(): + other_data = other_data.copy() + numpy.putmask(other_data, dom_mask, 1) + ndarray.__idiv__(self._data, other_data) + self._mask = mask_or(self._mask, new_mask) + return self + #............................................ + def __float__(self): + "Converts self to float." + if self._mask is not nomask: + warnings.warn("Warning: converting a masked element to nan.") + return numpy.nan + #raise MAError, 'Cannot convert masked element to a Python float.' + return float(self.item()) + + def __int__(self): + "Converts self to int." + if self._mask is not nomask: + raise MAError, 'Cannot convert masked element to a Python int.' + return int(self.item()) + #............................................ + def get_imag(self): + result = self._data.imag.view(type(self)) + result.__setmask__(self._mask) + return result + imag = property(fget=get_imag,doc="Imaginary part") + + def get_real(self): + result = self._data.real.view(type(self)) + result.__setmask__(self._mask) + return result + real = property(fget=get_real,doc="Real part") + + + #............................................ + def count(self, axis=None): + """Counts the non-masked elements of the array along the given axis. + +*Parameters*: + axis : {integer}, optional + Axis along which to count the non-masked elements. If not given, all the + non masked elements are counted. + +*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. + """ + m = self._mask + s = self.shape + ls = len(s) + if m is nomask: + if ls == 0: + return 1 + if ls == 1: + return s[0] + if axis is None: + return self.size + else: + n = s[axis] + t = list(s) + del t[axis] + return numeric.ones(t) * n + n1 = numpy.size(m, axis) + n2 = m.astype(int_).sum(axis) + if axis is None: + return (n1-n2) + else: + return masked_array(n1 - n2) + #............................................ + flatten = _arraymethod('flatten') +# ravel = _arraymethod('ravel') + def ravel(self): + """Returns a 1D version of self, as a view.""" + r = ndarray.ravel(self._data).view(type(self)) + r._update_from(self) + if self._mask is not nomask: + r._mask = ndarray.ravel(self._mask).reshape(r.shape) + else: + r._mask = nomask + return r + repeat = _arraymethod('repeat') + # + def reshape (self, *s): + """Reshapes the array to shape s. + +*Returns*: + A new masked array. + +*Notes: + If you want to modify the shape in place, please use ``a.shape = s`` + """ + result = self._data.reshape(*s).view(type(self)) + result.__dict__.update(self.__dict__) + if result._mask is not nomask: + result._mask = self._mask.copy() + result._mask.shape = result.shape + return result + # + def resize(self, newshape, refcheck=True, order=False): + """Attempts to modify the size and the shape of the array in place. + +The array must own its own memory and not be referenced by other arrays. + +*Returns*: + None. + """ + try: + self._data.resize(newshape, refcheck, order) + if self.mask is not nomask: + self._mask.resize(newshape, refcheck, order) + except ValueError: + raise ValueError("Cannot resize an array that has been referenced " + "or is referencing another array in this way.\n" + "Use the resize function.") + return None + # + def put(self, indices, values, mode='raise'): + """Sets storage-indexed locations to corresponding values. + +a.put(values, indices, mode) sets a.flat[n] = values[n] for each n in indices. +If values is shorter than indices then it will repeat. +If values has some masked values, the initial mask is updated in consequence, +else the corresponding values are unmasked. + """ + m = self._mask + # Hard mask: Get rid of the values/indices that fall on masked data + if self._hardmask and self._mask is not nomask: + mask = self._mask[indices] + indices = narray(indices, copy=False) + values = narray(values, copy=False, subok=True) + values.resize(indices.shape) + indices = indices[~mask] + values = values[~mask] + #.... + self._data.put(indices, values, mode=mode) + #.... + if m is nomask: + m = getmask(values) + else: + m = m.copy() + if getmask(values) is nomask: + m.put(indices, False, mode=mode) + else: + m.put(indices, values._mask, mode=mode) + m = make_mask(m, copy=False, shrink=True) + self._mask = m + #............................................ + def ids (self): + """Returns the addresses of the data and mask areas.""" + return (self.ctypes.data, self._mask.ctypes.data) + #............................................ + def all(self, axis=None, out=None): + """Returns True if all entries along the given axis are True, False otherwise. +Masked values are considered as True during computation. + +*Parameters* + axis : {integer}, optional + Axis along which the operation is performed. + If None, the operation is performed on a flatten array + out : {MaskedArray}, optional + Alternate optional output. + If not None, out should be a valid MaskedArray of the same shape as the + output of self._data.all(axis). + +*Returns* + A masked array, where the mask is True if all data along the axis are masked. + +*Notes* + An exception is raised if ``out`` is not None and not of the same type as self. + """ + if out is None: + d = self.filled(True).all(axis=axis).view(type(self)) + if d.ndim > 0: + d.__setmask__(self._mask.all(axis)) + return d + elif type(out) is not type(self): + raise TypeError("The external array should have a type %s (got %s instead)" %\ + (type(self), type(out))) + self.filled(True).all(axis=axis, out=out) + if out.ndim: + out.__setmask__(self._mask.all(axis)) + return out + + + def any(self, axis=None, out=None): + """Returns True if at least one entry along the given axis is True. + +Returns False if all entries are False. +Masked values are considered as True during computation. + +*Parameters* + axis : {integer}, optional + Axis along which the operation is performed. + If None, the operation is performed on a flatten array + out : {MaskedArray}, optional + Alternate optional output. + If not None, out should be a valid MaskedArray of the same shape as the + output of self._data.all(axis). + +*Returns* + A masked array, where the mask is True if all data along the axis are masked. + +*Notes* + An exception is raised if ``out`` is not None and not of the same type as self. + """ + if out is None: + d = self.filled(False).any(axis=axis).view(type(self)) + if d.ndim > 0: + d.__setmask__(self._mask.all(axis)) + return d + elif type(out) is not type(self): + raise TypeError("The external array should have a type %s (got %s instead)" %\ + (type(self), type(out))) + self.filled(False).any(axis=axis, out=out) + if out.ndim: + out.__setmask__(self._mask.all(axis)) + return out + + + def nonzero(self): + """Returns the indices of the elements of a that are not zero nor masked, +as a tuple of arrays. + +There are as many tuples as dimensions of a, each tuple contains the indices of +the non-zero elements in that dimension. The corresponding non-zero values can +be obtained with ``a[a.nonzero()]``. + +To group the indices by element, rather than dimension, use instead: +``transpose(a.nonzero())``. + +The result of this is always a 2d array, with a row for each non-zero element. + """ + return narray(self.filled(0), copy=False).nonzero() + #............................................ + def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): + """a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) +Returns the sum along the offset diagonal of the array's indicated `axis1` and `axis2`. + """ + # TODO: What are we doing with `out`? + m = self._mask + if m is nomask: + result = super(MaskedArray, self).trace(offset=offset, axis1=axis1, + axis2=axis2, out=out) + return result.astype(dtype) + else: + D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) + return D.astype(dtype).filled(0).sum(axis=None) + #............................................ + def sum(self, axis=None, dtype=None): + """Sums the array over the given axis. + +Masked elements are set to 0 internally. + +*Parameters*: + axis : {integer}, 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. + """ + if self._mask is nomask: + mask = nomask + else: + mask = self._mask.all(axis) + if (not mask.ndim) and mask: + return masked + result = self.filled(0).sum(axis, dtype=dtype).view(type(self)) + if result.ndim > 0: + result.__setmask__(mask) + return result + + def cumsum(self, axis=None, dtype=None): + """Returns the cumulative sum of the elements of the array along the given axis. + +Masked values are set to 0 internally. + +*Parameters*: + axis : {integer}, 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. + """ + result = self.filled(0).cumsum(axis=axis, dtype=dtype).view(type(self)) + result.__setmask__(self.mask) + return result + + def prod(self, axis=None, dtype=None): + """Returns the product of the elements of the array along the given axis. + +Masked elements are set to 1 internally. + +*Parameters*: + axis : {integer}, 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. + """ + if self._mask is nomask: + mask = nomask + else: + mask = self._mask.all(axis) + if (not mask.ndim) and mask: + return masked + result = self.filled(1).prod(axis=axis, dtype=dtype).view(type(self)) + if result.ndim: + result.__setmask__(mask) + return result + product = prod + + def cumprod(self, axis=None, dtype=None): + """Returns the cumulative product of the elements of the array along the given axis. + +Masked values are set to 1 internally. + +*Parameters*: + axis : {integer}, 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. + """ + result = self.filled(1).cumprod(axis=axis, dtype=dtype).view(type(self)) + result.__setmask__(self.mask) + return result + + def mean(self, axis=None, dtype=None): + """Averages the array over the given axis. Equivalent to + + a.sum(axis, dtype) / a.size(axis). + +*Parameters*: + axis : {integer}, 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. + """ + if self._mask is nomask: + return super(MaskedArray, self).mean(axis=axis, dtype=dtype) + else: + dsum = self.sum(axis=axis, dtype=dtype) + cnt = self.count(axis=axis) + return dsum*1./cnt + + def anom(self, axis=None, dtype=None): + """Returns the anomalies (deviations from the average) along the given axis. + +*Parameters*: + axis : {integer}, 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) + else: + return (self - expand_dims(m,axis)) + + def var(self, axis=None, dtype=None): + """Returns the variance, a measure of the spread of a distribution. + +The variance is the average of the squared deviations from the mean, +i.e. var = mean((x - x.mean())**2). + +*Parameters*: + axis : {integer}, 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. + +*Notes*: + The value returned is a biased estimate of the true variance. + For the (more standard) unbiased estimate, use varu. + """ + if self._mask is nomask: + # TODO: Do we keep super, or var _data and take a view ? + return super(MaskedArray, self).var(axis=axis, dtype=dtype) + else: + cnt = self.count(axis=axis) + danom = self.anom(axis=axis, dtype=dtype) + danom *= danom + dvar = narray(danom.sum(axis) / cnt).view(type(self)) + if axis is not None: + dvar._mask = mask_or(self._mask.all(axis), (cnt==1)) + dvar._update_from(self) + return dvar + + def std(self, axis=None, dtype=None): + """Returns the standard deviation, a measure of the spread of a distribution. + +The standard deviation is the square root of the average of the squared +deviations from the mean, i.e. std = sqrt(mean((x - x.mean())**2)). + +*Parameters*: + axis : {integer}, 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. + +*Notes*: + The value returned is a biased estimate of the true standard deviation. + For the more standard unbiased estimate, use stdu. + """ + dvar = self.var(axis,dtype) + if axis is not None or dvar is not masked: + dvar = sqrt(dvar) + return dvar + + #............................................ + def argsort(self, axis=None, fill_value=None, kind='quicksort', + order=None): + """Returns a ndarray of indices that sort the array along the specified axis. + Masked values are filled beforehand to fill_value. + Returns a numpy array. + +*Parameters*: + axis : {integer}, optional + Axis to be indirectly sorted. + If not given, uses a flatten version of the array. + fill_value : {var} + Value used to fill in the masked values. + If not given, self.fill_value is used instead. + kind : {string} + Sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + +*Notes*: + This method executes an indirect sort along the given axis using the algorithm + specified by the kind keyword. It returns an array of indices of the same shape + as 'a' that index data along the given axis in sorted order. + + The various sorts are characterized by average speed, worst case performance + need for work space, and whether they are stable. A stable sort keeps items + with the same key in the same relative order. The three available algorithms + have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is not + along the last axis. Consequently, sorts along the last axis are faster and use + less space than sorts along other axis. + """ + if fill_value is None: + fill_value = default_fill_value(self) + d = self.filled(fill_value).view(ndarray) + return d.argsort(axis=axis, kind=kind, order=order) + #........................ + def argmin(self, axis=None, fill_value=None): + """Returns a ndarray of indices for the minimum values of a along the +specified axis. + +Masked values are treated as if they had the value fill_value. + +*Parameters*: + axis : {integer}, optional + Axis along which to perform the operation. + If None, applies to a flattened version of the array. + fill_value : {var}, optional + Value used to fill in the masked values. + If None, the output of minimum_fill_value(self._data) is used. + """ + if fill_value is None: + fill_value = minimum_fill_value(self) + d = self.filled(fill_value).view(ndarray) + return d.argmin(axis) + #........................ + def argmax(self, axis=None, fill_value=None): + """Returns the array of indices for the maximum values of `a` along the +specified axis. + +Masked values are treated as if they had the value fill_value. + +*Parameters*: + axis : {integer}, optional + Axis along which to perform the operation. + If None, applies to a flattened version of the array. + fill_value : {var}, optional + Value used to fill in the masked values. + If None, the output of maximum_fill_value(self._data) is used. + """ + if fill_value is None: + fill_value = maximum_fill_value(self._data) + d = self.filled(fill_value).view(ndarray) + return d.argmax(axis) + + def sort(self, axis=-1, kind='quicksort', order=None, + endwith=True, fill_value=None): + """Sort a along the given axis. + +*Parameters*: + axis : {integer} + Axis to be indirectly sorted. + kind : {string} + Sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. + order : {var} + If a has fields defined, then the order keyword can be the field + name to sort on or a list (or tuple) of field names to indicate + the order that fields should be used to define the sort. + fill_value : {var} + Value used to fill in the masked values. + If None, use the the output of minimum_fill_value(). + endwith : {boolean} + Whether missing values (if any) should be forced in the upper indices + (at the end of the array) (True) or lower indices (at the beginning). + +*Returns*: + When used as method, returns None. + When used as a function, returns an array. + +*Notes*: + This method sorts 'a' in place along the given axis using the algorithm + specified by the kind keyword. + + The various sorts may characterized by average speed, worst case performance + need for work space, and whether they are stable. A stable sort keeps items + with the same key in the same relative order and is most useful when used w/ + argsort where the key might differ from the items being sorted. + The three available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | O(n^2) | 0 | no | + |'mergesort'| 2 | O(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | O(n*log(n)) | 0 | no | + |------------------------------------------------------| + + """ + if self._mask is nomask: + ndarray.sort(self,axis=axis, kind=kind, order=order) + else: + if fill_value is None: + if endwith: + filler = minimum_fill_value(self) + else: + filler = maximum_fill_value(self) + else: + filler = fill_value + idx = numpy.indices(self.shape) + idx[axis] = self.filled(filler).argsort(axis=axis,kind=kind,order=order) + idx_l = idx.tolist() + tmp_mask = self._mask[idx_l].flat + tmp_data = self._data[idx_l].flat + self.flat = tmp_data + self._mask.flat = tmp_mask + return + + #............................................ + def min(self, axis=None, fill_value=None): + """Returns the minimum of a along the given axis. + +Masked values are filled with fill_value. + +*Parameters*: + axis : {integer}, optional + Axis along which to perform the operation. + If None, applies to a flattened version of the array. + fill_value : {var}, optional + Value used to fill in the masked values. + If None, use the the output of minimum_fill_value(). + """ + mask = self._mask + # Check all/nothing case ...... + if mask is nomask: + return super(MaskedArray, self).min(axis=axis) + elif (not mask.ndim) and mask: + return masked + # Get the mask ................ + if axis is None: + mask = umath.logical_and.reduce(mask.flat) + else: + mask = umath.logical_and.reduce(mask, axis=axis) + # Get the fil value ........... + if fill_value is None: + fill_value = minimum_fill_value(self) + # Get the data ................ + result = self.filled(fill_value).min(axis=axis).view(type(self)) + if result.ndim > 0: + result._mask = mask + return result + #........................ + def max(self, axis=None, fill_value=None): + """Returns the maximum/a along the given axis. + +Masked values are filled with fill_value. + +*Parameters*: + axis : {integer}, optional + Axis along which to perform the operation. + If None, applies to a flattened version of the array. + fill_value : {var}, optional + Value used to fill in the masked values. + If None, use the the output of maximum_fill_value(). + """ + mask = self._mask + # Check all/nothing case ...... + if mask is nomask: + return super(MaskedArray, self).max(axis=axis) + elif (not mask.ndim) and mask: + return masked + # Check the mask .............. + if axis is None: + mask = umath.logical_and.reduce(mask.flat) + else: + mask = umath.logical_and.reduce(mask, axis=axis) + # Get the fill value .......... + if fill_value is None: + fill_value = maximum_fill_value(self) + # Get the data ................ + result = self.filled(fill_value).max(axis=axis).view(type(self)) + if result.ndim > 0: + result._mask = mask + return result + #........................ + def ptp(self, axis=None, fill_value=None): + """Returns the visible data range (max-min) along the given axis. + +*Parameters*: + axis : {integer}, optional + Axis along which to perform the operation. + If None, applies to a flattened version of the array. + fill_value : {var}, optional + Value used to fill in the masked values. + If None, the maximum uses the maximum default, the minimum uses + the minimum default. + """ + return self.max(axis, fill_value) - self.min(axis, fill_value) + + + # Array methods --------------------------------------- +# conj = conjugate = _arraymethod('conjugate') + copy = _arraymethod('copy') + diagonal = _arraymethod('diagonal') + take = _arraymethod('take') +# ravel = _arraymethod('ravel') + transpose = _arraymethod('transpose') + T = property(fget=lambda self:self.transpose()) + swapaxes = _arraymethod('swapaxes') + clip = _arraymethod('clip', onmask=False) + compress = _arraymethod('compress') + copy = _arraymethod('copy') + squeeze = _arraymethod('squeeze') + #-------------------------------------------- + def tolist(self, fill_value=None): + """Copies the data portion of the array to a hierarchical python list and +returns that list. + +Data items are converted to the nearest compatible Python type. +Masked values are converted to fill_value. If fill_value is None, the corresponding +entries in the output list will be ``None``. + """ + if fill_value is not None: + return self.filled(fill_value).tolist() + result = self.filled().tolist() + if self._mask is nomask: + return result + if self.ndim == 0: + return [None] + elif self.ndim == 1: + maskedidx = self._mask.nonzero()[0].tolist() + [operator.setitem(result,i,None) for i in maskedidx] + else: + for idx in zip(*[i.tolist() for i in self._mask.nonzero()]): + tmp = result + for i in idx[:-1]: + tmp = tmp[i] + tmp[idx[-1]] = None + return result + #........................ + def tostring(self, fill_value=None, order='C'): + """Returns a copy of array data as a Python string containing the raw +bytes in the array. + +*Parameters*: + fill_value : {var}, optional + Value used to fill in the masked values. + If None, uses self.fill_value instead. + order : {string} + Order of the data item in the copy {"C","F","A"}. + "C" -- C order (row major) + "Fortran" -- Fortran order (column major) + "Any" -- Current order of array. + None -- Same as "Any" + """ + return self.filled(fill_value).tostring(order=order) + #-------------------------------------------- + # Pickling + def __getstate__(self): + "Returns the internal state of the masked array, for pickling purposes." + state = (1, + self.shape, + self.dtype, + self.flags.fnc, + self._data.tostring(), + getmaskarray(self).tostring(), + self._fill_value, + ) + return state + # + def __setstate__(self, state): + """Restores the internal state of the masked array, for pickling purposes. +``state`` is typically the output of the ``__getstate__`` output, and is a 5-tuple: + + - class name + - a tuple giving the shape of the data + - a typecode for the data + - a binary string for the data + - a binary string for the mask. + """ + (ver, shp, typ, isf, raw, msk, flv) = state + ndarray.__setstate__(self, (shp, typ, isf, raw)) + self._mask.__setstate__((shp, dtype(bool), isf, msk)) + self.fill_value = flv + # + def __reduce__(self): + """Returns a 3-tuple for pickling a MaskedArray.""" + return (_mareconstruct, + (self.__class__, self._baseclass, (0,), 'b', ), + self.__getstate__()) + + +def _mareconstruct(subtype, baseclass, baseshape, basetype,): + """Internal function that builds a new MaskedArray from the information stored +in a pickle.""" + _data = ndarray.__new__(baseclass, baseshape, basetype) + _mask = ndarray.__new__(ndarray, baseshape, 'b1') + return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype, shrink=False) +#MaskedArray.__dump__ = dump +#MaskedArray.__dumps__ = dumps + + + +#####-------------------------------------------------------------------------- +#---- --- Shortcuts --- +#####--------------------------------------------------------------------------- +def isMaskedArray(x): + "Is x a masked array, that is, an instance of MaskedArray?" + return isinstance(x, MaskedArray) +isarray = isMaskedArray +isMA = isMaskedArray #backward compatibility +# We define the masked singleton as a float for higher precedence... +masked_singleton = MaskedArray(0, dtype=float_, mask=True) +masked = masked_singleton + +masked_array = MaskedArray + +def array(data, dtype=None, copy=False, order=False, mask=nomask, subok=True, + keep_mask=True, hard_mask=False, fill_value=None, shrink=True): + """array(data, dtype=None, copy=True, order=False, mask=nomask, + keep_mask=True, shrink=True, fill_value=None) +Acts as shortcut to MaskedArray, with options in a different order for convenience. +And backwards compatibility... + """ + #TODO: we should try to put 'order' somwehere + return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, + keep_mask=keep_mask, hard_mask=hard_mask, + fill_value=fill_value) +array.__doc__ = masked_array.__doc__ + +def is_masked(x): + """Returns whether x has some masked values.""" + m = getmask(x) + if m is nomask: + return False + elif m.any(): + return True + return False + + +#####--------------------------------------------------------------------------- +#---- --- Extrema functions --- +#####--------------------------------------------------------------------------- +class _extrema_operation(object): + "Generic class for maximum/minimum functions." + def __call__(self, a, b=None): + "Executes the call behavior." + if b is None: + return self.reduce(a) + return where(self.compare(a, b), a, b) + #......... + def reduce(self, target, axis=None): + "Reduces target along the given axis." + m = getmask(target) + if axis is not None: + kargs = { 'axis' : axis } + else: + kargs = {} + target = target.ravel() + if not (m is nomask): + m = m.ravel() + if m is nomask: + t = self.ufunc.reduce(target, **kargs) + else: + target = target.filled(self.fill_value_func(target)).view(type(target)) + t = self.ufunc.reduce(target, **kargs) + m = umath.logical_and.reduce(m, **kargs) + if hasattr(t, '_mask'): + t._mask = m + elif m: + t = masked + return t + #......... + def outer (self, a, b): + "Returns the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = logical_or.outer(ma, mb) + result = self.ufunc.outer(filled(a), filled(b)) + result._mask = m + return result + +#............................ +class _minimum_operation(_extrema_operation): + "Object to calculate minima" + def __init__ (self): + """minimum(a, b) or minimum(a) +In one argument case, returns the scalar minimum. + """ + self.ufunc = umath.minimum + self.afunc = amin + self.compare = less + self.fill_value_func = minimum_fill_value + +#............................ +class _maximum_operation(_extrema_operation): + "Object to calculate maxima" + def __init__ (self): + """maximum(a, b) or maximum(a) + In one argument case returns the scalar maximum. + """ + self.ufunc = umath.maximum + self.afunc = amax + self.compare = greater + self.fill_value_func = maximum_fill_value + +#.......................................................... +def min(array, axis=None, out=None): + """Returns the minima along the given axis. +If `axis` is None, applies to the flattened array.""" + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") + if axis is None: + return minimum(array) + else: + return minimum.reduce(array, axis) +min.__doc__ = MaskedArray.min.__doc__ +#............................ +def max(obj, axis=None, out=None): + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") + if axis is None: + return maximum(obj) + else: + return maximum.reduce(obj, axis) +max.__doc__ = MaskedArray.max.__doc__ +#............................. +def ptp(obj, axis=None): + """a.ptp(axis=None) = a.max(axis)-a.min(axis)""" + try: + return obj.max(axis)-obj.min(axis) + except AttributeError: + return max(obj, axis=axis) - min(obj, axis=axis) +ptp.__doc__ = MaskedArray.ptp.__doc__ + + +#####--------------------------------------------------------------------------- +#---- --- Definition of functions from the corresponding methods --- +#####--------------------------------------------------------------------------- +class _frommethod: + """Defines functions from existing MaskedArray methods. +:ivar _methodname (String): Name of the method to transform. + """ + def __init__(self, methodname): + self._methodname = methodname + self.__doc__ = self.getdoc() + def getdoc(self): + "Returns the doc of the function (from the doc of the method)." + try: + return getattr(MaskedArray, self._methodname).__doc__ + except: + return getattr(numpy, self._methodname).__doc__ + def __call__(self, a, *args, **params): + if isinstance(a, MaskedArray): + return getattr(a, self._methodname).__call__(*args, **params) + #FIXME ---- + #As x is not a MaskedArray, we transform it to a ndarray with asarray + #... and call the corresponding method. + #Except that sometimes it doesn't work (try reshape([1,2,3,4],(2,2))) + #we end up with a "SystemError: NULL result without error in PyObject_Call" + #A dirty trick is then to call the initial numpy function... + method = getattr(narray(a, copy=False), self._methodname) + try: + return method(*args, **params) + except SystemError: + return getattr(numpy,self._methodname).__call__(a, *args, **params) + +all = _frommethod('all') +anomalies = anom = _frommethod('anom') +any = _frommethod('any') +conjugate = _frommethod('conjugate') +ids = _frommethod('ids') +nonzero = _frommethod('nonzero') +diagonal = _frommethod('diagonal') +maximum = _maximum_operation() +mean = _frommethod('mean') +minimum = _minimum_operation () +product = _frommethod('prod') +ptp = _frommethod('ptp') +ravel = _frommethod('ravel') +repeat = _frommethod('repeat') +std = _frommethod('std') +sum = _frommethod('sum') +swapaxes = _frommethod('swapaxes') +take = _frommethod('take') +var = _frommethod('var') + +#.............................................................................. +def power(a, b, third=None): + """Computes a**b elementwise. + Masked values are set to 1.""" + if third is not None: + raise MAError, "3-argument power not supported." + ma = getmask(a) + mb = getmask(b) + m = mask_or(ma, mb) + fa = getdata(a) + fb = getdata(b) + if fb.dtype.char in typecodes["Integer"]: + return masked_array(umath.power(fa, fb), m) + md = make_mask((fa < 0), shrink=True) + m = mask_or(m, md) + if m is nomask: + return masked_array(umath.power(fa, fb)) + else: + fa = fa.copy() + fa[(fa < 0)] = 1 + return masked_array(umath.power(fa, fb), m) + +#.............................................................................. +def argsort(a, axis=None, kind='quicksort', order=None, fill_value=None): + "Function version of the eponymous method." + if fill_value is None: + fill_value = default_fill_value(a) + d = filled(a, fill_value) + if axis is None: + return d.argsort(kind=kind, order=order) + return d.argsort(axis, kind=kind, order=order) +argsort.__doc__ = MaskedArray.argsort.__doc__ + +def argmin(a, axis=None, fill_value=None): + "Function version of the eponymous method." + if fill_value is None: + fill_value = default_fill_value(a) + d = filled(a, fill_value) + return d.argmin(axis=axis) +argmin.__doc__ = MaskedArray.argmin.__doc__ + +def argmax(a, axis=None, fill_value=None): + "Function version of the eponymous method." + if fill_value is None: + fill_value = default_fill_value(a) + try: + fill_value = - fill_value + except: + pass + d = filled(a, fill_value) + return d.argmax(axis=axis) +argmin.__doc__ = MaskedArray.argmax.__doc__ + +def sort(a, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None): + "Function version of the eponymous method." + a = narray(a, copy=False, subok=True) + if fill_value is None: + if endwith: + filler = minimum_fill_value(a) + else: + filler = maximum_fill_value(a) + else: + filler = fill_value +# return + indx = numpy.indices(a.shape).tolist() + indx[axis] = filled(a,filler).argsort(axis=axis,kind=kind,order=order) + return a[indx] +sort.__doc__ = MaskedArray.sort.__doc__ + + +def compressed(x): + """Returns a 1-D array of all the non-masked data.""" + if getmask(x) is nomask: + return x + else: + return x.compressed() + +def concatenate(arrays, axis=0): + "Concatenates the arrays along the given axis." + d = numpy.concatenate([getdata(a) for a in arrays], axis) + rcls = get_masked_subclass(*arrays) + data = d.view(rcls) + # Check whether one of the arrays has a non-empty mask... + for x in arrays: + if getmask(x) is not nomask: + break + return data + # OK, so we have to concatenate the masks + dm = numpy.concatenate([getmaskarray(a) for a in arrays], axis) + shrink = numpy.logical_or.reduce([getattr(a,'_shrinkmask',True) for a in arrays]) + if shrink and not dm.any(): + data._mask = nomask + else: + data._mask = dm.reshape(d.shape) + return data + +def count(a, axis = None): + return masked_array(a, copy=False).count(axis) +count.__doc__ = MaskedArray.count.__doc__ + + +def expand_dims(x,axis): + "Expands the shape of the array by including a new axis before the given one." + result = n_expand_dims(x,axis) + if isinstance(x, MaskedArray): + new_shape = result.shape + result = x.view() + result.shape = new_shape + if result._mask is not nomask: + result._mask.shape = new_shape + return result + +#...................................... +def left_shift (a, n): + "Left shift n bits." + m = getmask(a) + if m is nomask: + d = umath.left_shift(filled(a), n) + return masked_array(d) + else: + d = umath.left_shift(filled(a, 0), n) + return masked_array(d, mask=m) + +def right_shift (a, n): + "Right shift n bits." + m = getmask(a) + if m is nomask: + d = umath.right_shift(filled(a), n) + return masked_array(d) + else: + d = umath.right_shift(filled(a, 0), n) + return masked_array(d, mask=m) + +#...................................... +def put(a, indices, values, mode='raise'): + """Sets storage-indexed locations to corresponding values. +Values and indices are filled if necessary.""" + # We can't use 'frommethod', the order of arguments is different + try: + return a.put(indices, values, mode=mode) + except AttributeError: + return narray(a, copy=False).put(indices, values, mode=mode) + +def putmask(a, mask, values): #, mode='raise'): + """Sets a.flat[n] = values[n] for each n where mask.flat[n] is true. + +If values is not the same size of a and mask then it will repeat as necessary. +This gives different behavior than a[mask] = values.""" + # We can't use 'frommethod', the order of arguments is different + try: + return a.putmask(values, mask) + except AttributeError: + return numpy.putmask(narray(a, copy=False), mask, values) + +def transpose(a,axes=None): + """Returns 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 dimensions compared +to the original. + """ + #We can't use 'frommethod', as 'transpose' doesn't take keywords + try: + return a.transpose(axes) + except AttributeError: + return narray(a, copy=False).transpose(axes).view(MaskedArray) + +def reshape(a, new_shape): + """Changes the shape of the array a to new_shape.""" + #We can't use 'frommethod', it whine about some parameters. Dmmit. + try: + return a.reshape(new_shape) + except AttributeError: + return narray(a, copy=False).reshape(new_shape).view(MaskedArray) + +def resize(x, new_shape): + """Returns a new array with the specified shape. + +The total size of the original array can be any size. +The new array is filled with repeated copies of a. If a was masked, the new array +will be masked, and the new mask will be a repetition of the old one. + """ + # We can't use _frommethods here, as N.resize is notoriously whiny. + m = getmask(x) + if m is not nomask: + m = numpy.resize(m, new_shape) + result = numpy.resize(x, new_shape).view(get_masked_subclass(x)) + if result.ndim: + result._mask = m + return result + + +#................................................ +def rank(obj): + "maskedarray version of the numpy function." + return fromnumeric.rank(getdata(obj)) +rank.__doc__ = numpy.rank.__doc__ +# +def shape(obj): + "maskedarray version of the numpy function." + return fromnumeric.shape(getdata(obj)) +shape.__doc__ = numpy.shape.__doc__ +# +def size(obj, axis=None): + "maskedarray version of the numpy function." + return fromnumeric.size(getdata(obj), axis) +size.__doc__ = numpy.size.__doc__ +#................................................ + +#####-------------------------------------------------------------------------- +#---- --- Extra functions --- +#####-------------------------------------------------------------------------- +def where (condition, x=None, y=None): + """where(condition | x, y) + +Returns a (subclass of) masked array, shaped like condition, where the elements +are x when condition is True, and y otherwise. If neither x nor y are given, +returns a tuple of indices where condition is True (a la condition.nonzero()). + +*Parameters*: + condition : {var} + The condition to meet. Must be convertible to an integer array. + x : {var}, optional + Values of the output when the condition is met + y : {var}, optional + Values of the output when the condition is not met. + """ + if x is None and y is None: + return filled(condition, 0).nonzero() + elif x is None or y is None: + raise ValueError, "Either both or neither x and y should be given." + # Get the condition ............... + fc = filled(condition, 0).astype(bool_) + notfc = numpy.logical_not(fc) + # Get the data ...................................... + xv = getdata(x) + yv = getdata(y) + if x is masked: + ndtype = yv.dtype + xm = numpy.ones(fc.shape, dtype=MaskType) + elif y is masked: + ndtype = xv.dtype + ym = numpy.ones(fc.shape, dtype=MaskType) + else: + ndtype = numpy.max([xv.dtype, yv.dtype]) + xm = getmask(x) + d = numpy.empty(fc.shape, dtype=ndtype).view(MaskedArray) + numpy.putmask(d._data, fc, xv.astype(ndtype)) + numpy.putmask(d._data, notfc, yv.astype(ndtype)) + d._mask = numpy.zeros(fc.shape, dtype=MaskType) + numpy.putmask(d._mask, fc, getmask(x)) + numpy.putmask(d._mask, notfc, getmask(y)) + d._mask |= getmaskarray(condition) + if not d._mask.any(): + d._mask = nomask + return d +# # Get the data as a (subclass of) MaskedArray +# xv = getdata(x) +# yv = getdata(y) +# d = numpy.choose(fc, (yv, xv)).view(MaskedArray) +# # Get the mask .................... +# xm = getmask(x) +# ym = getmask(y) +# d.mask = numpy.choose(fc, (ym, xm)) | getmask(condition) +# # Fix the dtype if one of the values was masked, to prevent an upload to float +# if y is masked: +# ndtype = xv.dtype +# elif x is masked: +# ndtype = yv.dtype +# else: +# ndtype = d.dtype +# return d.astype(ndtype) + +def choose (indices, t, out=None, mode='raise'): + "Returns array shaped like indices with elements chosen from t" + #TODO: implement options `out` and `mode`, if possible. + def fmask (x): + "Returns the filled array, or True if masked." + if x is masked: + return 1 + return filled(x) + def nmask (x): + "Returns the mask, True if ``masked``, False if ``nomask``." + if x is masked: + return 1 + m = getmask(x) + if m is nomask: + return 0 + return m + c = filled(indices, 0) + masks = [nmask(x) for x in t] + a = [fmask(x) for x in t] + d = numpy.choose(c, a) + m = numpy.choose(c, masks) + m = make_mask(mask_or(m, getmask(indices)), copy=0, shrink=True) + return masked_array(d, mask=m) + +def round_(a, decimals=0, out=None): + """Returns a copy of a, rounded to 'decimals' places. + +When 'decimals' is negative, it specifies the number of positions to the left of +the decimal point. The real and imaginary parts of complex numbers are rounded +separately. Nothing is done if the array is not of float type and 'decimals' is +greater than or equal to 0. + +*Parameters*: + decimals : {integer} + Number of decimals to round to. May be negative. + out : {ndarray} + Existing array to use for output. + If not given, returns a default copy of a. + +*Notes*: + If out is given and does not have a mask attribute, the mask of a is lost! + """ + if out is None: + result = fromnumeric.round_(getdata(a), decimals, out) + if isinstance(a,MaskedArray): + result = result.view(type(a)) + result._mask = a._mask + else: + result = result.view(MaskedArray) + return result + else: + fromnumeric.round_(getdata(a), decimals, out) + if hasattr(out, '_mask'): + out._mask = getmask(a) + return out + +def arange(stop, start=None, step=1, dtype=None): + "maskedarray version of the numpy function." + return numpy.arange(stop, start, step, dtype).view(MaskedArray) +arange.__doc__ = numpy.arange.__doc__ + +def inner(a, b): + "maskedarray version of the numpy function." + fa = filled(a, 0) + fb = filled(b, 0) + if len(fa.shape) == 0: + fa.shape = (1,) + if len(fb.shape) == 0: + fb.shape = (1,) + return numpy.inner(fa, fb).view(MaskedArray) +inner.__doc__ = numpy.inner.__doc__ +inner.__doc__ += "\n*Notes*:\n Masked values are replaced by 0." +innerproduct = inner + +def outer(a, b): + "maskedarray version of the numpy function." + fa = filled(a, 0).ravel() + fb = filled(b, 0).ravel() + d = numeric.outer(fa, fb) + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + return masked_array(d) + ma = getmaskarray(a) + mb = getmaskarray(b) + m = make_mask(1-numeric.outer(1-ma, 1-mb), copy=0) + return masked_array(d, mask=m) +outer.__doc__ = numpy.outer.__doc__ +outer.__doc__ += "\n*Notes*:\n Masked values are replaced by 0." +outerproduct = outer + +def allequal (a, b, fill_value=True): + """Returns True if all entries of a and b are equal, using fill_value +as a truth value where either or both are masked. + """ + m = mask_or(getmask(a), getmask(b)) + if m is nomask: + x = getdata(a) + y = getdata(b) + d = umath.equal(x, y) + return d.all() + elif fill_value: + x = getdata(a) + y = getdata(b) + d = umath.equal(x, y) + dm = array(d, mask=m, copy=False) + return dm.filled(True).all(None) + else: + return False + +def allclose (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8): + """ Returns True if all elements of a and b are equal subject to given tolerances. +If fill_value is True, masked values are considered equal. +If fill_value is False, masked values considered unequal. +The relative error rtol should be positive and << 1.0 +The absolute error atol comes into play for those elements of b that are very small +or zero; it says how small `a` must be also. + """ + m = mask_or(getmask(a), getmask(b)) + d1 = getdata(a) + d2 = getdata(b) + x = filled(array(d1, copy=0, mask=m), fill_value).astype(float) + y = filled(array(d2, copy=0, mask=m), 1).astype(float) + d = umath.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y)) + return fromnumeric.alltrue(fromnumeric.ravel(d)) + +#.............................................................................. +def asarray(a, dtype=None): + """asarray(data, dtype) = array(data, dtype, copy=0, subok=0) +Returns a as a MaskedArray object of the given dtype. +If dtype is not given or None, is is set to the dtype of a. +No copy is performed if a is already an array. +Subclasses are converted to the base class MaskedArray. + """ + return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False) + +def asanyarray(a, dtype=None): + """asanyarray(data, dtype) = array(data, dtype, copy=0, subok=1) +Returns a as an masked array. +If dtype is not given or None, is is set to the dtype of a. +No copy is performed if a is already an array. +Subclasses are conserved. + """ + return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True) + + +def empty(new_shape, dtype=float): + "maskedarray version of the numpy function." + return numpy.empty(new_shape, dtype).view(MaskedArray) +empty.__doc__ = numpy.empty.__doc__ + +def empty_like(a): + "maskedarray version of the numpy function." + return numpy.empty_like(a).view(MaskedArray) +empty_like.__doc__ = numpy.empty_like.__doc__ + +def ones(new_shape, dtype=float): + "maskedarray version of the numpy function." + return numpy.ones(new_shape, dtype).view(MaskedArray) +ones.__doc__ = numpy.ones.__doc__ + +def zeros(new_shape, dtype=float): + "maskedarray version of the numpy function." + return numpy.zeros(new_shape, dtype).view(MaskedArray) +zeros.__doc__ = numpy.zeros.__doc__ + +#####-------------------------------------------------------------------------- +#---- --- Pickling --- +#####-------------------------------------------------------------------------- +def dump(a,F): + """Pickles the MaskedArray `a` to the file `F`. +`F` can either be the handle of an exiting file, or a string representing a file name. + """ + if not hasattr(F,'readline'): + F = open(F,'w') + return cPickle.dump(a,F) + +def dumps(a): + """Returns 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.""" + if not hasattr(F, 'readline'): + F = open(F,'r') + return cPickle.load(F) + +def loads(strg): + "Loads a pickle from the current string.""" + return cPickle.loads(strg) + + +############################################################################### + +if __name__ == '__main__': + from maskedarray.testutils import assert_equal, assert_almost_equal + + # Small arrays .................................. + xs = numpy.random.uniform(-1,1,6).reshape(2,3) + ys = numpy.random.uniform(-1,1,6).reshape(2,3) + zs = xs + 1j * ys + m1 = [[True, False, False], [False, False, True]] + m2 = [[True, False, True], [False, False, True]] + nmxs = numpy.ma.array(xs, mask=m1) + nmys = numpy.ma.array(ys, mask=m2) + nmzs = numpy.ma.array(zs, mask=m1) + mmxs = array(xs, mask=m1) + mmys = array(ys, mask=m2) + mmzs = array(zs, mask=m1) + # Big arrays .................................... + xl = numpy.random.uniform(-1,1,100*100).reshape(100,100) + yl = numpy.random.uniform(-1,1,100*100).reshape(100,100) + zl = xl + 1j * yl + maskx = xl > 0.8 + masky = yl < -0.8 + nmxl = numpy.ma.array(xl, mask=maskx) + nmyl = numpy.ma.array(yl, mask=masky) + nmzl = numpy.ma.array(zl, mask=maskx) + mmxl = array(xl, mask=maskx, shrink=True) + mmyl = array(yl, mask=masky, shrink=True) + mmzl = array(zl, mask=maskx, shrink=True) + # + z = empty(3,) + mmys.all(0, out=z) + + if 1: + x = numpy.array([[ 0.13, 0.26, 0.90], + [ 0.28, 0.33, 0.63], + [ 0.31, 0.87, 0.70]]) + m = numpy.array([[ True, False, False], + [False, False, False], + [True, True, False]], dtype=numpy.bool_) + mx = masked_array(x, mask=m) + xbig = numpy.array([[False, False, True], + [False, False, True], + [False, True, True]], dtype=numpy.bool_) + mxbig = (mx > 0.5) + mxsmall = (mx < 0.5) + # + assert (mxbig.all()==False) + assert (mxbig.any()==True) + assert_equal(mxbig.all(0),[False, False, True]) + assert_equal(mxbig.all(1), [False, False, True]) + assert_equal(mxbig.any(0),[False, False, True]) + assert_equal(mxbig.any(1), [True, True, True]) + + if 1: + xx = array([1+10j,20+2j], mask=[1,0]) + assert_equal(xx.imag,[10,2]) + assert_equal(xx.imag.filled(), [1e+20,2]) + assert_equal(xx.real,[1,20]) + assert_equal(xx.real.filled(), [1e+20,20]) Added: trunk/scipy/sandbox/maskedarray/extras.py =================================================================== --- trunk/scipy/sandbox/maskedarray/extras.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/extras.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,722 @@ +"""Masked arrays add-ons. + +A collection of utilities for maskedarray + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: extras.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + +__all__ = [ +'apply_along_axis', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', +'vstack', 'hstack', 'dstack', 'row_stack', 'column_stack', +'compress_rowcols', 'compress_rows', 'compress_cols', 'count_masked', +'dot', 'hsplit', +'mask_rowcols','mask_rows','mask_cols','masked_all','masked_all_like', +'mediff1d', 'mr_', +'notmasked_edges','notmasked_contiguous', +'stdu', 'varu', + ] + +from itertools import groupby + +import core +from core import * + +import numpy +from numpy import float_ +import numpy.core.umath as umath +import numpy.core.numeric as numeric +from numpy.core.numeric import ndarray +from numpy.core.numeric import array as nxarray +from numpy.core.fromnumeric import asarray as nxasarray + +from numpy.lib.index_tricks import AxisConcatenator +import numpy.lib.function_base as function_base + +#............................................................................... +def issequence(seq): + """Returns True if the argument is a sequence (ndarray, list or tuple).""" + if isinstance(seq, ndarray): + return True + elif isinstance(seq, tuple): + return True + elif isinstance(seq, list): + return True + return False + +def count_masked(arr, axis=None): + """Counts the number of masked elements along the given axis. + +*Parameters*: + axis : {integer}, optional + Axis along which to count. + If None (default), a flattened version of the array is used. + """ + m = getmaskarray(arr) + return m.sum(axis) + +def masked_all(shape, dtype=float_): + """Returns an empty masked array of the given shape and dtype, + where all the data are masked. + +*Parameters*: + dtype : {dtype}, optional + Data type of the output. + """ + a = masked_array(numeric.empty(shape, dtype), + mask=numeric.ones(shape, bool_)) + return a + +def masked_all_like(arr): + """Returns an empty masked array of the same shape and dtype as the array `a`, + where all the data are masked.""" + a = masked_array(numeric.empty_like(arr), + mask=numeric.ones(arr.shape, bool_)) + return a + +#####-------------------------------------------------------------------------- +#---- --- New methods --- +#####-------------------------------------------------------------------------- +def varu(a, axis=None, dtype=None): + """Returns an unbiased estimate of the variance. + i.e. var = sum((x - x.mean())**2)/(size(x,axis)-1) + +*Parameters*: + axis : {integer}, 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. + +*Notes*: + The value returned is an unbiased estimate of the true variance. + For the (less standard) biased estimate, use var. + """ + a = asarray(a) + cnt = a.count(axis=axis) + anom = a.anom(axis=axis, dtype=dtype) + anom *= anom + dvar = anom.sum(axis) / (cnt-1) + if axis is None: + return dvar + dvar.__setmask__(mask_or(a._mask.all(axis), (cnt==1))) + return dvar +# return a.__class__(dvar, +# mask=mask_or(a._mask.all(axis), (cnt==1)), +# fill_value=a._fill_value) + +def stdu(a, axis=None, dtype=None): + """Returns an unbiased estimate of the standard deviation. + The standard deviation is the square root of the average of the squared + deviations from the mean, i.e. stdu = sqrt(varu(x)). + +*Parameters*: + axis : {integer}, 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. + +*Notes*: + The value returned is an unbiased estimate of the true standard deviation. + For the (less standard) biased estimate, use std. + """ + a = asarray(a) + dvar = a.varu(axis,dtype) + if axis is None: + if dvar is masked: + return masked + else: + # Should we use umath.sqrt instead ? + return sqrt(dvar) + return sqrt(dvar) +# return a.__class__(sqrt(dvar._data), mask=dvar._mask, +# fill_value=a._fill_value) + +MaskedArray.stdu = stdu +MaskedArray.varu = varu + +#####-------------------------------------------------------------------------- +#---- --- Standard functions --- +#####-------------------------------------------------------------------------- +class _fromnxfunction: + """Defines a wrapper to adapt numpy functions to masked arrays.""" + def __init__(self, funcname): + self._function = funcname + self.__doc__ = self.getdoc() + def getdoc(self): + "Retrieves the __doc__ string from the function." + return getattr(numpy, self._function).__doc__ +\ + "*Notes*:\n (The function is applied to both the _data and the _mask, if any.)" + def __call__(self, *args, **params): + func = getattr(numpy, self._function) + if len(args)==1: + x = args[0] + if isinstance(x,ndarray): + _d = func(nxasarray(x), **params) + _m = func(getmaskarray(x), **params) + return masked_array(_d, mask=_m) + elif isinstance(x, tuple) or isinstance(x, list): + _d = func(tuple([nxasarray(a) for a in x]), **params) + _m = func(tuple([getmaskarray(a) for a in x]), **params) + return masked_array(_d, mask=_m) + else: + arrays = [] + args = list(args) + while len(args)>0 and issequence(args[0]): + arrays.append(args.pop(0)) + res = [] + for x in arrays: + _d = func(nxasarray(x), *args, **params) + _m = func(getmaskarray(x), *args, **params) + res.append(masked_array(_d, mask=_m)) + return res + +atleast_1d = _fromnxfunction('atleast_1d') +atleast_2d = _fromnxfunction('atleast_2d') +atleast_3d = _fromnxfunction('atleast_3d') + +vstack = row_stack = _fromnxfunction('vstack') +hstack = _fromnxfunction('hstack') +column_stack = _fromnxfunction('column_stack') +dstack = _fromnxfunction('dstack') + +hsplit = _fromnxfunction('hsplit') + +#####-------------------------------------------------------------------------- +#---- +#####-------------------------------------------------------------------------- +def flatten_inplace(seq): + """Flattens a sequence in place.""" + k = 0 + while (k != len(seq)): + while hasattr(seq[k],'__iter__'): + seq[k:(k+1)] = seq[k] + k += 1 + return seq + + +def apply_along_axis(func1d,axis,arr,*args,**kwargs): + """ Execute func1d(arr[i],*args) where func1d takes 1-D arrays + and arr is an N-d array. i varies so as to apply the function + along the given axis for each 1-d subarray in arr. + """ + arr = core.array(arr, copy=False, subok=True) + nd = arr.ndim + if axis < 0: + axis += nd + if (axis >= nd): + raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d." + % (axis,nd)) + ind = [0]*(nd-1) + i = numeric.zeros(nd,'O') + indlist = range(nd) + indlist.remove(axis) + i[axis] = slice(None,None) + outshape = numeric.asarray(arr.shape).take(indlist) + i.put(indlist, ind) + j = i.copy() + res = func1d(arr[tuple(i.tolist())],*args,**kwargs) + # if res is a number, then we have a smaller output array + asscalar = numeric.isscalar(res) + if not asscalar: + try: + len(res) + except TypeError: + asscalar = True + # Note: we shouldn't set the dtype of the output from the first result... + #...so we force the type to object, and build a list of dtypes + #...we'll just take the largest, to avoid some downcasting + dtypes = [] + if asscalar: + dtypes.append(numeric.asarray(res).dtype) + outarr = zeros(outshape, object_) + outarr[tuple(ind)] = res + Ntot = numeric.product(outshape) + k = 1 + while k < Ntot: + # increment the index + ind[-1] += 1 + n = -1 + while (ind[n] >= outshape[n]) and (n > (1-nd)): + ind[n-1] += 1 + ind[n] = 0 + n -= 1 + i.put(indlist,ind) + res = func1d(arr[tuple(i.tolist())],*args,**kwargs) + outarr[tuple(ind)] = res + dtypes.append(asarray(res).dtype) + k += 1 + else: + res = core.array(res, copy=False, subok=True) + j = i.copy() + j[axis] = ([slice(None,None)] * res.ndim) + j.put(indlist, ind) + Ntot = numeric.product(outshape) + holdshape = outshape + outshape = list(arr.shape) + outshape[axis] = res.shape + dtypes.append(asarray(res).dtype) + outshape = flatten_inplace(outshape) + outarr = zeros(outshape, object_) + outarr[tuple(flatten_inplace(j.tolist()))] = res + k = 1 + while k < Ntot: + # increment the index + ind[-1] += 1 + n = -1 + while (ind[n] >= holdshape[n]) and (n > (1-nd)): + ind[n-1] += 1 + ind[n] = 0 + n -= 1 + i.put(indlist, ind) + j.put(indlist, ind) + res = func1d(arr[tuple(i.tolist())],*args,**kwargs) + outarr[tuple(flatten_inplace(j.tolist()))] = res + dtypes.append(asarray(res).dtype) + k += 1 + max_dtypes = numeric.dtype(numeric.asarray(dtypes).max()) + if not hasattr(arr, '_mask'): + result = numeric.asarray(outarr, dtype=max_dtypes) + else: + result = core.asarray(outarr, dtype=max_dtypes) + result.fill_value = core.default_fill_value(result) + return result + +def average (a, axis=None, weights=None, returned=False): + """Averages the array over the given axis. + +*Parameters*: + axis : {integer}, optional + Axis along which to perform the operation. + If None, applies to a flattened version of the array. + weights : {sequence}, optional + Sequence of weights. + The weights must have the shape of a, or be 1D with length the size of a + along the given axis. + If no weights are given, weights are assumed to be 1. + returned : {boolean} + Flag indicating whether a tuple (result, sum of weights/counts) should be + returned as output (True), or just the result (False). + """ + a = asarray(a) + mask = a.mask + ash = a.shape + if ash == (): + ash = (1,) + if axis is None: + if mask is nomask: + if weights is None: + n = a.sum(axis=None) + d = float(a.size) + else: + w = filled(weights, 0.0).ravel() + n = umath.add.reduce(a._data.ravel() * w) + d = umath.add.reduce(w) + del w + else: + if weights is None: + n = a.filled(0).sum(axis=None) + d = umath.add.reduce((-mask).ravel().astype(int_)) + else: + w = array(filled(weights, 0.0), float, mask=mask).ravel() + n = add.reduce(a.ravel() * w) + d = add.reduce(w) + del w + else: + if mask is nomask: + if weights is None: + d = ash[axis] * 1.0 + n = add.reduce(a._data, axis, dtype=float_) + else: + w = filled(weights, 0.0) + wsh = w.shape + if wsh == (): + wsh = (1,) + if wsh == ash: + w = numeric.array(w, float_, copy=0) + n = add.reduce(a*w, axis) + d = add.reduce(w, axis) + del w + elif wsh == (ash[axis],): + ni = ash[axis] + r = [None]*len(ash) + r[axis] = slice(None, None, 1) + w = eval ("w["+ repr(tuple(r)) + "] * ones(ash, float)") + n = add.reduce(a*w, axis, dtype=float_) + d = add.reduce(w, axis, dtype=float_) + del w, r + else: + raise ValueError, 'average: weights wrong shape.' + else: + if weights is None: + n = add.reduce(a, axis, dtype=float_) + d = umath.add.reduce((-mask), axis=axis, dtype=float_) + else: + w = filled(weights, 0.0) + wsh = w.shape + if wsh == (): + wsh = (1,) + if wsh == ash: + w = array(w, dtype=float_, mask=mask, copy=0) + n = add.reduce(a*w, axis, dtype=float_) + d = add.reduce(w, axis, dtype=float_) + elif wsh == (ash[axis],): + ni = ash[axis] + r = [None]*len(ash) + r[axis] = slice(None, None, 1) + w = eval ("w["+ repr(tuple(r)) + "] * masked_array(ones(ash, float), mask)") + n = add.reduce(a*w, axis, dtype=float_) + d = add.reduce(w, axis, dtype=float_) + else: + raise ValueError, 'average: weights wrong shape.' + del w + if n is masked or d is masked: + return masked + result = n/d + del n + + if isMaskedArray(result): + if ((axis is None) or (axis==0 and a.ndim == 1)) and \ + (result.mask is nomask): + result = result._data + if returned: + if not isMaskedArray(d): + d = masked_array(d) + if isinstance(d, ndarray) and (not d.shape == result.shape): + d = ones(result.shape, dtype=float_) * d + if returned: + return result, d + else: + return result + +#.............................................................................. +def compress_rowcols(x, axis=None): + """Suppresses the rows and/or columns of a 2D array that contains masked values. + + The suppression behavior is selected with the `axis`parameter. + - If axis is None, rows and columns are suppressed. + - If axis is 0, only rows are suppressed. + - If axis is 1 or -1, only columns are suppressed. + +*Returns*: + compressed_array : a ndarray. + """ + x = asarray(x) + if x.ndim != 2: + raise NotImplementedError, "compress2d works for 2D arrays only." + m = getmask(x) + # Nothing is masked: return x + if m is nomask or not m.any(): + return x._data + # All is masked: return empty + if m.all(): + return nxarray([]) + # Builds a list of rows/columns indices + (idxr, idxc) = (range(len(x)), range(x.shape[1])) + masked = m.nonzero() + if not axis: + for i in function_base.unique(masked[0]): + idxr.remove(i) + if axis in [None, 1, -1]: + for j in function_base.unique(masked[1]): + idxc.remove(j) + return x._data[idxr][:,idxc] + +def compress_rows(a): + """Suppresses whole rows of a 2D array that contain masked values.""" + return compress_rowcols(a,0) + +def compress_cols(a): + """Suppresses whole columnss of a 2D array that contain masked values.""" + return compress_rowcols(a,1) + +def mask_rowcols(a, axis=None): + """Masks whole rows and/or columns of a 2D array that contain masked values. + The masking behavior is selected with the `axis`parameter. + - If axis is None, rows and columns are masked. + - If axis is 0, only rows are masked. + - If axis is 1 or -1, only columns are masked. + Returns a *pure* ndarray. + """ + a = asarray(a) + if a.ndim != 2: + raise NotImplementedError, "compress2d works for 2D arrays only." + m = getmask(a) + # Nothing is masked: return a + if m is nomask or not m.any(): + return a + maskedval = m.nonzero() + a._mask = a._mask.copy() + if not axis: + a[function_base.unique(maskedval[0])] = masked + if axis in [None, 1, -1]: + a[:,function_base.unique(maskedval[1])] = masked + return a + +def mask_rows(a, axis=None): + """Masks whole rows of a 2D array that contain masked values.""" + return mask_rowcols(a, 0) + +def mask_cols(a, axis=None): + """Masks whole columns of a 2D array that contain masked values.""" + return mask_rowcols(a, 1) + + +def dot(a,b, strict=False): + """Returns the dot product of two 2D masked arrays a and b. + + Like the generic numpy equivalent, the product sum is over the last dimension + of a and the second-to-last dimension of b. + If strict is True, masked values are propagated: if a masked value appears + in a row or column, the whole row or column is considered masked. + +*Parameters*: + strict : {boolean} + Whether masked data are propagated (True) or set to 0 for the computation. + +*Note*: + The first argument is not conjugated. + """ + #TODO: Works only with 2D arrays. There should be a way to get it to run with higher dimension + if strict and (a.ndim == 2) and (b.ndim == 2): + a = mask_rows(a) + b = mask_cols(b) + # + d = numpy.dot(filled(a, 0), filled(b, 0)) + # + am = (~getmaskarray(a)) + bm = (~getmaskarray(b)) + m = ~numpy.dot(am,bm) + return masked_array(d, mask=m) + +#............................................................................... +def mediff1d(array, to_end=None, to_begin=None): + """Returns the differences between consecutive elements of an array, possibly with + prefixed and/or appended values. + +*Parameters*: + array : {array} + Input array, will be flattened before the difference is taken. + to_end : {number}, optional + If provided, this number will be tacked onto the end of the returned + differences. + to_begin : {number}, optional + If provided, this number will be taked onto the beginning of the + returned differences. + +*Returns*: + ed : {array} + The differences. Loosely, this will be (ary[1:] - ary[:-1]). + """ + a = masked_array(array, copy=True) + if a.ndim > 1: + a.reshape((a.size,)) + (d, m, n) = (a._data, a._mask, a.size-1) + dd = d[1:]-d[:-1] + if m is nomask: + dm = nomask + else: + dm = m[1:]-m[:-1] + # + if to_end is not None: + to_end = asarray(to_end) + nend = to_end.size + if to_begin is not None: + to_begin = asarray(to_begin) + nbegin = to_begin.size + r_data = numeric.empty((n+nend+nbegin,), dtype=a.dtype) + r_mask = numeric.zeros((n+nend+nbegin,), dtype=bool_) + r_data[:nbegin] = to_begin._data + r_mask[:nbegin] = to_begin._mask + r_data[nbegin:-nend] = dd + r_mask[nbegin:-nend] = dm + else: + r_data = numeric.empty((n+nend,), dtype=a.dtype) + r_mask = numeric.zeros((n+nend,), dtype=bool_) + r_data[:-nend] = dd + r_mask[:-nend] = dm + r_data[-nend:] = to_end._data + r_mask[-nend:] = to_end._mask + # + elif to_begin is not None: + to_begin = asarray(to_begin) + nbegin = to_begin.size + r_data = numeric.empty((n+nbegin,), dtype=a.dtype) + r_mask = numeric.zeros((n+nbegin,), dtype=bool_) + r_data[:nbegin] = to_begin._data + r_mask[:nbegin] = to_begin._mask + r_data[nbegin:] = dd + r_mask[nbegin:] = dm + # + else: + r_data = dd + r_mask = dm + return masked_array(r_data, mask=r_mask) + + + + +#####-------------------------------------------------------------------------- +#---- --- Concatenation helpers --- +#####-------------------------------------------------------------------------- + +class mconcatenator(AxisConcatenator): + """Translates slice objects to concatenation along an axis.""" + + def __init__(self, axis=0): + AxisConcatenator.__init__(self, axis, matrix=False) + + def __getitem__(self,key): + if isinstance(key, str): + raise MAError, "Unavailable for masked array." + if type(key) is not tuple: + key = (key,) + objs = [] + scalars = [] + final_dtypedescr = None + for k in range(len(key)): + scalar = False + if type(key[k]) is slice: + step = key[k].step + start = key[k].start + stop = key[k].stop + if start is None: + start = 0 + if step is None: + step = 1 + if type(step) is type(1j): + size = int(abs(step)) + newobj = function_base.linspace(start, stop, num=size) + else: + newobj = numeric.arange(start, stop, step) + elif type(key[k]) is str: + if (key[k] in 'rc'): + self.matrix = True + self.col = (key[k] == 'c') + continue + try: + self.axis = int(key[k]) + continue + except (ValueError, TypeError): + raise ValueError, "Unknown special directive" + elif type(key[k]) in numeric.ScalarType: + newobj = asarray([key[k]]) + scalars.append(k) + scalar = True + else: + newobj = key[k] + objs.append(newobj) + if isinstance(newobj, numeric.ndarray) and not scalar: + if final_dtypedescr is None: + final_dtypedescr = newobj.dtype + elif newobj.dtype > final_dtypedescr: + final_dtypedescr = newobj.dtype + if final_dtypedescr is not None: + for k in scalars: + objs[k] = objs[k].astype(final_dtypedescr) + res = concatenate(tuple(objs),axis=self.axis) + return self._retval(res) + +class mr_class(mconcatenator): + """Translates slice objects to concatenation along the first axis. + + For example: + >>> mr_[array([1,2,3]), 0, 0, array([4,5,6])] + array([1, 2, 3, 0, 0, 4, 5, 6]) + """ + def __init__(self): + mconcatenator.__init__(self, 0) + +mr_ = mr_class() + +#####-------------------------------------------------------------------------- +#---- --- +#####-------------------------------------------------------------------------- + +def flatnotmasked_edges(a): + """Finds the indices of the first and last not masked values in a 1D masked array. + If all values are masked, returns None. + """ + m = getmask(a) + if m is nomask or not numpy.any(m): + return [0,-1] + unmasked = numeric.flatnonzero(~m) + if len(unmasked) > 0: + return unmasked[[0,-1]] + else: + return None + +def notmasked_edges(a, axis=None): + """Finds the indices of the first and last not masked values along the given + axis in a masked array. + If all values are masked, returns None. + Otherwise, returns a list of 2 tuples, corresponding to the indices of the + first and last unmasked values respectively. + """ + a = asarray(a) + if axis is None or a.ndim == 1: + return flatnotmasked_edges(a) + m = getmask(a) + idx = array(numpy.indices(a.shape), mask=nxasarray([m]*a.ndim)) + return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), + tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]),] + +def flatnotmasked_contiguous(a): + """Finds contiguous unmasked data in a flattened masked array. + Returns a sorted sequence of slices (start index, end index). + """ + m = getmask(a) + if m is nomask: + return (a.size, [0,-1]) + unmasked = numeric.flatnonzero(~m) + if len(unmasked) == 0: + return None + result = [] + for k, group in groupby(enumerate(unmasked), lambda (i,x):i-x): + tmp = numpy.fromiter((g[1] for g in group), int_) +# result.append((tmp.size, tuple(tmp[[0,-1]]))) + result.append( slice(tmp[0],tmp[-1]) ) + result.sort() + return result + +def notmasked_contiguous(a, axis=None): + """Finds contiguous unmasked data in a masked array along the given axis. + Returns a sorted sequence of slices (start index, end index). + Note: Only accepts 2D arrays at most. + """ + a = asarray(a) + nd = a.ndim + if nd > 2: + raise NotImplementedError,"Currently limited to atmost 2D array." + if axis is None or nd == 1: + return flatnotmasked_contiguous(a) + # + result = [] + # + other = (axis+1)%2 + idx = [0,0] + idx[axis] = slice(None,None) + # + for i in range(a.shape[other]): + idx[other] = i + result.append( flatnotmasked_contiguous(a[idx]) ) + return result + +################################################################################ +if __name__ == '__main__': + # + import numpy as N + from maskedarray.testutils import assert_equal + if 1: + b = ones(5) + m = [1,0,0,0,0] + d = masked_array(b,mask=m) + c = mr_[d,0,0,d] Added: trunk/scipy/sandbox/maskedarray/morestats.py =================================================================== --- trunk/scipy/sandbox/maskedarray/morestats.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/morestats.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,406 @@ +""" +Generic statistics functions, with support to MA. + +:author: Pierre GF Gerard-Marchant +:contact: pierregm_at_uga_edu +:date: $Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $ +:version: $Id: morestats.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + + +import numpy +from numpy import bool_, float_, int_, ndarray, \ + sqrt,\ + arange, empty,\ + r_ +from numpy import array as narray +import numpy.core.numeric as numeric +from numpy.core.numeric import concatenate + +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray.core import masked, nomask, MaskedArray, masked_array +from scipy.sandbox.maskedarray.extras import apply_along_axis, dot +from scipy.sandbox.maskedarray.mstats import trim_both, trimmed_stde, mquantiles, mmedian, stde_median + +from scipy.stats.distributions import norm, beta, t, binom +from scipy.stats.morestats import find_repeats + +__all__ = ['hdquantiles', 'hdmedian', 'hdquantiles_sd', + 'trimmed_mean_ci', 'mjci', 'rank_data'] + + +#####-------------------------------------------------------------------------- +#---- --- Quantiles --- +#####-------------------------------------------------------------------------- +def hdquantiles(data, prob=list([.25,.5,.75]), axis=None, var=False,): + """Computes quantile estimates with the Harrell-Davis method, where the estimates +are calculated as a weighted linear combination of order statistics. + +*Parameters* : + data: {ndarray} + Data array. + prob: {sequence} + Sequence of quantiles to compute. + axis : {integer} + Axis along which to compute the quantiles. If None, use a flattened array. + var : {boolean} + Whether to return the variance of the estimate. + +*Returns* + A (p,) array of quantiles (if ``var`` is False), or a (2,p) array of quantiles + and variances (if ``var`` is True), where ``p`` is the number of quantiles. + +:Note: + The function is restricted to 2D arrays. + """ + def _hd_1D(data,prob,var): + "Computes the HD quantiles for a 1D array. Returns nan for invalid data." + xsorted = numpy.squeeze(numpy.sort(data.compressed().view(ndarray))) + # Don't use length here, in case we have a numpy scalar + n = xsorted.size + #......... + hd = empty((2,len(prob)), float_) + if n < 2: + hd.flat = numpy.nan + if var: + return hd + return hd[0] + #......... + v = arange(n+1) / float(n) + betacdf = beta.cdf + for (i,p) in enumerate(prob): + _w = betacdf(v, (n+1)*p, (n+1)*(1-p)) + w = _w[1:] - _w[:-1] + hd_mean = dot(w, xsorted) + hd[0,i] = hd_mean + # + hd[1,i] = dot(w, (xsorted-hd_mean)**2) + # + hd[0, prob == 0] = xsorted[0] + hd[0, prob == 1] = xsorted[-1] + if var: + hd[1, prob == 0] = hd[1, prob == 1] = numpy.nan + return hd + return hd[0] + # Initialization & checks --------- + data = masked_array(data, copy=False, dtype=float_) + p = numpy.array(prob, copy=False, ndmin=1) + # Computes quantiles along axis (or globally) + if (axis is None) or (data.ndim == 1): + result = _hd_1D(data, p, var) + else: + assert data.ndim <= 2, "Array should be 2D at most !" + result = apply_along_axis(_hd_1D, axis, data, p, var) + # + return masked_array(result, mask=numpy.isnan(result)) + +#.............................................................................. +def hdmedian(data, axis=-1, var=False): + """Returns the Harrell-Davis estimate of the median along the given axis. + +*Parameters* : + data: {ndarray} + Data array. + axis : {integer} + Axis along which to compute the quantiles. If None, use a flattened array. + var : {boolean} + Whether to return the variance of the estimate. + """ + result = hdquantiles(data,[0.5], axis=axis, var=var) + return result.squeeze() + + +#.............................................................................. +def hdquantiles_sd(data, prob=list([.25,.5,.75]), axis=None): + """Computes the standard error of the Harrell-Davis quantile estimates by jackknife. + + +*Parameters* : + data: {ndarray} + Data array. + prob: {sequence} + Sequence of quantiles to compute. + axis : {integer} + Axis along which to compute the quantiles. If None, use a flattened array. + +*Note*: + The function is restricted to 2D arrays. + """ + def _hdsd_1D(data,prob): + "Computes the std error for 1D arrays." + xsorted = numpy.sort(data.compressed()) + n = len(xsorted) + #......... + hdsd = empty(len(prob), float_) + if n < 2: + hdsd.flat = numpy.nan + #......... + vv = arange(n) / float(n-1) + betacdf = beta.cdf + # + for (i,p) in enumerate(prob): + _w = betacdf(vv, (n+1)*p, (n+1)*(1-p)) + w = _w[1:] - _w[:-1] + mx_ = numpy.fromiter([dot(w,xsorted[r_[range(0,k), + range(k+1,n)].astype(int_)]) + for k in range(n)], dtype=float_) + mx_var = numpy.array(mx_.var(), copy=False, ndmin=1) * n / float(n-1) + hdsd[i] = float(n-1) * sqrt(numpy.diag(mx_var).diagonal() / float(n)) + return hdsd + # Initialization & checks --------- + data = masked_array(data, copy=False, dtype=float_) + p = numpy.array(prob, copy=False, ndmin=1) + # Computes quantiles along axis (or globally) + if (axis is None): + result = _hdsd_1D(data.compressed(), p) + else: + assert data.ndim <= 2, "Array should be 2D at most !" + result = apply_along_axis(_hdsd_1D, axis, data, p) + # + return masked_array(result, mask=numpy.isnan(result)).ravel() + + +#####-------------------------------------------------------------------------- +#---- --- Confidence intervals --- +#####-------------------------------------------------------------------------- + +def trimmed_mean_ci(data, proportiontocut=0.2, alpha=0.05, axis=None): + """Returns the selected confidence interval of the trimmed mean along the +given axis. + +*Parameters* : + data : {sequence} + Input data. The data is transformed to a masked array + proportiontocut : {float} + Proportion of the data to cut from each side of the data . + As a result, (2*proportiontocut*n) values are actually trimmed. + alpha : {float} + Confidence level of the intervals. + axis : {integer} + Axis along which to cut. If None, uses a flattened version of the input. + """ + data = masked_array(data, copy=False) + trimmed = trim_both(data, proportiontocut=proportiontocut, axis=axis) + tmean = trimmed.mean(axis) + tstde = trimmed_stde(data, proportiontocut=proportiontocut, axis=axis) + df = trimmed.count(axis) - 1 + tppf = t.ppf(1-alpha/2.,df) + return numpy.array((tmean - tppf*tstde, tmean+tppf*tstde)) + +#.............................................................................. +def mjci(data, prob=[0.25,0.5,0.75], axis=None): + """Returns the Maritz-Jarrett estimators of the standard error of selected +experimental quantiles of the data. + +*Parameters* : + data: {ndarray} + Data array. + prob: {sequence} + Sequence of quantiles to compute. + axis : {integer} + Axis along which to compute the quantiles. If None, use a flattened array. + """ + def _mjci_1D(data, p): + data = data.compressed() + sorted = numpy.sort(data) + n = data.size + prob = (numpy.array(p) * n + 0.5).astype(int_) + betacdf = beta.cdf + # + mj = empty(len(prob), float_) + x = arange(1,n+1, dtype=float_) / n + y = x - 1./n + for (i,m) in enumerate(prob): + (m1,m2) = (m-1, n-m) + W = betacdf(x,m-1,n-m) - betacdf(y,m-1,n-m) + C1 = numpy.dot(W,sorted) + C2 = numpy.dot(W,sorted**2) + mj[i] = sqrt(C2 - C1**2) + return mj + # + data = masked_array(data, copy=False) + assert data.ndim <= 2, "Array should be 2D at most !" + p = numpy.array(prob, copy=False, ndmin=1) + # Computes quantiles along axis (or globally) + if (axis is None): + return _mjci_1D(data, p) + else: + return apply_along_axis(_mjci_1D, axis, data, p) + +#.............................................................................. +def mquantiles_cimj(data, prob=[0.25,0.50,0.75], alpha=0.05, axis=None): + """Computes the alpha confidence interval for the selected quantiles of the +data, with Maritz-Jarrett estimators. + +*Parameters* : + data: {ndarray} + Data array. + prob: {sequence} + Sequence of quantiles to compute. + alpha : {float} + Confidence level of the intervals. + axis : {integer} + Axis along which to compute the quantiles. If None, use a flattened array. + """ + alpha = min(alpha, 1-alpha) + z = norm.ppf(1-alpha/2.) + xq = mquantiles(data, prob, alphap=0, betap=0, axis=axis) + smj = mjci(data, prob, axis=axis) + return (xq - z * smj, xq + z * smj) + + +#............................................................................. +def median_cihs(data, alpha=0.05, axis=None): + """Computes the alpha-level confidence interval for the median of the data, +following the Hettmasperger-Sheather method. + +*Parameters* : + data : {sequence} + Input data. Masked values are discarded. The input should be 1D only, or + axis should be set to None. + alpha : {float} + Confidence level of the intervals. + axis : {integer} + Axis along which to compute the quantiles. If None, use a flattened array. + """ + def _cihs_1D(data, alpha): + data = numpy.sort(data.compressed()) + n = len(data) + alpha = min(alpha, 1-alpha) + k = int(binom._ppf(alpha/2., n, 0.5)) + gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5) + if gk < 1-alpha: + k -= 1 + gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5) + gkk = binom.cdf(n-k-1,n,0.5) - binom.cdf(k,n,0.5) + I = (gk - 1 + alpha)/(gk - gkk) + lambd = (n-k) * I / float(k + (n-2*k)*I) + lims = (lambd*data[k] + (1-lambd)*data[k-1], + lambd*data[n-k-1] + (1-lambd)*data[n-k]) + return lims + data = masked_array(data, copy=False) + # Computes quantiles along axis (or globally) + if (axis is None): + result = _cihs_1D(data.compressed(), p, var) + else: + assert data.ndim <= 2, "Array should be 2D at most !" + result = apply_along_axis(_cihs_1D, axis, data, alpha) + # + return result + +#.............................................................................. +def compare_medians_ms(group_1, group_2, axis=None): + """Compares the medians from two independent groups along the given axis. + +The comparison is performed using the McKean-Schrader estimate of the standard +error of the medians. + +*Parameters* : + group_1 : {sequence} + First dataset. + group_2 : {sequence} + Second dataset. + axis : {integer} + Axis along which the medians are estimated. If None, the arrays are flattened. + +*Returns* : + A (p,) array of comparison values. + + """ + (med_1, med_2) = (mmedian(group_1, axis=axis), mmedian(group_2, axis=axis)) + (std_1, std_2) = (stde_median(group_1, axis=axis), + stde_median(group_2, axis=axis)) + W = abs(med_1 - med_2) / sqrt(std_1**2 + std_2**2) + return 1 - norm.cdf(W) + + +#####-------------------------------------------------------------------------- +#---- --- Ranking --- +#####-------------------------------------------------------------------------- + +#.............................................................................. +def rank_data(data, axis=None, use_missing=False): + """Returns the rank (also known as order statistics) of each data point +along the given axis. + +If some values are tied, their rank is averaged. +If some values are masked, their rank is set to 0 if use_missing is False, or +set to the average rank of the unmasked values if use_missing is True. + +*Parameters* : + data : {sequence} + Input data. The data is transformed to a masked array + axis : {integer} + Axis along which to perform the ranking. If None, the array is first + flattened. An exception is raised if the axis is specified for arrays + with a dimension larger than 2 + use_missing : {boolean} + Whether the masked values have a rank of 0 (False) or equal to the + average rank of the unmasked values (True). + """ + # + def _rank1d(data, use_missing=False): + n = data.count() + rk = numpy.empty(data.size, dtype=float_) + idx = data.argsort() + rk[idx[:n]] = numpy.arange(1,n+1) + # + if use_missing: + rk[idx[n:]] = (n+1)/2. + else: + rk[idx[n:]] = 0 + # + repeats = find_repeats(data) + for r in repeats[0]: + condition = (data==r).filled(False) + rk[condition] = rk[condition].mean() + return rk + # + data = masked_array(data, copy=False) + if axis is None: + if data.ndim > 1: + return _rank1d(data.ravel(), use_missing).reshape(data.shape) + else: + return _rank1d(data, use_missing) + else: + return apply_along_axis(_rank1d, axis, data, use_missing) + +############################################################################### +if __name__ == '__main__': + + if 0: + from maskedarray.testutils import assert_almost_equal + data = [0.706560797,0.727229578,0.990399276,0.927065621,0.158953014, + 0.887764025,0.239407086,0.349638551,0.972791145,0.149789972, + 0.936947700,0.132359948,0.046041972,0.641675031,0.945530547, + 0.224218684,0.771450991,0.820257774,0.336458052,0.589113496, + 0.509736129,0.696838829,0.491323573,0.622767425,0.775189248, + 0.641461450,0.118455200,0.773029450,0.319280007,0.752229111, + 0.047841438,0.466295911,0.583850781,0.840581845,0.550086491, + 0.466470062,0.504765074,0.226855960,0.362641207,0.891620942, + 0.127898691,0.490094097,0.044882048,0.041441695,0.317976349, + 0.504135618,0.567353033,0.434617473,0.636243375,0.231803616, + 0.230154113,0.160011327,0.819464108,0.854706985,0.438809221, + 0.487427267,0.786907310,0.408367937,0.405534192,0.250444460, + 0.995309248,0.144389588,0.739947527,0.953543606,0.680051621, + 0.388382017,0.863530727,0.006514031,0.118007779,0.924024803, + 0.384236354,0.893687694,0.626534881,0.473051932,0.750134705, + 0.241843555,0.432947602,0.689538104,0.136934797,0.150206859, + 0.474335206,0.907775349,0.525869295,0.189184225,0.854284286, + 0.831089744,0.251637345,0.587038213,0.254475554,0.237781276, + 0.827928620,0.480283781,0.594514455,0.213641488,0.024194386, + 0.536668589,0.699497811,0.892804071,0.093835427,0.731107772] + # + assert_almost_equal(hdquantiles(data,[0., 1.]), + [0.006514031, 0.995309248]) + hdq = hdquantiles(data,[0.25, 0.5, 0.75]) + assert_almost_equal(hdq, [0.253210762, 0.512847491, 0.762232442,]) + hdq = hdquantiles_sd(data,[0.25, 0.5, 0.75]) + assert_almost_equal(hdq, [0.03786954, 0.03805389, 0.03800152,], 4) + # + data = numpy.array(data).reshape(10,10) + hdq = hdquantiles(data,[0.25,0.5,0.75],axis=0) Added: trunk/scipy/sandbox/maskedarray/mpl_maskedarray.patch =================================================================== --- trunk/scipy/sandbox/maskedarray/mpl_maskedarray.patch 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/mpl_maskedarray.patch 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,12 @@ +diff -urNp matplotlib/numerix/ma.init/__init__.py matplotlib/numerix/ma/__init__.py +--- matplotlib/numerix/ma.init/__init__.py 2006-08-19 16:21:56.000000000 -0400 ++++ matplotlib/numerix/ma/__init__.py 2006-11-29 12:48:14.000000000 -0500 +@@ -9,7 +9,9 @@ elif which[0] == "numeric": + nomask = None + getmaskorNone = getmask + elif which[0] == "numpy": +- from numpy.core.ma import * ++ from maskedarray import * + def getmaskorNone(obj): + _msk = getmask(obj) + if _msk is nomask: Added: trunk/scipy/sandbox/maskedarray/mrecords.py =================================================================== --- trunk/scipy/sandbox/maskedarray/mrecords.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/mrecords.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,717 @@ +"""mrecords +Defines a class of record arrays supporting masked arrays. + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: mrecords.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + +import sys +import types + +import numpy +from numpy import bool_, complex_, float_, int_, str_, object_ +from numpy import array as narray +import numpy.core.numeric as numeric +import numpy.core.numerictypes as ntypes +from numpy.core.defchararray import chararray +from numpy.core.records import find_duplicate + +from numpy.core.records import format_parser, record, recarray +from numpy.core.records import fromarrays as recfromarrays + +ndarray = numeric.ndarray +_byteorderconv = numpy.core.records._byteorderconv +_typestr = ntypes._typestr + +import scipy.sandbox.maskedarray +from scipy.sandbox.maskedarray import MaskedArray, masked, nomask, masked_array,\ + make_mask, mask_or, getmask, getmaskarray, filled +from scipy.sandbox.maskedarray.core import default_fill_value, masked_print_option + +import warnings + +reserved_fields = ['_data','_mask','_fieldmask', 'dtype'] + +def _getformats(data): + "Returns the formats of each array of arraylist as a comma-separated string." + if hasattr(data,'dtype'): + return ",".join([desc[1] for desc in data.dtype.descr]) + + formats = '' + for obj in data: + obj = numeric.asarray(obj) +# if not isinstance(obj, ndarray): +## if not isinstance(obj, ndarray): +# raise ValueError, "item in the array list must be an ndarray." + formats += _typestr[obj.dtype.type] + if issubclass(obj.dtype.type, ntypes.flexible): + formats += `obj.itemsize` + formats += ',' + return formats[:-1] + +def _checknames(descr, names=None): + """Checks that the field names of the descriptor ``descr`` are not some +reserved keywords. If this is the case, a default 'f%i' is substituted. +If the argument `names` is not None, updates the field names to valid names. + """ + ndescr = len(descr) + default_names = ['f%i' % i for i in range(ndescr)] + if names is None: + new_names = default_names + else: + if isinstance(names, (tuple, list)): + new_names = names + elif isinstance(names, str): + new_names = names.split(',') + else: + raise NameError, "illegal input names %s" % `names` + nnames = len(new_names) + if nnames < ndescr: + new_names += default_names[nnames:] + ndescr = [] + for (n, d, t) in zip(new_names, default_names, descr.descr): + if n in reserved_fields: + if t[0] in reserved_fields: + ndescr.append((d,t[1])) + else: + ndescr.append(t) + else: + ndescr.append((n,t[1])) + return numeric.dtype(ndescr) + + + +class MaskedRecords(MaskedArray, object): + """ + +*IVariables*: + _data : {recarray} + Underlying data, as a record array. + _mask : {boolean array} + Mask of the records. A record is masked when all its fields are masked. + _fieldmask : {boolean recarray} + Record array of booleans, setting the mask of each individual field of each record. + _fill_value : {record} + Filling values for each field. + """ + _defaultfieldmask = nomask + _defaulthardmask = False + def __new__(cls, data, mask=nomask, dtype=None, + hard_mask=False, fill_value=None, +# offset=0, strides=None, + formats=None, names=None, titles=None, + byteorder=None, aligned=False): + # Get the new descriptor ................ + if dtype is not None: + descr = numeric.dtype(dtype) + else: + if formats is None: + formats = _getformats(data) + parsed = format_parser(formats, names, titles, aligned, byteorder) + descr = parsed._descr + if names is not None: + descr = _checknames(descr,names) + _names = descr.names + mdescr = [(n,'|b1') for n in _names] + # get the shape ......................... + try: + shape = numeric.asarray(data[0]).shape + except IndexError: + shape = len(data.dtype) + if isinstance(shape, int): + shape = (shape,) + # Construct the _data recarray .......... + if isinstance(data, record): + _data = numeric.asarray(data).view(recarray) + _fieldmask = mask + elif isinstance(data, MaskedRecords): + _data = data._data + _fieldmask = data._fieldmask + elif isinstance(data, recarray): + _data = data + if mask is nomask: + _fieldmask = data.astype(mdescr) + _fieldmask.flat = tuple([False]*len(mdescr)) + else: + _fieldmask = mask + elif (isinstance(data, (tuple, numpy.void)) or\ + hasattr(data,'__len__') and isinstance(data[0], (tuple, numpy.void))): + data = numeric.array(data, dtype=descr).view(recarray) + _data = data + if mask is nomask: + _fieldmask = data.astype(mdescr) + _fieldmask.flat = tuple([False]*len(mdescr)) + else: + _fieldmask = mask + else: + _data = recarray(shape, dtype=descr) + _fieldmask = recarray(shape, dtype=mdescr) + for (n,v) in zip(_names, data): + _data[n] = numeric.asarray(v).view(ndarray) + _fieldmask[n] = getmaskarray(v) + #........................................ + _data = _data.view(cls) + _data._fieldmask = _fieldmask + _data._hardmask = hard_mask + if fill_value is None: + _data._fill_value = [default_fill_value(numeric.dtype(d[1])) + for d in descr.descr] + else: + _data._fill_value = fill_value + return _data + + def __array_finalize__(self,obj): + if isinstance(obj, MaskedRecords): + self.__dict__.update(_fieldmask=obj._fieldmask, + _hardmask=obj._hardmask, + _fill_value=obj._fill_value + ) + else: + self.__dict__.update(_fieldmask = nomask, + _hardmask = False, + fill_value = None + ) + return + + def _getdata(self): + "Returns the data as a recarray." + return self.view(recarray) + _data = property(fget=_getdata) + + #...................................................... + def __getattribute__(self, attr): + "Returns the given attribute." + try: + # Returns a generic attribute + return object.__getattribute__(self,attr) + except AttributeError: + # OK, so attr must be a field name + pass + # Get the list of fields ...... + _names = self.dtype.names + if attr in _names: + _data = self._data + _mask = self._fieldmask +# obj = masked_array(_data.__getattribute__(attr), copy=False, +# mask=_mask.__getattribute__(attr)) + # Use a view in order to avoid the copy of the mask in MaskedArray.__new__ + obj = narray(_data.__getattribute__(attr), copy=False).view(MaskedArray) + obj._mask = _mask.__getattribute__(attr) + if not obj.ndim and obj._mask: + return masked + return obj + raise AttributeError,"No attribute '%s' !" % attr + + def __setattr__(self, attr, val): + "Sets the attribute attr to the value val." + newattr = attr not in self.__dict__ + try: + # Is attr a generic attribute ? + ret = object.__setattr__(self, attr, val) + except: + # Not a generic attribute: exit if it's not a valid field + fielddict = self.dtype.names or {} + if attr not in fielddict: + exctype, value = sys.exc_info()[:2] + raise exctype, value + else: + if attr not in list(self.dtype.names) + ['_mask','mask']: + return ret + if newattr: # We just added this one + try: # or this setattr worked on an internal + # attribute. + object.__delattr__(self, attr) + except: + return ret + # Case #1.: Basic field ............ + base_fmask = self._fieldmask + _names = self.dtype.names + if attr in _names: + fval = filled(val) + mval = getmaskarray(val) + if self._hardmask: + mval = mask_or(mval, base_fmask.__getattr__(attr)) + self._data.__setattr__(attr, fval) + base_fmask.__setattr__(attr, mval) + return + elif attr == '_mask': + self.__setmask__(val) + return + #............................................ + def __getitem__(self, indx): + """Returns all the fields sharing the same fieldname base. +The fieldname base is either `_data` or `_mask`.""" + _localdict = self.__dict__ + _data = self._data + # We want a field ........ + if isinstance(indx, str): + obj = _data[indx].view(MaskedArray) + obj._set_mask(_localdict['_fieldmask'][indx]) + # Force to nomask if the mask is empty + if not obj._mask.any(): + obj._mask = nomask + return obj + # We want some elements .. + # First, the data ........ + obj = ndarray.__getitem__(self, indx) + if isinstance(obj, numpy.void): + obj = self.__class__(obj, dtype=self.dtype) + else: + obj = obj.view(type(self)) + obj._fieldmask = numpy.asarray(_localdict['_fieldmask'][indx]).view(recarray) + return obj + #............................................ + def __setitem__(self, indx, value): + "Sets the given record to value." + MaskedArray.__setitem__(self, indx, value) + + + def __setslice__(self, i, j, value): + "Sets the slice described by [i,j] to `value`." + _localdict = self.__dict__ + d = self._data + m = _localdict['_fieldmask'] + names = self.dtype.names + if value is masked: + for n in names: + m[i:j][n] = True + elif not self._hardmask: + fval = filled(value) + mval = getmaskarray(value) + for n in names: + d[n][i:j] = fval + m[n][i:j] = mval + else: + mindx = getmaskarray(self)[i:j] + dval = numeric.asarray(value) + valmask = getmask(value) + if valmask is nomask: + for n in names: + mval = mask_or(m[n][i:j], valmask) + d[n][i:j][~mval] = value + elif valmask.size > 1: + for n in names: + mval = mask_or(m[n][i:j], valmask) + d[n][i:j][~mval] = dval[~mval] + m[n][i:j] = mask_or(m[n][i:j], mval) + self._fieldmask = m + + #..................................................... + def __setmask__(self, mask): + "Sets the mask." + names = self.dtype.names + fmask = self.__dict__['_fieldmask'] + newmask = make_mask(mask, copy=False) +# self.unshare_mask() + if self._hardmask: + for n in names: + fmask[n].__ior__(newmask) + else: + for n in names: + fmask[n].flat = newmask + return + + def _getmask(self): + """Returns the mask of the mrecord: a record is masked when all the fields +are masked.""" + if self.size > 1: + return self._fieldmask.view((bool_, len(self.dtype))).all(1) + + _setmask = __setmask__ + _mask = property(fget=_getmask, fset=_setmask) + + #...................................................... + def __str__(self): + "Calculates the string representation." + if self.size > 1: + mstr = ["(%s)" % ",".join([str(i) for i in s]) + for s in zip(*[getattr(self,f) for f in self.dtype.names])] + return "[%s]" % ", ".join(mstr) + else: + mstr = ["%s" % ",".join([str(i) for i in s]) + for s in zip([getattr(self,f) for f in self.dtype.names])] + return "(%s)" % ", ".join(mstr) + + def __repr__(self): + "Calculates the repr representation." + _names = self.dtype.names + fmt = "%%%is : %%s" % (max([len(n) for n in _names])+4,) + reprstr = [fmt % (f,getattr(self,f)) for f in self.dtype.names] + reprstr.insert(0,'masked_records(') + reprstr.extend([fmt % (' fill_value', self._fill_value), + ' )']) + return str("\n".join(reprstr)) + #...................................................... + def view(self, obj): + """Returns a view of the mrecarray.""" + try: + if issubclass(obj, ndarray): + return ndarray.view(self, obj) + except TypeError: + pass + dtype = numeric.dtype(obj) + if dtype.fields is None: + return self.__array__().view(dtype) + return ndarray.view(self, obj) + #...................................................... + def filled(self, fill_value=None): + """Returns an array of the same class as ``_data``, with masked values +filled with ``fill_value``. If ``fill_value`` is None, ``self.fill_value`` is +used instead. + +Subclassing is preserved. + + """ + _localdict = self.__dict__ + d = self._data + fm = _localdict['_fieldmask'] + if not numeric.asarray(fm, dtype=bool_).any(): + return d + # + if fill_value is None: + value = _localdict['_fill_value'] + else: + value = fill_value + if numeric.size(value) == 1: + value = [value,] * len(self.dtype) + # + if self is masked: + result = numeric.asanyarray(value) + else: + result = d.copy() + for (n, v) in zip(d.dtype.names, value): + numpy.putmask(numeric.asarray(result[n]), + numeric.asarray(fm[n]), v) + return result + #............................................ + def harden_mask(self): + "Forces the mask to hard" + self._hardmask = True + def soften_mask(self): + "Forces the mask to soft" + self._hardmask = False + #............................................. + def copy(self): + """Returns a copy of the masked record.""" + _localdict = self.__dict__ + return MaskedRecords(self._data.copy(), + mask=_localdict['_fieldmask'].copy(), + dtype=self.dtype) + #............................................. + + +#####--------------------------------------------------------------------------- +#---- --- Constructors --- +#####--------------------------------------------------------------------------- + +def fromarrays(arraylist, dtype=None, shape=None, formats=None, + names=None, titles=None, aligned=False, byteorder=None): + """Creates a mrecarray from a (flat) list of masked arrays. + +*Parameters*: + arraylist : {sequence} + A list of (masked) arrays. Each element of the sequence is first converted + to a masked array if needed. If a 2D array is passed as argument, it is + processed line by line + dtype : {numeric.dtype} + Data type descriptor. + {shape} : {integer} + Number of records. If None, ``shape`` is defined from the shape of the + first array in the list. + formats : {sequence} + Sequence of formats for each individual field. If None, the formats will + be autodetected by inspecting the fields and selecting the highest dtype + possible. + names : {sequence} + Sequence of the names of each field. + -titles : {sequence} + (Description to write) + aligned : {boolean} + (Description to write, not used anyway) + byteorder: {boolean} + (Description to write, not used anyway) + +*Notes*: + Lists of tuples should be preferred over lists of lists for faster processing. + """ + arraylist = [masked_array(x) for x in arraylist] + # Define/check the shape..................... + if shape is None or shape == 0: + shape = arraylist[0].shape + if isinstance(shape, int): + shape = (shape,) + # Define formats from scratch ............... + if formats is None and dtype is None: + formats = _getformats(arraylist) + # Define the dtype .......................... + if dtype is not None: + descr = numeric.dtype(dtype) + _names = descr.names + else: + parsed = format_parser(formats, names, titles, aligned, byteorder) + _names = parsed._names + descr = parsed._descr + # Determine shape from data-type............. + if len(descr) != len(arraylist): + msg = "Mismatch between the number of fields (%i) and the number of "\ + "arrays (%i)" + raise ValueError, msg % (len(descr), len(arraylist)) + d0 = descr[0].shape + nn = len(d0) + if nn > 0: + shape = shape[:-nn] + # Make sure the shape is the correct one .... + for k, obj in enumerate(arraylist): + nn = len(descr[k].shape) + testshape = obj.shape[:len(obj.shape)-nn] + if testshape != shape: + raise ValueError, "Array-shape mismatch in array %d" % k + # Reconstruct the descriptor, by creating a _data and _mask version + return MaskedRecords(arraylist, dtype=descr) +#.............................................................................. +def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None, + titles=None, aligned=False, byteorder=None): + """Creates a MaskedRecords from a list of records. + +*Parameters*: + arraylist : {sequence} + A list of (masked) arrays. Each element of the sequence is first converted + to a masked array if needed. If a 2D array is passed as argument, it is + processed line by line + dtype : {numeric.dtype} + Data type descriptor. + {shape} : {integer} + Number of records. If None, ``shape`` is defined from the shape of the + first array in the list. + formats : {sequence} + Sequence of formats for each individual field. If None, the formats will + be autodetected by inspecting the fields and selecting the highest dtype + possible. + names : {sequence} + Sequence of the names of each field. + -titles : {sequence} + (Description to write) + aligned : {boolean} + (Description to write, not used anyway) + byteorder: {boolean} + (Description to write, not used anyway) + +*Notes*: + Lists of tuples should be preferred over lists of lists for faster processing. + """ + # reclist is in fact a mrecarray ................. + if isinstance(reclist, MaskedRecords): + mdescr = reclist.dtype + shape = reclist.shape + return MaskedRecords(reclist, dtype=mdescr) + # No format, no dtype: create from to arrays ..... + nfields = len(reclist[0]) + if formats is None and dtype is None: # slower + if isinstance(reclist, recarray): + arrlist = [reclist.field(i) for i in range(len(reclist.dtype))] + if names is None: + names = reclist.dtype.names + else: + obj = numeric.array(reclist,dtype=object) + arrlist = [numeric.array(obj[...,i].tolist()) + for i in xrange(nfields)] + return MaskedRecords(arrlist, formats=formats, names=names, + titles=titles, aligned=aligned, byteorder=byteorder) + # Construct the descriptor ....................... + if dtype is not None: + descr = numeric.dtype(dtype) + _names = descr.names + else: + parsed = format_parser(formats, names, titles, aligned, byteorder) + _names = parsed._names + descr = parsed._descr + + try: + retval = numeric.array(reclist, dtype = descr).view(recarray) + except TypeError: # list of lists instead of list of tuples + if (shape is None or shape == 0): + shape = len(reclist)*2 + if isinstance(shape, (int, long)): + shape = (shape*2,) + if len(shape) > 1: + raise ValueError, "Can only deal with 1-d array." + retval = recarray(shape, mdescr) + for k in xrange(retval.size): + retval[k] = tuple(reclist[k]) + return MaskedRecords(retval, dtype=descr) + else: + if shape is not None and retval.shape != shape: + retval.shape = shape + # + return MaskedRecords(retval, dtype=descr) + +def _guessvartypes(arr): + """Tries to guess the dtypes of the str_ ndarray `arr`, by testing element-wise +conversion. Returns a list of dtypes. +The array is first converted to ndarray. If the array is 2D, the test is performed +on the first line. An exception is raised if the file is 3D or more. + """ + vartypes = [] + arr = numeric.asarray(arr) + if len(arr.shape) == 2 : + arr = arr[0] + elif len(arr.shape) > 2: + raise ValueError, "The array should be 2D at most!" + # Start the conversion loop ....... + for f in arr: + try: + val = int(f) + except ValueError: + try: + val = float(f) + except ValueError: + try: + val = complex(f) + except ValueError: + vartypes.append(arr.dtype) + else: + vartypes.append(complex_) + else: + vartypes.append(float_) + else: + vartypes.append(int_) + return vartypes + +def openfile(fname): + "Opens the file handle of file `fname`" + # A file handle ................... + if hasattr(fname, 'readline'): + return fname + # Try to open the file and guess its type + try: + f = open(fname) + except IOError: + raise IOError, "No such file: '%s'" % fname + if f.readline()[:2] != "\\x": + f.seek(0,0) + return f + raise NotImplementedError, "Wow, binary file" + + +def fromtextfile(fname, delimitor=None, commentchar='#', missingchar='', + varnames=None, vartypes=None): + """Creates a mrecarray from data stored in the file `filename`. + +*Parameters* : + filename : {file name/handle} + Handle of an opened file. + delimitor : {string} + Alphanumeric character used to separate columns in the file. + If None, any (group of) white spacestring(s) will be used. + commentchar : {string} + Alphanumeric character used to mark the start of a comment. + missingchar` : {string} + String indicating missing data, and used to create the masks. + varnames : {sequence} + Sequence of the variable names. If None, a list will be created from + the first non empty line of the file. + vartypes : {sequence} + Sequence of the variables dtypes. If None, it will be estimated from + the first non-commented line. + + + Ultra simple: the varnames are in the header, one line""" + # Try to open the file ...................... + f = openfile(fname) + # Get the first non-empty line as the varnames + while True: + line = f.readline() + firstline = line[:line.find(commentchar)].strip() + _varnames = firstline.split(delimitor) + if len(_varnames) > 1: + break + if varnames is None: + varnames = _varnames + # Get the data .............................. + _variables = masked_array([line.strip().split(delimitor) for line in f + if line[0] != commentchar and len(line) > 1]) + (_, nfields) = _variables.shape + # Try to guess the dtype .................... + if vartypes is None: + vartypes = _guessvartypes(_variables[0]) + else: + vartypes = [numeric.dtype(v) for v in vartypes] + if len(vartypes) != nfields: + msg = "Attempting to %i dtypes for %i fields!" + msg += " Reverting to default." + warnings.warn(msg % (len(vartypes), nfields)) + vartypes = _guessvartypes(_variables[0]) + # Construct the descriptor .................. + mdescr = [(n,f) for (n,f) in zip(varnames, vartypes)] + # Get the data and the mask ................. + # We just need a list of masked_arrays. It's easier to create it like that: + _mask = (_variables.T == missingchar) + _datalist = [masked_array(a,mask=m,dtype=t) + for (a,m,t) in zip(_variables.T, _mask, vartypes)] + return MaskedRecords(_datalist, dtype=mdescr) + +#.................................................................... +def addfield(mrecord, newfield, newfieldname=None): + """Adds a new field to the masked record array, using `newfield` as data +and `newfieldname` as name. If `newfieldname` is None, the new field name is +set to 'fi', where `i` is the number of existing fields. + """ + _data = mrecord._data + _mask = mrecord._fieldmask + if newfieldname is None or newfieldname in reserved_fields: + newfieldname = 'f%i' % len(_data.dtype) + newfield = masked_array(newfield) + # Get the new data ............ + # Create a new empty recarray + newdtype = numeric.dtype(_data.dtype.descr + \ + [(newfieldname, newfield.dtype)]) + newdata = recarray(_data.shape, newdtype) + # Add the exisintg field + [newdata.setfield(_data.getfield(*f),*f) + for f in _data.dtype.fields.values()] + # Add the new field + newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname]) + newdata = newdata.view(MaskedRecords) + # Get the new mask ............. + # Create a new empty recarray + newmdtype = numeric.dtype([(n,bool_) for n in newdtype.names]) + newmask = recarray(_data.shape, newmdtype) + # Add the old masks + [newmask.setfield(_mask.getfield(*f),*f) + for f in _mask.dtype.fields.values()] + # Add the mask of the new field + newmask.setfield(getmaskarray(newfield), + *newmask.dtype.fields[newfieldname]) + newdata._fieldmask = newmask + return newdata + +################################################################################ +if __name__ == '__main__': + import numpy as N + from maskedarray.testutils import assert_equal + if 1: + d = N.arange(5) + m = maskedarray.make_mask([1,0,0,1,1]) + base_d = N.r_[d,d[::-1]].reshape(2,-1).T + base_m = N.r_[[m, m[::-1]]].T + base = masked_array(base_d, mask=base_m).T + mrecord = fromarrays(base,dtype=[('a',N.float_),('b',N.float_)]) + mrec = MaskedRecords(mrecord.copy()) + # + if 1: + mrec = mrec.copy() + mrec.harden_mask() + assert(mrec._hardmask) + mrec._mask = nomask + assert_equal(mrec._mask, N.r_[[m,m[::-1]]].all(0)) + mrec.soften_mask() + assert(not mrec._hardmask) + mrec.mask = nomask + tmp = mrec['b']._mask + assert(mrec['b']._mask is nomask) + assert_equal(mrec['a']._mask,mrec['b']._mask) Added: trunk/scipy/sandbox/maskedarray/mstats.py =================================================================== --- trunk/scipy/sandbox/maskedarray/mstats.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/mstats.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,433 @@ +""" +Generic statistics functions, with support to MA. + +:author: Pierre GF Gerard-Marchant +:contact: pierregm_at_uga_edu +:date: $Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $ +:version: $Id: mstats.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + + +import numpy +from numpy import bool_, float_, int_, \ + sqrt +from numpy import array as narray +import numpy.core.numeric as numeric +from numpy.core.numeric import concatenate + +import scipy.sandbox.maskedarray +from scipy.sandbox.maskedarray.core import masked, nomask, MaskedArray, masked_array +from scipy.sandbox.maskedarray.extras import apply_along_axis, dot + +__all__ = ['cov','meppf','plotting_positions','meppf','mmedian','mquantiles', + 'stde_median','trim_tail','trim_both','trimmed_mean','trimmed_stde', + 'winsorize'] + +#####-------------------------------------------------------------------------- +#---- -- Trimming --- +#####-------------------------------------------------------------------------- + +def winsorize(data, alpha=0.2): + """Returns a Winsorized version of the input array. + +The (alpha/2.) lowest values are set to the (alpha/2.)th percentile, and +the (alpha/2.) highest values are set to the (1-alpha/2.)th percentile +Masked values are skipped. + +*Parameters*: + data : {ndarray} + Input data to Winsorize. The data is first flattened. + alpha : {float}, optional + Percentage of total Winsorization : alpha/2. on the left, alpha/2. on the right + """ + data = masked_array(data, copy=False).ravel() + idxsort = data.argsort() + (nsize, ncounts) = (data.size, data.count()) + ntrim = int(alpha * ncounts) + (xmin,xmax) = data[idxsort[[ntrim, ncounts-nsize-ntrim-1]]] + return masked_array(numpy.clip(data, xmin, xmax), mask=data._mask) + +#.............................................................................. +def trim_both(data, proportiontocut=0.2, axis=None): + """Trims the data by masking the int(trim*n) smallest and int(trim*n) largest +values of data along the given axis, where n is the number of unmasked values. + +*Parameters*: + data : {ndarray} + Data to trim. + proportiontocut : {float} + Percentage of trimming. If n is the number of unmasked values before trimming, + the number of values after trimming is (1-2*trim)*n. + axis : {integer} + Axis along which to perform the trimming. If None, the input array is first + flattened. + """ + #................... + def _trim_1D(data, trim): + "Private function: return a trimmed 1D array." + nsize = data.size + ncounts = data.count() + ntrim = int(trim * ncounts) + idxsort = data.argsort() + data[idxsort[:ntrim]] = masked + data[idxsort[ncounts-nsize-ntrim:]] = masked + return data + #................... + data = masked_array(data, copy=False, subok=True) + data.unshare_mask() + if (axis is None): + return _trim_1D(data.ravel(), proportiontocut) + else: + assert data.ndim <= 2, "Array should be 2D at most !" + return apply_along_axis(_trim_1D, axis, data, proportiontocut) + +#.............................................................................. +def trim_tail(data, proportiontocut=0.2, tail='left', axis=None): + """Trims the data by masking int(trim*n) values from ONE tail of the data +along the given axis, where n is the number of unmasked values. + +*Parameters*: + data : {ndarray} + Data to trim. + proportiontocut : {float} + Percentage of trimming. If n is the number of unmasked values before trimming, + the number of values after trimming is (1-trim)*n. + tail : {string} + Trimming direction, in ('left', 'right'). If left, the proportiontocut + lowest values are set to the corresponding percentile. If right, the + proportiontocut highest values are used instead. + axis : {integer} + Axis along which to perform the trimming. If None, the input array is first + flattened. + """ + #................... + def _trim_1D(data, trim, left): + "Private function: return a trimmed 1D array." + nsize = data.size + ncounts = data.count() + ntrim = int(trim * ncounts) + idxsort = data.argsort() + if left: + data[idxsort[:ntrim]] = masked + else: + data[idxsort[ncounts-nsize-ntrim:]] = masked + return data + #................... + data = masked_array(data, copy=False, subok=True) + data.unshare_mask() + # + if not isinstance(tail, str): + raise TypeError("The tail argument should be in ('left','right')") + tail = tail.lower()[0] + if tail == 'l': + left = True + elif tail == 'r': + left=False + else: + raise ValueError("The tail argument should be in ('left','right')") + # + if (axis is None): + return _trim_1D(data.ravel(), proportiontocut, left) + else: + assert data.ndim <= 2, "Array should be 2D at most !" + return apply_along_axis(_trim_1D, axis, data, proportiontocut, left) + +#.............................................................................. +def trimmed_mean(data, proportiontocut=0.2, axis=None): + """Returns the trimmed mean of the data along the given axis. Trimming is +performed on both ends of the distribution. + +*Parameters*: + data : {ndarray} + Data to trim. + proportiontocut : {float} + Proportion of the data to cut from each side of the data . + As a result, (2*proportiontocut*n) values are actually trimmed. + axis : {integer} + Axis along which to perform the trimming. If None, the input array is first + flattened. + """ + return trim_both(data, proportiontocut=proportiontocut, axis=axis).mean(axis=axis) + +#.............................................................................. +def trimmed_stde(data, proportiontocut=0.2, axis=None): + """Returns the standard error of the trimmed mean for the input data, +along the given axis. Trimming is performed on both ends of the distribution. + +*Parameters*: + data : {ndarray} + Data to trim. + proportiontocut : {float} + Proportion of the data to cut from each side of the data . + As a result, (2*proportiontocut*n) values are actually trimmed. + axis : {integer} + Axis along which to perform the trimming. If None, the input array is first + flattened. + """ + #........................ + def _trimmed_stde_1D(data, trim=0.2): + "Returns the standard error of the trimmed mean for a 1D input data." + winsorized = winsorize(data) + nsize = winsorized.count() + winstd = winsorized.stdu() + return winstd / ((1-2*trim) * numpy.sqrt(nsize)) + #........................ + data = masked_array(data, copy=False, subok=True) + data.unshare_mask() + if (axis is None): + return _trimmed_stde_1D(data.ravel(), proportiontocut) + else: + assert data.ndim <= 2, "Array should be 2D at most !" + return apply_along_axis(_trimmed_stde_1D, axis, data, proportiontocut) + +#............................................................................. +def stde_median(data, axis=None): + """Returns the McKean-Schrader estimate of the standard error of the sample +median along the given axis. + + +*Parameters*: + data : {ndarray} + Data to trim. + axis : {integer} + Axis along which to perform the trimming. If None, the input array is first + flattened. + """ + def _stdemed_1D(data): + sorted = numpy.sort(data.compressed()) + n = len(sorted) + z = 2.5758293035489004 + k = int(round((n+1)/2. - z * sqrt(n/4.),0)) + return ((sorted[n-k] - sorted[k-1])/(2.*z)) + # + data = masked_array(data, copy=False, subok=True) + if (axis is None): + return _stdemed_1D(data) + else: + assert data.ndim <= 2, "Array should be 2D at most !" + return apply_along_axis(_stdemed_1D, axis, data) + + +#####-------------------------------------------------------------------------- +#---- --- Quantiles --- +#####-------------------------------------------------------------------------- + + +def mquantiles(data, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None): + """Computes empirical quantiles for a *1xN* data array. +Samples quantile are defined by: +*Q(p) = (1-g).x[i] +g.x[i+1]* +where *x[j]* is the jth order statistic, +with *i = (floor(n*p+m))*, *m=alpha+p*(1-alpha-beta)* and *g = n*p + m - i)*. + +Typical values of (alpha,beta) are: + + - (0,1) : *p(k) = k/n* : linear interpolation of cdf (R, type 4) + - (.5,.5) : *p(k) = (k+1/2.)/n* : piecewise linear function (R, type 5) + - (0,0) : *p(k) = k/(n+1)* : (R type 6) + - (1,1) : *p(k) = (k-1)/(n-1)*. In this case, p(k) = mode[F(x[k])]. + That's R default (R type 7) + - (1/3,1/3): *p(k) = (k-1/3)/(n+1/3)*. Then p(k) ~ median[F(x[k])]. + The resulting quantile estimates are approximately median-unbiased + regardless of the distribution of x. (R type 8) + - (3/8,3/8): *p(k) = (k-3/8)/(n+1/4)*. Blom. + The resulting quantile estimates are approximately unbiased + if x is normally distributed (R type 9) + - (.4,.4) : approximately quantile unbiased (Cunnane) + - (.35,.35): APL, used with PWM + +*Parameters*: + x : {sequence} + Input data, as a sequence or array of dimension at most 2. + prob : {sequence} + List of quantiles to compute. + alpha : {float} + Plotting positions parameter. + beta : {float} + Plotting positions parameter. + axis : {integer} + Axis along which to perform the trimming. If None, the input array is first + flattened. + """ + def _quantiles1D(data,m,p): + x = numpy.sort(data.compressed()) + n = len(x) + if n == 0: + return masked_array(numpy.empty(len(p), dtype=float_), mask=True) + elif n == 1: + return masked_array(numpy.resize(x, p.shape), mask=nomask) + aleph = (n*p + m) + k = numpy.floor(aleph.clip(1, n-1)).astype(int_) + gamma = (aleph-k).clip(0,1) + return (1.-gamma)*x[(k-1).tolist()] + gamma*x[k.tolist()] + + # Initialization & checks --------- + data = masked_array(data, copy=False) + p = narray(prob, copy=False, ndmin=1) + m = alphap + p*(1.-alphap-betap) + # Computes quantiles along axis (or globally) + if (axis is None): + return _quantiles1D(data, m, p) + else: + assert data.ndim <= 2, "Array should be 2D at most !" + return apply_along_axis(_quantiles1D, axis, data, m, p) + + +def plotting_positions(data, alpha=0.4, beta=0.4): + """Returns the plotting positions (or empirical percentile points) for the + data. + Plotting positions are defined as (i-alpha)/(n-alpha-beta), where: + - i is the rank order statistics + - n is the number of unmasked values along the given axis + - alpha and beta are two parameters. + + Typical values for alpha and beta are: + - (0,1) : *p(k) = k/n* : linear interpolation of cdf (R, type 4) + - (.5,.5) : *p(k) = (k-1/2.)/n* : piecewise linear function (R, type 5) + - (0,0) : *p(k) = k/(n+1)* : Weibull (R type 6) + - (1,1) : *p(k) = (k-1)/(n-1)*. In this case, p(k) = mode[F(x[k])]. + That's R default (R type 7) + - (1/3,1/3): *p(k) = (k-1/3)/(n+1/3)*. Then p(k) ~ median[F(x[k])]. + The resulting quantile estimates are approximately median-unbiased + regardless of the distribution of x. (R type 8) + - (3/8,3/8): *p(k) = (k-3/8)/(n+1/4)*. Blom. + The resulting quantile estimates are approximately unbiased + if x is normally distributed (R type 9) + - (.4,.4) : approximately quantile unbiased (Cunnane) + - (.35,.35): APL, used with PWM + """ + data = masked_array(data, copy=False).reshape(1,-1) + n = data.count() + plpos = numpy.empty(data.size, dtype=float_) + plpos[n:] = 0 + plpos[data.argsort()[:n]] = (numpy.arange(1,n+1) - alpha)/(n+1-alpha-beta) + return masked_array(plpos, mask=data._mask) + +meppf = plotting_positions + + +def mmedian(data, axis=None): + """Returns the median of data along the given axis. Missing data are discarded.""" + def _median1D(data): + x = numpy.sort(data.compressed()) + if x.size == 0: + return masked + return numpy.median(x) + data = masked_array(data, subok=True, copy=True) + if axis is None: + return _median1D(data) + else: + return apply_along_axis(_median1D, axis, data) + + +def cov(x, y=None, rowvar=True, bias=False, strict=False): + """Estimates the covariance matrix. + + +Normalization is by (N-1) where N is the number of observations (unbiased +estimate). If bias is True then normalization is by N. + +*Parameters*: + x : {ndarray} + Input data. If x is a 1D array, returns the variance. If x is a 2D array, + returns the covariance matrix. + y : {ndarray}, optional + Optional set of variables. + rowvar : {boolean} + If rowvar is true, then each row is a variable with obersvations in columns. + If rowvar is False, each column is a variable and the observations are in + the rows. + bias : {boolean} + Whether to use a biased or unbiased estimate of the covariance. + If bias is True, then the normalization is by N, the number of observations. + Otherwise, the normalization is by (N-1) + strict : {boolean} + If strict is True, masked values are propagated: if a masked value appears in + a row or column, the whole row or column is considered masked. + """ + X = narray(x, ndmin=2, subok=True, dtype=float) + if X.shape[0] == 1: + rowvar = True + if rowvar: + axis = 0 + tup = (slice(None),None) + else: + axis = 1 + tup = (None, slice(None)) + # + if y is not None: + y = narray(y, copy=False, ndmin=2, subok=True, dtype=float) + X = concatenate((X,y),axis) + # + X -= X.mean(axis=1-axis)[tup] + n = X.count(1-axis) + # + if bias: + fact = n*1.0 + else: + fact = n-1.0 + # + if not rowvar: + return (dot(X.T, X.conj(), strict=False) / fact).squeeze() + else: + return (dot(X, X.T.conj(), strict=False) / fact).squeeze() + + +def idealfourths(data, axis=None): + """Returns an estimate of the interquartile range of the data along the given +axis, as computed with the ideal fourths. + """ + def _idf(data): + x = numpy.sort(data.compressed()) + n = len(x) + (j,h) = divmod(n/4. + 5/12.,1) + qlo = (1-h)*x[j] + h*x[j+1] + k = n - j + qup = (1-h)*x[k] + h*x[k-1] + return qup - qlo + data = masked_array(data, copy=False) + if (axis is None): + return _idf(data) + else: + return apply_along_axis(_idf, axis, data) + + +def rsh(data, points=None): + """Evalutates Rosenblatt's shifted histogram estimators for each point +on the dataset 'data'. + +*Parameters* : + data : {sequence} + Input data. Masked values are ignored. + points : {sequence} + Sequence of points where to evaluate Rosenblatt shifted histogram. + If None, use the data. + """ + data = masked_array(data, copy=False) + if points is None: + points = data + else: + points = numpy.array(points, copy=False, ndmin=1) + if data.ndim != 1: + raise AttributeError("The input array should be 1D only !") + n = data.count() + h = 1.2 * idealfourths(data) / n**(1./5) + nhi = (data[:,None] <= points[None,:] + h).sum(0) + nlo = (data[:,None] < points[None,:] - h).sum(0) + return (nhi-nlo) / (2.*n*h) + +################################################################################ +if __name__ == '__main__': + from maskedarray.testutils import assert_almost_equal + if 1: + a = maskedarray.arange(1,101) + a[1::2] = masked + b = maskedarray.resize(a, (100,100)) + assert_almost_equal(mquantiles(b), [25., 50., 75.]) + assert_almost_equal(mquantiles(b, axis=0), maskedarray.resize(a,(3,100))) + assert_almost_equal(mquantiles(b, axis=1), + maskedarray.resize([24.9, 50., 75.1], (100,3))) Added: trunk/scipy/sandbox/maskedarray/setup.py =================================================================== --- trunk/scipy/sandbox/maskedarray/setup.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/setup.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,19 @@ +#!/usr/bin/env python +__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" +__version__ = '1.0' +__revision__ = "$Revision: 3473 $" +__date__ = '$Date: 2007-10-29 08:18:13 -0700 (Mon, 29 Oct 2007) $' + +import os + +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + config = Configuration('maskedarray',parent_package,top_path) + config.add_data_dir('tests') + return config + +if __name__ == "__main__": + from numpy.distutils.core import setup + #setup.update(nmasetup) + config = configuration(top_path='').todict() + setup(**config) Added: trunk/scipy/sandbox/maskedarray/tests/test_core.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_core.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/tests/test_core.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,1316 @@ +# pylint: disable-msg=W0611, W0612, W0511,R0201 +"""Tests suite for MaskedArray & subclassing. + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: test_core.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + +import types + +import numpy +import numpy.core.fromnumeric as fromnumeric +from scipy.testing import * +from numpy import array as narray + +from scipy.sandbox.maskedarray.testutils import * + +import scipy.sandbox.maskedarray.core as coremodule +from scipy.sandbox.maskedarray.core import * + +pi = numpy.pi + +#.............................................................................. +class TestMA(TestCase): + "Base test class for MaskedArrays." + def __init__(self, *args, **kwds): + TestCase.__init__(self, *args, **kwds) + self.setUp() + + def setUp (self): + "Base data definition." + x = narray([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) + y = narray([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 = masked_array(x, mask=m1) + ym = masked_array(y, mask=m2) + z = narray([-.5, 0., .5, .8]) + zm = masked_array(z, mask=[0,1,0,0]) + xf = numpy.where(m1, 1.e+20, x) + xm.set_fill_value(1.e+20) + self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf) + #........................ + 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()) + fail_if_equal(xm.mask.astype(int_), ym.mask.astype(int_)) + s = x.shape + assert_equal(numpy.shape(xm), s) + assert_equal(xm.shape, s) + assert_equal(xm.dtype, x.dtype) + assert_equal(zm.dtype, z.dtype) + assert_equal(xm.size , reduce(lambda x,y:x*y, s)) + assert_equal(count(xm) , len(m1) - reduce(lambda x,y:x+y, m1)) + assert_array_equal(xm, xf) + assert_array_equal(filled(xm, 1.e20), xf) + assert_array_equal(x, xm) + #........................ + def test_basic2d(self): + "Test of basic array creation and properties in 2 dimensions." + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + for s in [(4,3), (6,2)]: + x.shape = s + y.shape = s + xm.shape = s + ym.shape = s + xf.shape = s + + assert(not isMaskedArray(x)) + assert(isMaskedArray(xm)) + assert_equal(shape(xm), s) + assert_equal(xm.shape, s) + assert_equal( xm.size , reduce(lambda x,y:x*y, s)) + assert_equal( count(xm) , len(m1) - reduce(lambda x,y:x+y, m1)) + assert_equal(xm, xf) + assert_equal(filled(xm, 1.e20), xf) + assert_equal(x, xm) + #........................ + def test_basic_arithmetic (self): + "Test of basic arithmetic." + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + a2d = array([[1,2],[0,4]]) + a2dm = masked_array(a2d, [[0,0],[1,0]]) + assert_equal(a2d * a2d, a2d * a2dm) + assert_equal(a2d + a2d, a2d + a2dm) + assert_equal(a2d - a2d, a2d - a2dm) + for s in [(12,), (4,3), (2,6)]: + x = x.reshape(s) + y = y.reshape(s) + xm = xm.reshape(s) + ym = ym.reshape(s) + xf = xf.reshape(s) + assert_equal(-x, -xm) + assert_equal(x + y, xm + ym) + assert_equal(x - y, xm - ym) + assert_equal(x * y, xm * ym) + assert_equal(x / y, xm / ym) + assert_equal(a10 + y, a10 + ym) + assert_equal(a10 - y, a10 - ym) + assert_equal(a10 * y, a10 * ym) + assert_equal(a10 / y, a10 / ym) + assert_equal(x + a10, xm + a10) + assert_equal(x - a10, xm - a10) + assert_equal(x * a10, xm * a10) + assert_equal(x / a10, xm / a10) + assert_equal(x**2, xm**2) + assert_equal(abs(x)**2.5, abs(xm) **2.5) + assert_equal(x**y, xm**ym) + assert_equal(numpy.add(x,y), add(xm, ym)) + assert_equal(numpy.subtract(x,y), subtract(xm, ym)) + assert_equal(numpy.multiply(x,y), multiply(xm, ym)) + assert_equal(numpy.divide(x,y), divide(xm, ym)) + #........................ + def test_mixed_arithmetic(self): + "Tests mixed arithmetics." + na = narray([1]) + ma = array([1]) + self.failUnless(isinstance(na + ma, MaskedArray)) + self.failUnless(isinstance(ma + na, MaskedArray)) + #........................ + def test_inplace_arithmetic(self): + """Test of inplace operations and rich comparisons""" + # addition + x = arange(10) + y = arange(10) + xm = arange(10) + xm[2] = masked + x += 1 + assert_equal(x, y+1) + xm += 1 + assert_equal(xm, y+1) + # subtraction + x = arange(10) + xm = arange(10) + xm[2] = masked + x -= 1 + assert_equal(x, y-1) + xm -= 1 + assert_equal(xm, y-1) + # multiplication + x = arange(10)*1.0 + xm = arange(10)*1.0 + xm[2] = masked + x *= 2.0 + assert_equal(x, y*2) + xm *= 2.0 + assert_equal(xm, y*2) + # division + x = arange(10)*2 + xm = arange(10)*2 + xm[2] = masked + x /= 2 + assert_equal(x, y) + xm /= 2 + assert_equal(xm, y) + # division, pt 2 + x = arange(10)*1.0 + xm = arange(10)*1.0 + xm[2] = masked + x /= 2.0 + assert_equal(x, y/2.0) + xm /= arange(10) + assert_equal(xm, ones((10,))) + + x = arange(10).astype(float_) + xm = arange(10) + xm[2] = masked +# id1 = id(x.raw_data()) + id1 = x.raw_data().ctypes.data + x += 1. +# assert id1 == id(x.raw_data()) + assert (id1 == x.raw_data().ctypes.data) + assert_equal(x, y+1.) + # addition w/ array + x = arange(10, dtype=float_) + xm = arange(10, dtype=float_) + xm[2] = masked + m = xm.mask + a = arange(10, dtype=float_) + a[-1] = masked + x += a + xm += a + assert_equal(x,y+a) + assert_equal(xm,y+a) + assert_equal(xm.mask, mask_or(m,a.mask)) + # subtraction w/ array + x = arange(10, dtype=float_) + xm = arange(10, dtype=float_) + xm[2] = masked + m = xm.mask + a = arange(10, dtype=float_) + a[-1] = masked + x -= a + xm -= a + assert_equal(x,y-a) + assert_equal(xm,y-a) + assert_equal(xm.mask, mask_or(m,a.mask)) + # multiplication w/ array + x = arange(10, dtype=float_) + xm = arange(10, dtype=float_) + xm[2] = masked + m = xm.mask + a = arange(10, dtype=float_) + a[-1] = masked + x *= a + xm *= a + assert_equal(x,y*a) + assert_equal(xm,y*a) + assert_equal(xm.mask, mask_or(m,a.mask)) + # division w/ array + x = arange(10, dtype=float_) + xm = arange(10, dtype=float_) + xm[2] = masked + m = xm.mask + a = arange(10, dtype=float_) + a[-1] = masked + x /= a + xm /= a + assert_equal(x,y/a) + assert_equal(xm,y/a) + assert_equal(xm.mask, mask_or(mask_or(m,a.mask), (a==0))) + # + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + z = xm/ym + assert_equal(z._mask, [1,1,1,0,0,1,1,0,0,0,1,1]) + assert_equal(z._data, [0.2,1.,1./3.,-1.,-pi/2.,-1.,5.,1.,1.,1.,2.,1.]) + xm = xm.copy() + xm /= ym + assert_equal(xm._mask, [1,1,1,0,0,1,1,0,0,0,1,1]) + assert_equal(xm._data, [1/5.,1.,1./3.,-1.,-pi/2.,-1.,5.,1.,1.,1.,2.,1.]) + + + #.......................... + def test_scalararithmetic(self): + "Tests some scalar arithmetics on MaskedArrays." + xm = array(0, mask=1) + assert((1/array(0)).mask) + assert((1 + xm).mask) + assert((-xm).mask) + assert((-xm).mask) + assert(maximum(xm, xm).mask) + assert(minimum(xm, xm).mask) + assert(xm.filled().dtype is xm.data.dtype) + x = array(0, mask=0) + assert_equal(x.filled().ctypes.data, x.ctypes.data) + assert_equal(str(xm), str(masked_print_option)) + #......................... + def test_basic_ufuncs (self): + "Test various functions such as sin, cos." + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + assert_equal(numpy.cos(x), cos(xm)) + assert_equal(numpy.cosh(x), cosh(xm)) + assert_equal(numpy.sin(x), sin(xm)) + assert_equal(numpy.sinh(x), sinh(xm)) + assert_equal(numpy.tan(x), tan(xm)) + assert_equal(numpy.tanh(x), tanh(xm)) + assert_equal(numpy.sqrt(abs(x)), sqrt(xm)) + assert_equal(numpy.log(abs(x)), log(xm)) + assert_equal(numpy.log10(abs(x)), log10(xm)) + assert_equal(numpy.exp(x), exp(xm)) + assert_equal(numpy.arcsin(z), arcsin(zm)) + assert_equal(numpy.arccos(z), arccos(zm)) + assert_equal(numpy.arctan(z), arctan(zm)) + assert_equal(numpy.arctan2(x, y), arctan2(xm, ym)) + assert_equal(numpy.absolute(x), absolute(xm)) + assert_equal(numpy.equal(x,y), equal(xm, ym)) + assert_equal(numpy.not_equal(x,y), not_equal(xm, ym)) + assert_equal(numpy.less(x,y), less(xm, ym)) + assert_equal(numpy.greater(x,y), greater(xm, ym)) + assert_equal(numpy.less_equal(x,y), less_equal(xm, ym)) + assert_equal(numpy.greater_equal(x,y), greater_equal(xm, ym)) + assert_equal(numpy.conjugate(x), conjugate(xm)) + #........................ + def test_count_func (self): + "Tests count" + ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) + assert( isinstance(count(ott), int)) + assert_equal(3, count(ott)) + assert_equal(1, count(1)) + assert_equal(0, array(1,mask=[1])) + ott = ott.reshape((2,2)) + assert isMaskedArray(count(ott,0)) + assert isinstance(count(ott), types.IntType) + assert_equal(3, count(ott)) + assert getmask(count(ott,0)) is nomask + assert_equal([1,2],count(ott,0)) + #........................ + def test_minmax_func (self): + "Tests minimum and maximum." + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + xr = numpy.ravel(x) #max doesn't work if shaped + xmr = ravel(xm) + assert_equal(max(xr), maximum(xmr)) #true because of careful selection of data + assert_equal(min(xr), minimum(xmr)) #true because of careful selection of data + # + assert_equal(minimum([1,2,3],[4,0,9]), [1,0,3]) + assert_equal(maximum([1,2,3],[4,0,9]), [4,2,9]) + x = arange(5) + y = arange(5) - 2 + x[3] = masked + y[0] = masked + assert_equal(minimum(x,y), where(less(x,y), x, y)) + assert_equal(maximum(x,y), where(greater(x,y), x, y)) + assert minimum(x) == 0 + assert maximum(x) == 4 + # + x = arange(4).reshape(2,2) + x[-1,-1] = masked + assert_equal(maximum(x), 2) + + def test_minmax_methods(self): + "Additional tests on max/min" + (_, _, _, _, _, 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) + 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) + 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) + #........................ + def test_addsumprod (self): + "Tests add, sum, product." + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + assert_equal(numpy.add.reduce(x), add.reduce(x)) + assert_equal(numpy.add.accumulate(x), add.accumulate(x)) + assert_equal(4, sum(array(4),axis=0)) + assert_equal(4, sum(array(4), axis=0)) + assert_equal(numpy.sum(x,axis=0), sum(x,axis=0)) + assert_equal(numpy.sum(filled(xm,0),axis=0), sum(xm,axis=0)) + assert_equal(numpy.sum(x,0), sum(x,0)) + assert_equal(numpy.product(x,axis=0), product(x,axis=0)) + assert_equal(numpy.product(x,0), product(x,0)) + assert_equal(numpy.product(filled(xm,1),axis=0), product(xm,axis=0)) + s = (3,4) + x.shape = y.shape = xm.shape = ym.shape = s + if len(s) > 1: + assert_equal(numpy.concatenate((x,y),1), concatenate((xm,ym),1)) + assert_equal(numpy.add.reduce(x,1), add.reduce(x,1)) + assert_equal(numpy.sum(x,1), sum(x,1)) + assert_equal(numpy.product(x,1), product(x,1)) + #......................... + def test_concat(self): + "Tests concatenations." + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + # basic concatenation + assert_equal(numpy.concatenate((x,y)), concatenate((xm,ym))) + assert_equal(numpy.concatenate((x,y)), concatenate((x,y))) + assert_equal(numpy.concatenate((x,y)), concatenate((xm,y))) + assert_equal(numpy.concatenate((x,y,x)), concatenate((x,ym,x))) + # Concatenation along an axis + s = (3,4) + x.shape = y.shape = xm.shape = ym.shape = s + assert_equal(xm.mask, numpy.reshape(m1, s)) + assert_equal(ym.mask, numpy.reshape(m2, s)) + xmym = concatenate((xm,ym),1) + assert_equal(numpy.concatenate((x,y),1), xmym) + assert_equal(numpy.concatenate((xm.mask,ym.mask),1), xmym._mask) + #........................ + def test_indexing(self): + "Tests conversions and indexing" + x1 = numpy.array([1,2,4,3]) + x2 = array(x1, mask=[1,0,0,0]) + x3 = array(x1, mask=[0,1,0,1]) + x4 = array(x1) + # test conversion to strings + junk, garbage = str(x2), repr(x2) + assert_equal(numpy.sort(x1),sort(x2,endwith=False)) + # tests of indexing + assert type(x2[1]) is type(x1[1]) + assert x1[1] == x2[1] + assert x2[0] is masked + assert_equal(x1[2],x2[2]) + assert_equal(x1[2:5],x2[2:5]) + assert_equal(x1[:],x2[:]) + assert_equal(x1[1:], x3[1:]) + x1[2] = 9 + x2[2] = 9 + assert_equal(x1,x2) + x1[1:3] = 99 + x2[1:3] = 99 + assert_equal(x1,x2) + x2[1] = masked + assert_equal(x1,x2) + x2[1:3] = masked + assert_equal(x1,x2) + x2[:] = x1 + x2[1] = masked + assert allequal(getmask(x2),array([0,1,0,0])) + x3[:] = masked_array([1,2,3,4],[0,1,1,0]) + assert allequal(getmask(x3), array([0,1,1,0])) + x4[:] = masked_array([1,2,3,4],[0,1,1,0]) + assert allequal(getmask(x4), array([0,1,1,0])) + assert allequal(x4, array([1,2,3,4])) + x1 = numpy.arange(5)*1.0 + x2 = masked_values(x1, 3.0) + assert_equal(x1,x2) + assert allequal(array([0,0,0,1,0],MaskType), x2.mask) +#FIXME: Well, eh, fill_value is now a property assert_equal(3.0, x2.fill_value()) + assert_equal(3.0, x2.fill_value) + x1 = array([1,'hello',2,3],object) + x2 = numpy.array([1,'hello',2,3],object) + s1 = x1[1] + s2 = x2[1] + assert_equal(type(s2), str) + assert_equal(type(s1), str) + assert_equal(s1, s2) + assert x1[1:1].shape == (0,) + #........................ + def test_copy(self): + "Tests of some subtle points of copying and sizing." + n = [0,0,1,0,0] + m = make_mask(n) + m2 = make_mask(m) + assert(m is m2) + m3 = make_mask(m, copy=1) + assert(m is not m3) + + x1 = numpy.arange(5) + y1 = array(x1, mask=m) + #assert( y1._data is x1) + assert_equal(y1._data.__array_interface__, x1.__array_interface__) + assert( allequal(x1,y1.raw_data())) + #assert( y1.mask is m) + assert_equal(y1._mask.__array_interface__, m.__array_interface__) + + 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) + + 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) + 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)) + + y3 = array(x1*1.0, mask=m) + assert(filled(y3).dtype is (x1*1.0).dtype) + + x4 = arange(4) + x4[2] = masked + y4 = resize(x4, (8,)) + assert_equal(concatenate([x4,x4]), y4) + assert_equal(getmask(y4),[0,0,1,0,0,0,1,0]) + y5 = repeat(x4, (2,2,2,2), axis=0) + assert_equal(y5, [0,0,1,1,2,2,3,3]) + y6 = repeat(x4, 2, axis=0) + assert_equal(y5, y6) + y7 = x4.repeat((2,2,2,2), axis=0) + assert_equal(y5,y7) + y8 = x4.repeat(2,0) + assert_equal(y5,y8) + + y9 = x4.copy() + assert_equal(y9._data, x4._data) + assert_equal(y9._mask, x4._mask) + # + x = masked_array([1,2,3], mask=[0,1,0]) + # Copy is False by default + y = masked_array(x) +# assert_equal(id(y._data), id(x._data)) +# assert_equal(id(y._mask), id(x._mask)) + assert_equal(y._data.ctypes.data, x._data.ctypes.data) + assert_equal(y._mask.ctypes.data, x._mask.ctypes.data) + y = masked_array(x, copy=True) +# assert_not_equal(id(y._data), id(x._data)) +# assert_not_equal(id(y._mask), id(x._mask)) + assert_not_equal(y._data.ctypes.data, x._data.ctypes.data) + assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data) + #........................ + def test_where(self): + "Test the where function" + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + d = where(xm>2,xm,-9) + assert_equal(d, [-9.,-9.,-9.,-9., -9., 4., -9., -9., 10., -9., -9., 3.]) + assert_equal(d._mask, xm._mask) + d = where(xm>2,-9,ym) + assert_equal(d, [5.,0.,3., 2., -1.,-9.,-9., -10., -9., 1., 0., -9.]) + assert_equal(d._mask, [1,0,1,0,0,0,1,0,0,0,0,0]) + d = where(xm>2, xm, masked) + assert_equal(d, [-9.,-9.,-9.,-9., -9., 4., -9., -9., 10., -9., -9., 3.]) + tmp = xm._mask.copy() + tmp[(xm<=2).filled(True)] = True + assert_equal(d._mask, tmp) + # + ixm = xm.astype(int_) + d = where(ixm>2, ixm, masked) + assert_equal(d, [-9,-9,-9,-9, -9, 4, -9, -9, 10, -9, -9, 3]) + assert_equal(d.dtype, ixm.dtype) + # + x = arange(10) + x[3] = masked + c = x >= 8 + z = where(c , x, masked) + assert z.dtype is x.dtype + assert z[3] is masked + assert z[4] is masked + assert z[7] is masked + assert z[8] is not masked + assert z[9] is not masked + assert_equal(x,z) + # + z = where(c , masked, x) + assert z.dtype is x.dtype + assert z[3] is masked + assert z[4] is not masked + assert z[7] is not masked + assert z[8] is masked + assert z[9] is masked + + #........................ + def test_oddfeatures_1(self): + "Test of other odd features" + x = arange(20) + x = x.reshape(4,5) + x.flat[5] = 12 + assert x[1,0] == 12 + z = x + 10j * x + assert_equal(z.real, x) + assert_equal(z.imag, 10*x) + assert_equal((z*conjugate(z)).real, 101*x*x) + z.imag[...] = 0.0 + + x = arange(10) + x[3] = masked + assert str(x[3]) == str(masked) + c = x >= 8 + assert count(where(c,masked,masked)) == 0 + assert shape(where(c,masked,masked)) == c.shape + # + z = masked_where(c, x) + assert z.dtype is x.dtype + assert z[3] is masked + assert z[4] is not masked + assert z[7] is not masked + assert z[8] is masked + assert z[9] is masked + assert_equal(x,z) + # + #........................ + def test_oddfeatures_2(self): + "Tests some more features." + x = array([1.,2.,3.,4.,5.]) + c = array([1,1,1,0,0]) + x[2] = masked + z = where(c, x, -x) + assert_equal(z, [1.,2.,0., -4., -5]) + c[0] = masked + z = where(c, x, -x) + assert_equal(z, [1.,2.,0., -4., -5]) + assert z[0] is masked + assert z[1] is not masked + assert z[2] is masked + # + x = arange(6) + x[5] = masked + y = arange(6)*10 + y[2] = masked + c = array([1,1,1,0,0,0], mask=[1,0,0,0,0,0]) + cm = c.filled(1) + z = where(c,x,y) + zm = where(cm,x,y) + assert_equal(z, zm) + assert getmask(zm) is nomask + assert_equal(zm, [0,1,2,30,40,50]) + z = where(c, masked, 1) + assert_equal(z, [99,99,99,1,1,1]) + z = where(c, 1, masked) + assert_equal(z, [99, 1, 1, 99, 99, 99]) + #........................ + def test_oddfeatures_3(self): + """Tests some generic features.""" + atest = ones((10,10,10), dtype=float_) + btest = zeros(atest.shape, MaskType) + ctest = masked_where(btest,atest) + assert_equal(atest,ctest) + #........................ + def test_maskingfunctions(self): + "Tests masking functions." + x = array([1.,2.,3.,4.,5.]) + x[2] = masked + assert_equal(masked_where(greater(x, 2), x), masked_greater(x,2)) + assert_equal(masked_where(greater_equal(x, 2), x), masked_greater_equal(x,2)) + assert_equal(masked_where(less(x, 2), x), masked_less(x,2)) + assert_equal(masked_where(less_equal(x, 2), x), masked_less_equal(x,2)) + assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x,2)) + assert_equal(masked_where(equal(x, 2), x), masked_equal(x,2)) + assert_equal(masked_where(not_equal(x,2), x), masked_not_equal(x,2)) + assert_equal(masked_inside(range(5), 1, 3), [0, 199, 199, 199, 4]) + assert_equal(masked_outside(range(5), 1, 3),[199,1,2,3,199]) + assert_equal(masked_inside(array(range(5), mask=[1,0,0,0,0]), 1, 3).mask, [1,1,1,1,0]) + assert_equal(masked_outside(array(range(5), mask=[0,1,0,0,0]), 1, 3).mask, [1,1,0,0,1]) + assert_equal(masked_equal(array(range(5), mask=[1,0,0,0,0]), 2).mask, [1,0,1,0,0]) + assert_equal(masked_not_equal(array([2,2,1,2,1], mask=[1,0,0,0,0]), 2).mask, [1,0,1,0,1]) + assert_equal(masked_where([1,1,0,0,0], [1,2,3,4,5]), [99,99,3,4,5]) + #........................ + def test_TakeTransposeInnerOuter(self): + "Test of take, transpose, inner, outer products" + x = arange(24) + y = numpy.arange(24) + x[5:6] = masked + x = x.reshape(2,3,4) + y = y.reshape(2,3,4) + assert_equal(numpy.transpose(y,(2,0,1)), transpose(x,(2,0,1))) + assert_equal(numpy.take(y, (2,0,1), 1), take(x, (2,0,1), 1)) + assert_equal(numpy.inner(filled(x,0),filled(y,0)), + inner(x, y)) + assert_equal(numpy.outer(filled(x,0),filled(y,0)), + outer(x, y)) + y = array(['abc', 1, 'def', 2, 3], object) + y[2] = masked + t = take(y,[0,3,4]) + assert t[0] == 'abc' + assert t[1] == 2 + assert t[2] == 3 + #....................... + def test_maskedelement(self): + "Test of masked element" + x = arange(6) + x[1] = masked + assert(str(masked) == '--') + assert(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) + #self.failUnlessRaises(Exception, lambda x,y: x+y, masked, 2) + #self.failUnlessRaises(Exception, lambda x,y: x+y, masked, xx) + #self.failUnlessRaises(Exception, lambda x,y: x+y, xx, masked) + #........................ + def test_scalar(self): + "Checks masking a scalar" + x = masked_array(0) + assert_equal(str(x), '0') + x = masked_array(0,mask=True) + assert_equal(str(x), str(masked_print_option)) + x = masked_array(0, mask=False) + assert_equal(str(x), '0') + #........................ + def test_usingmasked(self): + "Checks that there's no collapsing to masked" + x = masked_array([1,2]) + y = x * masked + assert_equal(y.shape, x.shape) + assert_equal(y._mask, [True, True]) + y = x[0] * masked + assert y is masked + y = x + masked + assert_equal(y.shape, x.shape) + assert_equal(y._mask, [True, True]) + + #........................ + def test_topython(self): + "Tests some communication issues with Python." + assert_equal(1, int(array(1))) + assert_equal(1.0, float(array(1))) + assert_equal(1, int(array([[[1]]]))) + assert_equal(1.0, float(array([[1]]))) + self.failUnlessRaises(ValueError, float, array([1,1])) + assert numpy.isnan(float(array([1],mask=[1]))) +#TODO: Check how bool works... +#TODO: self.failUnless(bool(array([0,1]))) +#TODO: self.failUnless(bool(array([0,0],mask=[0,1]))) +#TODO: self.failIf(bool(array([0,0]))) +#TODO: self.failIf(bool(array([0,0],mask=[0,0]))) + #........................ + def test_arraymethods(self): + "Tests some MaskedArray methods." + a = array([1,3,2]) + b = array([1,3,2], mask=[1,0,1]) + assert_equal(a.any(), a.data.any()) + assert_equal(a.all(), a.data.all()) + assert_equal(a.argmax(), a.data.argmax()) + assert_equal(a.argmin(), a.data.argmin()) + assert_equal(a.choose(0,1,2,3,4), a.data.choose(0,1,2,3,4)) + assert_equal(a.compress([1,0,1]), a.data.compress([1,0,1])) + assert_equal(a.conj(), a.data.conj()) + assert_equal(a.conjugate(), a.data.conjugate()) + # + m = array([[1,2],[3,4]]) + assert_equal(m.diagonal(), m.data.diagonal()) + assert_equal(a.sum(), a.data.sum()) + assert_equal(a.take([1,2]), a.data.take([1,2])) + assert_equal(m.transpose(), m.data.transpose()) + #........................ + def test_basicattributes(self): + "Tests some basic array attributes." + a = array([1,3,2]) + b = array([1,3,2], mask=[1,0,1]) + assert_equal(a.ndim, 1) + assert_equal(b.ndim, 1) + assert_equal(a.size, 3) + assert_equal(b.size, 3) + assert_equal(a.shape, (3,)) + assert_equal(b.shape, (3,)) + #........................ + def test_single_element_subscript(self): + "Tests single element subscripts of Maskedarrays." + a = array([1,3,2]) + b = array([1,3,2], mask=[1,0,1]) + assert_equal(a[0].shape, ()) + assert_equal(b[0].shape, ()) + assert_equal(b[1].shape, ()) + #........................ + def test_maskcreation(self): + "Tests how masks are initialized at the creation of Maskedarrays." + data = arange(24, dtype=float_) + data[[3,6,15]] = masked + dma_1 = MaskedArray(data) + assert_equal(dma_1.mask, data.mask) + dma_2 = MaskedArray(dma_1) + assert_equal(dma_2.mask, dma_1.mask) + dma_3 = MaskedArray(dma_1, mask=[1,0,0,0]*6) + fail_if_equal(dma_3.mask, dma_1.mask) + + def test_backwards(self): + "Tests backward compatibility with numpy.core.ma" + import numpy.core.ma as nma + x = nma.arange(5) + x[2] = nma.masked + X = masked_array(x, mask=x._mask) + assert_equal(X._mask, x.mask) + assert_equal(X._data, x._data) + X = masked_array(x) + assert_equal(X._data, x._data) + assert_equal(X._mask, x.mask) + assert_equal(getmask(x), [0,0,1,0,0]) + + def test_pickling(self): + "Tests pickling" + import cPickle + a = arange(10) + a[::3] = masked + a.fill_value = 999 + a_pickled = cPickle.loads(a.dumps()) + assert_equal(a_pickled._mask, a._mask) + assert_equal(a_pickled._data, a._data) + assert_equal(a_pickled.fill_value, 999) + # + a = array(numpy.matrix(range(10)), mask=[1,0,1,0,0]*2) + a_pickled = cPickle.loads(a.dumps()) + assert_equal(a_pickled._mask, a._mask) + assert_equal(a_pickled, a) + assert(isinstance(a_pickled._data,numpy.matrix)) + # + def test_fillvalue(self): + "Check that we don't lose the fill_value" + data = masked_array([1,2,3],fill_value=-999) + series = data[[0,2,1]] + assert_equal(series._fill_value, data._fill_value) + # + def test_asarray(self): + (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d + xmm = asarray(xm) + assert_equal(xmm._data, xm._data) + assert_equal(xmm._mask, xm._mask) + # + def test_fix_invalid(self): + "Checks fix_invalid." + data = masked_array(numpy.sqrt([-1., 0., 1.]), mask=[0,0,1]) + data_fixed = fix_invalid(data) + assert_equal(data_fixed._data, [data.fill_value, 0., 1.]) + assert_equal(data_fixed._mask, [1., 0., 1.]) + # + def test_imag_real(self): + xx = array([1+10j,20+2j], mask=[1,0]) + assert_equal(xx.imag,[10,2]) + assert_equal(xx.imag.filled(), [1e+20,2]) + assert_equal(xx.imag.dtype, xx._data.imag.dtype) + assert_equal(xx.real,[1,20]) + assert_equal(xx.real.filled(), [1e+20,20]) + assert_equal(xx.real.dtype, xx._data.real.dtype) + +#............................................................................... + +class TestUfuncs(TestCase): + "Test class for the application of ufuncs on MaskedArrays." + def setUp(self): + "Base data definition." + self.d = (array([1.0, 0, -1, pi/2]*2, mask=[0,1]+[0]*6), + array([1.0, 0, -1, pi/2]*2, mask=[1,0]+[0]*6),) + + def test_testUfuncRegression(self): + "Tests new ufuncs on MaskedArrays." + for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', + 'sin', 'cos', 'tan', + 'arcsin', 'arccos', 'arctan', + 'sinh', 'cosh', 'tanh', + 'arcsinh', + 'arccosh', + 'arctanh', + 'absolute', 'fabs', 'negative', + # 'nonzero', 'around', + 'floor', 'ceil', + # 'sometrue', 'alltrue', + 'logical_not', + 'add', 'subtract', 'multiply', + 'divide', 'true_divide', 'floor_divide', + 'remainder', 'fmod', 'hypot', 'arctan2', + 'equal', 'not_equal', 'less_equal', 'greater_equal', + 'less', 'greater', + 'logical_and', 'logical_or', 'logical_xor', + ]: + #print f + try: + uf = getattr(umath, f) + except AttributeError: + uf = getattr(fromnumeric, f) + mf = getattr(coremodule, f) + args = self.d[:uf.nin] + ur = uf(*args) + mr = mf(*args) + assert_equal(ur.filled(0), mr.filled(0), f) + assert_mask_equal(ur.mask, mr.mask) + #........................ + def test_reduce(self): + "Tests reduce on MaskedArrays." + a = self.d[0] + assert(not alltrue(a,axis=0)) + assert(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) + #........................ + def test_minmax(self): + "Tests extrema on MaskedArrays." + a = arange(1,13).reshape(3,4) + amask = masked_where(a < 5,a) + assert_equal(amask.max(), a.max()) + 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) + +#............................................................................... + +class TestArrayMethods(TestCase): + "Test class for miscellaneous MaskedArrays methods." + def setUp(self): + "Base data definition." + x = numpy.array([ 8.375, 7.545, 8.828, 8.5 , 1.757, 5.928, + 8.43 , 7.78 , 9.865, 5.878, 8.979, 4.732, + 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, + 6.04 , 9.63 , 7.712, 3.382, 4.489, 6.479, + 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, + 7.357, 9.828, 6.272, 3.758, 6.693, 0.993]) + X = x.reshape(6,6) + XX = x.reshape(3,2,2,3) + + m = numpy.array([0, 1, 0, 1, 0, 0, + 1, 0, 1, 1, 0, 1, + 0, 0, 0, 1, 0, 1, + 0, 0, 0, 1, 1, 1, + 1, 0, 0, 1, 0, 0, + 0, 0, 1, 0, 1, 0]) + mx = array(data=x,mask=m) + mX = array(data=X,mask=m.reshape(X.shape)) + mXX = array(data=XX,mask=m.reshape(XX.shape)) + + m2 = numpy.array([1, 1, 0, 1, 0, 0, + 1, 1, 1, 1, 0, 1, + 0, 0, 1, 1, 0, 1, + 0, 0, 0, 1, 1, 1, + 1, 0, 0, 1, 1, 0, + 0, 0, 1, 0, 1, 1]) + m2x = array(data=x,mask=m2) + m2X = array(data=X,mask=m2.reshape(X.shape)) + m2XX = array(data=XX,mask=m2.reshape(XX.shape)) + self.d = (x,X,XX,m,mx,mX,mXX,m2x,m2X,m2XX) + + #------------------------------------------------------ + def test_trace(self): + "Tests trace on MaskedArrays." + (x,X,XX,m,mx,mX,mXX,m2x,m2X,m2XX) = self.d + mXdiag = mX.diagonal() + assert_equal(mX.trace(), mX.diagonal().compressed().sum()) + assert_almost_equal(mX.trace(), + X.trace() - sum(mXdiag.mask*X.diagonal(),axis=0)) + + def test_clip(self): + "Tests clip on MaskedArrays." + (x,X,XX,m,mx,mX,mXX,m2x,m2X,m2XX) = self.d + clipped = mx.clip(2,8) + assert_equal(clipped.mask,mx.mask) + assert_equal(clipped.data,x.clip(2,8)) + assert_equal(clipped.data,mx.data.clip(2,8)) + + def test_ptp(self): + "Tests ptp on MaskedArrays." + (x,X,XX,m,mx,mX,mXX,m2x,m2X,m2XX) = self.d + (n,m) = X.shape + assert_equal(mx.ptp(),mx.compressed().ptp()) + rows = numpy.zeros(n,numpy.float_) + cols = numpy.zeros(m,numpy.float_) + for k in range(m): + cols[k] = mX[:,k].compressed().ptp() + for k in range(n): + rows[k] = mX[k].compressed().ptp() + assert_equal(mX.ptp(0),cols) + assert_equal(mX.ptp(1),rows) + + def test_swapaxes(self): + "Tests swapaxes on MaskedArrays." + (x,X,XX,m,mx,mX,mXX,m2x,m2X,m2XX) = self.d + mXswapped = mX.swapaxes(0,1) + assert_equal(mXswapped[-1],mX[:,-1]) + mXXswapped = mXX.swapaxes(0,2) + assert_equal(mXXswapped.shape,(2,2,3,3)) + + def test_cumsumprod(self): + "Tests cumsum & cumprod on MaskedArrays." + (x,X,XX,m,mx,mX,mXX,m2x,m2X,m2XX) = self.d + mXcp = mX.cumsum(0) + assert_equal(mXcp.data,mX.filled(0).cumsum(0)) + mXcp = mX.cumsum(1) + assert_equal(mXcp.data,mX.filled(0).cumsum(1)) + # + mXcp = mX.cumprod(0) + assert_equal(mXcp.data,mX.filled(1).cumprod(0)) + mXcp = mX.cumprod(1) + assert_equal(mXcp.data,mX.filled(1).cumprod(1)) + + def test_varstd(self): + "Tests var & std on MaskedArrays." + (x,X,XX,m,mx,mX,mXX,m2x,m2X,m2XX) = self.d + assert_almost_equal(mX.var(axis=None),mX.compressed().var()) + assert_almost_equal(mX.std(axis=None),mX.compressed().std()) + assert_equal(mXX.var(axis=3).shape,XX.var(axis=3).shape) + assert_equal(mX.var().shape,X.var().shape) + (mXvar0,mXvar1) = (mX.var(axis=0), mX.var(axis=1)) + for k in range(6): + assert_almost_equal(mXvar1[k],mX[k].compressed().var()) + assert_almost_equal(mXvar0[k],mX[:,k].compressed().var()) + assert_almost_equal(numpy.sqrt(mXvar0[k]), mX[:,k].compressed().std()) + + def test_argmin(self): + "Tests argmin & argmax on MaskedArrays." + (x,X,XX,m,mx,mX,mXX,m2x,m2X,m2XX) = self.d + # + assert_equal(mx.argmin(),35) + assert_equal(mX.argmin(),35) + assert_equal(m2x.argmin(),4) + assert_equal(m2X.argmin(),4) + assert_equal(mx.argmax(),28) + assert_equal(mX.argmax(),28) + assert_equal(m2x.argmax(),31) + assert_equal(m2X.argmax(),31) + # + assert_equal(mX.argmin(0), [2,2,2,5,0,5]) + assert_equal(m2X.argmin(0), [2,2,4,5,0,4]) + assert_equal(mX.argmax(0), [0,5,0,5,4,0]) + assert_equal(m2X.argmax(0), [5,5,0,5,1,0]) + # + assert_equal(mX.argmin(1), [4,1,0,0,5,5,]) + assert_equal(m2X.argmin(1), [4,4,0,0,5,3]) + assert_equal(mX.argmax(1), [2,4,1,1,4,1]) + assert_equal(m2X.argmax(1), [2,4,1,1,1,1]) + + def test_put(self): + "Tests put." + d = arange(5) + 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) + x[[1,4]] = [10,40] +# assert( x.mask is not m) + assert( x[3] is masked) + assert( 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) + i = [0,2,4,6] + x.put(i, [6,4,2,0]) + assert_equal(x, asarray([6,1,4,3,2,5,0,7,8,9,])) + assert_equal(x.mask, [0,0,0,0,0,1,0,0,0,0]) + x.put(i, masked_array([0,2,4,6],[1,0,1,0])) + assert_array_equal(x, [0,1,2,3,4,5,6,7,8,9,]) + assert_equal(x.mask, [1,0,0,0,1,1,0,0,0,0]) + # + x = masked_array(arange(10), mask=[1,0,0,0,0]*2) + put(x, i, [6,4,2,0]) + assert_equal(x, asarray([6,1,4,3,2,5,0,7,8,9,])) + assert_equal(x.mask, [0,0,0,0,0,1,0,0,0,0]) + put(x, i, masked_array([0,2,4,6],[1,0,1,0])) + assert_array_equal(x, [0,1,2,3,4,5,6,7,8,9,]) + assert_equal(x.mask, [1,0,0,0,1,1,0,0,0,0]) + + def test_put_hardmask(self): + "Tests put on hardmask" + d = arange(5) + n = [0,0,0,1,1] + m = make_mask(n) + xh = array(d+1, mask = m, hard_mask=True, copy=True) + xh.put([4,2,0,1,3],[1,2,3,4,5]) + assert_equal(xh._data, [3,4,2,4,5]) + + def test_take(self): + "Tests take" + x = masked_array([10,20,30,40],[0,1,0,1]) + assert_equal(x.take([0,0,3]), masked_array([10, 10, 40], [0,0,1]) ) + assert_equal(x.take([0,0,3]), x[[0,0,3]]) + assert_equal(x.take([[0,1],[0,1]]), + masked_array([[10,20],[10,20]], [[0,1],[0,1]]) ) + # + x = array([[10,20,30],[40,50,60]], mask=[[0,0,1],[1,0,0,]]) + assert_equal(x.take([0,2], axis=1), + array([[10,30],[40,60]], mask=[[0,1],[1,0]])) + assert_equal(take(x, [0,2], axis=1), + array([[10,30],[40,60]], mask=[[0,1],[1,0]])) + #........................ + def test_anyall(self): + """Checks the any/all methods/functions.""" + x = numpy.array([[ 0.13, 0.26, 0.90], + [ 0.28, 0.33, 0.63], + [ 0.31, 0.87, 0.70]]) + m = numpy.array([[ True, False, False], + [False, False, False], + [True, True, False]], dtype=numpy.bool_) + mx = masked_array(x, mask=m) + xbig = numpy.array([[False, False, True], + [False, False, True], + [False, True, True]], dtype=numpy.bool_) + mxbig = (mx > 0.5) + mxsmall = (mx < 0.5) + # + assert (mxbig.all()==False) + assert (mxbig.any()==True) + assert_equal(mxbig.all(0),[False, False, True]) + assert_equal(mxbig.all(1), [False, False, True]) + assert_equal(mxbig.any(0),[False, False, True]) + assert_equal(mxbig.any(1), [True, True, True]) + # + assert (mxsmall.all()==False) + assert (mxsmall.any()==True) + assert_equal(mxsmall.all(0), [True, True, False]) + assert_equal(mxsmall.all(1), [False, False, False]) + assert_equal(mxsmall.any(0), [True, True, False]) + assert_equal(mxsmall.any(1), [True, True, False]) + # + X = numpy.matrix(x) + mX = masked_array(X, mask=m) + mXbig = (mX > 0.5) + mXsmall = (mX < 0.5) + # + assert (mXbig.all()==False) + assert (mXbig.any()==True) + assert_equal(mXbig.all(0), numpy.matrix([False, False, True])) + assert_equal(mXbig.all(1), numpy.matrix([False, False, True]).T) + assert_equal(mXbig.any(0), numpy.matrix([False, False, True])) + assert_equal(mXbig.any(1), numpy.matrix([ True, True, True]).T) + # + assert (mXsmall.all()==False) + assert (mXsmall.any()==True) + assert_equal(mXsmall.all(0), numpy.matrix([True, True, False])) + assert_equal(mXsmall.all(1), numpy.matrix([False, False, False]).T) + assert_equal(mXsmall.any(0), numpy.matrix([True, True, False])) + assert_equal(mXsmall.any(1), numpy.matrix([True, True, False]).T) + + def test_keepmask(self): + "Tests the keep mask flag" + x = masked_array([1,2,3], mask=[1,0,0]) + mx = masked_array(x) + assert_equal(mx.mask, x.mask) + mx = masked_array(x, mask=[0,1,0], keep_mask=False) + assert_equal(mx.mask, [0,1,0]) + mx = masked_array(x, mask=[0,1,0], keep_mask=True) + assert_equal(mx.mask, [1,1,0]) + # We default to true + mx = masked_array(x, mask=[0,1,0]) + assert_equal(mx.mask, [1,1,0]) + + def test_hardmask(self): + "Test hard_mask" + d = arange(5) + n = [0,0,0,1,1] + m = make_mask(n) + xh = array(d, mask = m, hard_mask=True) + # We need to copy, to avoid updating d in xh! + xs = array(d, mask = m, hard_mask=False, copy=True) + xh[[1,4]] = [10,40] + xs[[1,4]] = [10,40] + assert_equal(xh._data, [0,10,2,3,4]) + 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) + xh[1:4] = [10,20,30] + xs[1:4] = [10,20,30] + assert_equal(xh._data, [0,10,20,3,4]) + assert_equal(xs._data, [0,10,20,30,40]) + #assert_equal(xh.mask.ctypes.data, m.ctypes.data) + assert_equal(xs.mask, nomask) + xh[0] = masked + xs[0] = masked + assert_equal(xh.mask, [1,0,0,1,1]) + assert_equal(xs.mask, [1,0,0,0,0]) + xh[:] = 1 + xs[:] = 1 + assert_equal(xh._data, [0,1,1,3,4]) + assert_equal(xs._data, [1,1,1,1,1]) + assert_equal(xh.mask, [1,0,0,1,1]) + assert_equal(xs.mask, nomask) + # Switch to soft mask + xh.soften_mask() + xh[:] = arange(5) + assert_equal(xh._data, [0,1,2,3,4]) + assert_equal(xh.mask, nomask) + # Switch back to hard mask + xh.harden_mask() + xh[xh<3] = masked + assert_equal(xh._data, [0,1,2,3,4]) + assert_equal(xh._mask, [1,1,1,0,0]) + xh[filled(xh>1,False)] = 5 + assert_equal(xh._data, [0,1,2,5,5]) + assert_equal(xh._mask, [1,1,1,0,0]) + # + xh = array([[1,2],[3,4]], mask = [[1,0],[0,0]], hard_mask=True) + xh[0] = 0 + assert_equal(xh._data, [[1,0],[3,4]]) + assert_equal(xh._mask, [[1,0],[0,0]]) + xh[-1,-1] = 5 + assert_equal(xh._data, [[1,0],[3,5]]) + assert_equal(xh._mask, [[1,0],[0,0]]) + xh[filled(xh<5,False)] = 2 + assert_equal(xh._data, [[1,2],[2,5]]) + assert_equal(xh._mask, [[1,0],[0,0]]) + # + "Another test of hardmask" + d = arange(5) + n = [0,0,0,1,1] + m = make_mask(n) + xh = array(d, mask = m, hard_mask=True) + xh[4:5] = 999 + #assert_equal(xh.mask.ctypes.data, m.ctypes.data) + xh[0:1] = 999 + assert_equal(xh._data,[999,1,2,3,4]) + + def test_smallmask(self): + "Checks the behaviour of _smallmask" + a = arange(10) + a[1] = masked + a[1] = 1 + assert_equal(a._mask, nomask) + a = arange(10) + a._smallmask = False + a[1] = masked + a[1] = 1 + assert_equal(a._mask, zeros(10)) + + + def test_sort(self): + "Test sort" + x = array([1,4,2,3],mask=[0,1,0,0],dtype=numpy.uint8) + # + sortedx = sort(x) + assert_equal(sortedx._data,[1,2,3,4]) + assert_equal(sortedx._mask,[0,0,0,1]) + # + sortedx = sort(x, endwith=False) + assert_equal(sortedx._data, [4,1,2,3]) + assert_equal(sortedx._mask, [1,0,0,0]) + # + x.sort() + assert_equal(x._data,[1,2,3,4]) + assert_equal(x._mask,[0,0,0,1]) + # + x = array([1,4,2,3],mask=[0,1,0,0],dtype=numpy.uint8) + x.sort(endwith=False) + assert_equal(x._data, [4,1,2,3]) + assert_equal(x._mask, [1,0,0,0]) + # + x = [1,4,2,3] + sortedx = sort(x) + assert(not isinstance(sorted, MaskedArray)) + # + x = array([0,1,-1,-2,2], mask=nomask, dtype=numpy.int8) + sortedx = sort(x, endwith=False) + assert_equal(sortedx._data, [-2,-1,0,1,2]) + x = array([0,1,-1,-2,2], mask=[0,1,0,0,1], dtype=numpy.int8) + sortedx = sort(x, endwith=False) + assert_equal(sortedx._data, [1,2,-2,-1,0]) + assert_equal(sortedx._mask, [1,1,0,0,0]) + + def test_sort_2d(self): + "Check sort of 2D array." + # 2D array w/o mask + a = masked_array([[8,4,1],[2,0,9]]) + a.sort(0) + assert_equal(a, [[2,0,1],[8,4,9]]) + a = masked_array([[8,4,1],[2,0,9]]) + a.sort(1) + assert_equal(a, [[1,4,8],[0,2,9]]) + # 2D array w/mask + a = masked_array([[8,4,1],[2,0,9]], mask=[[1,0,0],[0,0,1]]) + a.sort(0) + assert_equal(a, [[2,0,1],[8,4,9]]) + assert_equal(a._mask, [[0,0,0],[1,0,1]]) + a = masked_array([[8,4,1],[2,0,9]], mask=[[1,0,0],[0,0,1]]) + a.sort(1) + assert_equal(a, [[1,4,8],[0,2,9]]) + assert_equal(a._mask, [[0,0,1],[0,0,1]]) + # 3D + a = masked_array([[[7, 8, 9],[4, 5, 6],[1, 2, 3]], + [[1, 2, 3],[7, 8, 9],[4, 5, 6]], + [[7, 8, 9],[1, 2, 3],[4, 5, 6]], + [[4, 5, 6],[1, 2, 3],[7, 8, 9]]]) + a[a%4==0] = masked + am = a.copy() + an = a.filled(99) + am.sort(0) + an.sort(0) + assert_equal(am, an) + am = a.copy() + an = a.filled(99) + am.sort(1) + an.sort(1) + assert_equal(am, an) + am = a.copy() + an = a.filled(99) + am.sort(2) + an.sort(2) + assert_equal(am, an) + + + def test_ravel(self): + "Tests ravel" + a = array([[1,2,3,4,5]], mask=[[0,1,0,0,0]]) + aravel = a.ravel() + assert_equal(a._mask.shape, a.shape) + a = array([0,0], mask=[1,1]) + aravel = a.ravel() + assert_equal(a._mask.shape, a.shape) + a = array(numpy.matrix([1,2,3,4,5]), mask=[[0,1,0,0,0]]) + aravel = a.ravel() + assert_equal(a.shape,(1,5)) + assert_equal(a._mask.shape, a.shape) + # Checs that small_mask is preserved + a = array([1,2,3,4],mask=[0,0,0,0],shrink=False) + assert_equal(a.ravel()._mask, [0,0,0,0]) + + def test_reshape(self): + "Tests reshape" + x = arange(4) + x[0] = masked + y = x.reshape(2,2) + assert_equal(y.shape, (2,2,)) + assert_equal(y._mask.shape, (2,2,)) + assert_equal(x.shape, (4,)) + assert_equal(x._mask.shape, (4,)) + + def test_compressed(self): + "Tests compressed" + a = array([1,2,3,4],mask=[0,0,0,0]) + b = a.compressed() + assert_equal(b, a) + assert_equal(b._mask, nomask) + a[0] = masked + b = a.compressed() + assert_equal(b._data, [2,3,4]) + assert_equal(b._mask, nomask) + + def test_tolist(self): + "Tests to list" + x = array(numpy.arange(12)) + x[[1,-2]] = masked + xlist = x.tolist() + assert(xlist[1] is None) + assert(xlist[-2] is None) + # + x.shape = (3,4) + xlist = x.tolist() + # + assert_equal(xlist[0],[0,None,2,3]) + assert_equal(xlist[1],[4,5,6,7]) + assert_equal(xlist[2],[8,9,None,11]) + + def test_squeeze(self): + "Check squeeze" + data = masked_array([[1,2,3]]) + assert_equal(data.squeeze(), [1,2,3]) + data = masked_array([[1,2,3]], mask=[[1,1,1]]) + 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) + +#.............................................................................. + +############################################################################### +#------------------------------------------------------------------------------ +if __name__ == "__main__": + unittest.main() Added: trunk/scipy/sandbox/maskedarray/tests/test_extras.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_extras.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/tests/test_extras.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,328 @@ +# pylint: disable-msg=W0611, W0612, W0511 +"""Tests suite for MaskedArray. +Adapted from the original test_ma by Pierre Gerard-Marchant + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: test_extras.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + +import numpy as N +from scipy.testing import * + +import scipy.sandbox.maskedarray.testutils +from scipy.sandbox.maskedarray.testutils import * + +from scipy.sandbox.maskedarray.core import * +from scipy.sandbox.maskedarray.extras import * + +class TestAverage(TestCase): + "Several tests of average. Why so many ? Good point..." + def test_testAverage1(self): + "Test of average." + ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) + assert_equal(2.0, average(ott,axis=0)) + 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) + ott[:] = masked + assert_equal(average(ott,axis=0).mask, [True]) + ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) + ott = ott.reshape(2,2) + ott[:,1] = masked + assert_equal(average(ott,axis=0), [2.0, 0.0]) + assert_equal(average(ott,axis=1).mask[0], [True]) + assert_equal([2.,0.], average(ott, axis=0)) + result, wts = average(ott, axis=0, returned=1) + assert_equal(wts, [1., 0.]) + + def test_testAverage2(self): + "More tests of average." + w1 = [0,1,1,1,1,0] + w2 = [[0,1,1,1,1,0],[1,0,0,0,0,1]] + x = arange(6, dtype=float_) + assert_equal(average(x, axis=0), 2.5) + assert_equal(average(x, axis=0, weights=w1), 2.5) + y = array([arange(6, dtype=float_), 2.0*arange(6)]) + assert_equal(average(y, None), N.add.reduce(N.arange(6))*3./12.) + assert_equal(average(y, axis=0), N.arange(6) * 3./2.) + assert_equal(average(y, axis=1), [average(x,axis=0), average(x,axis=0) * 2.0]) + assert_equal(average(y, None, weights=w2), 20./6.) + assert_equal(average(y, axis=0, weights=w2), [0.,1.,2.,3.,4.,10.]) + assert_equal(average(y, axis=1), [average(x,axis=0), average(x,axis=0) * 2.0]) + m1 = zeros(6) + m2 = [0,0,1,1,0,0] + m3 = [[0,0,1,1,0,0],[0,1,1,1,1,0]] + m4 = ones(6) + m5 = [0, 1, 1, 1, 1, 1] + assert_equal(average(masked_array(x, m1),axis=0), 2.5) + assert_equal(average(masked_array(x, m2),axis=0), 2.5) + assert_equal(average(masked_array(x, m4),axis=0).mask, [True]) + assert_equal(average(masked_array(x, m5),axis=0), 0.0) + assert_equal(count(average(masked_array(x, m4),axis=0)), 0) + z = masked_array(y, m3) + assert_equal(average(z, None), 20./6.) + assert_equal(average(z, axis=0), [0.,1.,99.,99.,4.0, 7.5]) + assert_equal(average(z, axis=1), [2.5, 5.0]) + assert_equal(average(z,axis=0, weights=w2), [0.,1., 99., 99., 4.0, 10.0]) + + def test_testAverage3(self): + "Yet more tests of average!" + a = arange(6) + b = arange(6) * 3 + r1, w1 = average([[a,b],[b,a]], axis=1, returned=1) + assert_equal(shape(r1) , shape(w1)) + assert_equal(r1.shape , w1.shape) + r2, w2 = average(ones((2,2,3)), axis=0, weights=[3,1], returned=1) + assert_equal(shape(w2) , shape(r2)) + r2, w2 = average(ones((2,2,3)), returned=1) + assert_equal(shape(w2) , shape(r2)) + r2, w2 = average(ones((2,2,3)), weights=ones((2,2,3)), returned=1) + assert_equal(shape(w2), shape(r2)) + a2d = array([[1,2],[0,4]], float) + a2dm = masked_array(a2d, [[0,0],[1,0]]) + a2da = average(a2d, axis=0) + assert_equal(a2da, [0.5, 3.0]) + a2dma = average(a2dm, axis=0) + assert_equal(a2dma, [1.0, 3.0]) + a2dma = average(a2dm, axis=None) + assert_equal(a2dma, 7./3.) + a2dma = average(a2dm, axis=1) + assert_equal(a2dma, [1.5, 4.0]) + +class TestConcatenator(TestCase): + "Tests for mr_, the equivalent of r_ for masked arrays." + def test_1d(self): + "Tests mr_ on 1D arrays." + assert_array_equal(mr_[1,2,3,4,5,6],array([1,2,3,4,5,6])) + b = ones(5) + 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)) + 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]) + + def test_2d(self): + "Tests mr_ on 2D arrays." + a_1 = rand(5,5) + a_2 = rand(5,5) + m_1 = N.round_(rand(5,5),0) + m_2 = N.round_(rand(5,5),0) + 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)) + assert_array_equal(d[:,:5],b_1) + assert_array_equal(d[:,5:],b_2) + assert_array_equal(d.mask, N.r_['1',m_1,m_2]) + d = mr_[b_1,b_2] + assert(d.shape == (10,5)) + assert_array_equal(d[:5,:],b_1) + assert_array_equal(d[5:,:],b_2) + assert_array_equal(d.mask, N.r_[m_1,m_2]) + +class TestNotMasked(TestCase): + "Tests notmasked_edges and notmasked_contiguous." + def test_edges(self): + "Tests unmasked_edges" + a = masked_array(N.arange(24).reshape(3,8), + mask=[[0,0,0,0,1,1,1,0], + [1,1,1,1,1,1,1,1], + [0,0,0,0,0,0,1,0],]) + # + assert_equal(notmasked_edges(a, None), [0,23]) + # + tmp = notmasked_edges(a, 0) + assert_equal(tmp[0], (array([0,0,0,0,2,2,0]), array([0,1,2,3,4,5,7]))) + assert_equal(tmp[1], (array([2,2,2,2,2,2,2]), array([0,1,2,3,4,5,7]))) + # + tmp = notmasked_edges(a, 1) + assert_equal(tmp[0], (array([0,2,]), array([0,0]))) + assert_equal(tmp[1], (array([0,2,]), array([7,7]))) + + def test_contiguous(self): + "Tests notmasked_contiguous" + a = masked_array(N.arange(24).reshape(3,8), + mask=[[0,0,0,0,1,1,1,1], + [1,1,1,1,1,1,1,1], + [0,0,0,0,0,0,1,0],]) + tmp = notmasked_contiguous(a, None) + assert_equal(tmp[-1], slice(23,23,None)) + assert_equal(tmp[-2], slice(16,21,None)) + assert_equal(tmp[-3], slice(0,3,None)) + # + tmp = notmasked_contiguous(a, 0) + assert(len(tmp[-1]) == 1) + assert(tmp[-2] is None) + assert_equal(tmp[-3],tmp[-1]) + assert(len(tmp[0]) == 2) + # + tmp = notmasked_contiguous(a, 1) + assert_equal(tmp[0][-1], slice(0,3,None)) + assert(tmp[1] is None) + assert_equal(tmp[2][-1], slice(7,7,None)) + assert_equal(tmp[2][-2], slice(0,5,None)) + +class Test2DFunctions(TestCase): + "Tests 2D functions" + def test_compress2d(self): + "Tests compress2d" + x = array(N.arange(9).reshape(3,3), mask=[[1,0,0],[0,0,0],[0,0,0]]) + assert_equal(compress_rowcols(x), [[4,5],[7,8]] ) + assert_equal(compress_rowcols(x,0), [[3,4,5],[6,7,8]] ) + assert_equal(compress_rowcols(x,1), [[1,2],[4,5],[7,8]] ) + x = array(x._data, mask=[[0,0,0],[0,1,0],[0,0,0]]) + assert_equal(compress_rowcols(x), [[0,2],[6,8]] ) + assert_equal(compress_rowcols(x,0), [[0,1,2],[6,7,8]] ) + assert_equal(compress_rowcols(x,1), [[0,2],[3,5],[6,8]] ) + x = array(x._data, mask=[[1,0,0],[0,1,0],[0,0,0]]) + assert_equal(compress_rowcols(x), [[8]] ) + assert_equal(compress_rowcols(x,0), [[6,7,8]] ) + assert_equal(compress_rowcols(x,1,), [[2],[5],[8]] ) + x = array(x._data, mask=[[1,0,0],[0,1,0],[0,0,1]]) + assert_equal(compress_rowcols(x).size, 0 ) + assert_equal(compress_rowcols(x,0).size, 0 ) + assert_equal(compress_rowcols(x,1).size, 0 ) + # + def test_mask_rowcols(self): + "Tests mask_rowcols." + x = array(N.arange(9).reshape(3,3), mask=[[1,0,0],[0,0,0],[0,0,0]]) + assert_equal(mask_rowcols(x).mask, [[1,1,1],[1,0,0],[1,0,0]] ) + assert_equal(mask_rowcols(x,0).mask, [[1,1,1],[0,0,0],[0,0,0]] ) + assert_equal(mask_rowcols(x,1).mask, [[1,0,0],[1,0,0],[1,0,0]] ) + x = array(x._data, mask=[[0,0,0],[0,1,0],[0,0,0]]) + assert_equal(mask_rowcols(x).mask, [[0,1,0],[1,1,1],[0,1,0]] ) + assert_equal(mask_rowcols(x,0).mask, [[0,0,0],[1,1,1],[0,0,0]] ) + assert_equal(mask_rowcols(x,1).mask, [[0,1,0],[0,1,0],[0,1,0]] ) + x = array(x._data, mask=[[1,0,0],[0,1,0],[0,0,0]]) + assert_equal(mask_rowcols(x).mask, [[1,1,1],[1,1,1],[1,1,0]] ) + 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()) + assert(mask_rowcols(x,0).all()) + assert(mask_rowcols(x,1).all()) + # + def test_dot(self): + "Tests dot product" + n = N.arange(1,7) + # + m = [1,0,0,0,0,0] + a = masked_array(n, mask=m).reshape(2,3) + b = masked_array(n, mask=m).reshape(3,2) + c = dot(a,b,True) + assert_equal(c.mask, [[1,1],[1,0]]) + c = dot(b,a,True) + assert_equal(c.mask, [[1,1,1],[1,0,0],[1,0,0]]) + c = dot(a,b,False) + assert_equal(c, N.dot(a.filled(0), b.filled(0))) + c = dot(b,a,False) + assert_equal(c, N.dot(b.filled(0), a.filled(0))) + # + m = [0,0,0,0,0,1] + a = masked_array(n, mask=m).reshape(2,3) + b = masked_array(n, mask=m).reshape(3,2) + c = dot(a,b,True) + assert_equal(c.mask,[[0,1],[1,1]]) + c = dot(b,a,True) + assert_equal(c.mask, [[0,0,1],[0,0,1],[1,1,1]]) + c = dot(a,b,False) + assert_equal(c, N.dot(a.filled(0), b.filled(0))) + assert_equal(c, dot(a,b)) + c = dot(b,a,False) + assert_equal(c, N.dot(b.filled(0), a.filled(0))) + # + m = [0,0,0,0,0,0] + a = masked_array(n, mask=m).reshape(2,3) + b = masked_array(n, mask=m).reshape(3,2) + c = dot(a,b) + assert_equal(c.mask,nomask) + c = dot(b,a) + assert_equal(c.mask,nomask) + # + a = masked_array(n, mask=[1,0,0,0,0,0]).reshape(2,3) + b = masked_array(n, mask=[0,0,0,0,0,0]).reshape(3,2) + c = dot(a,b,True) + assert_equal(c.mask,[[1,1],[0,0]]) + c = dot(a,b,False) + assert_equal(c, N.dot(a.filled(0),b.filled(0))) + c = dot(b,a,True) + assert_equal(c.mask,[[1,0,0],[1,0,0],[1,0,0]]) + c = dot(b,a,False) + assert_equal(c, N.dot(b.filled(0),a.filled(0))) + # + a = masked_array(n, mask=[0,0,0,0,0,1]).reshape(2,3) + b = masked_array(n, mask=[0,0,0,0,0,0]).reshape(3,2) + c = dot(a,b,True) + assert_equal(c.mask,[[0,0],[1,1]]) + c = dot(a,b) + assert_equal(c, N.dot(a.filled(0),b.filled(0))) + c = dot(b,a,True) + assert_equal(c.mask,[[0,0,1],[0,0,1],[0,0,1]]) + c = dot(b,a,False) + assert_equal(c, N.dot(b.filled(0), a.filled(0))) + # + a = masked_array(n, mask=[0,0,0,0,0,1]).reshape(2,3) + b = masked_array(n, mask=[0,0,1,0,0,0]).reshape(3,2) + c = dot(a,b,True) + assert_equal(c.mask,[[1,0],[1,1]]) + c = dot(a,b,False) + assert_equal(c, N.dot(a.filled(0),b.filled(0))) + c = dot(b,a,True) + assert_equal(c.mask,[[0,0,1],[1,1,1],[0,0,1]]) + c = dot(b,a,False) + assert_equal(c, N.dot(b.filled(0),a.filled(0))) + + def test_mediff1d(self): + "Tests mediff1d" + x = masked_array(N.arange(5), mask=[1,0,0,0,1]) + difx_d = (x._data[1:]-x._data[:-1]) + difx_m = (x._mask[1:]-x._mask[:-1]) + dx = mediff1d(x) + assert_equal(dx._data, difx_d) + assert_equal(dx._mask, difx_m) + # + dx = mediff1d(x, to_begin=masked) + assert_equal(dx._data, N.r_[0,difx_d]) + assert_equal(dx._mask, N.r_[1,difx_m]) + dx = mediff1d(x, to_begin=[1,2,3]) + assert_equal(dx._data, N.r_[[1,2,3],difx_d]) + assert_equal(dx._mask, N.r_[[0,0,0],difx_m]) + # + dx = mediff1d(x, to_end=masked) + assert_equal(dx._data, N.r_[difx_d,0]) + assert_equal(dx._mask, N.r_[difx_m,1]) + dx = mediff1d(x, to_end=[1,2,3]) + assert_equal(dx._data, N.r_[difx_d,[1,2,3]]) + assert_equal(dx._mask, N.r_[difx_m,[0,0,0]]) + # + dx = mediff1d(x, to_end=masked, to_begin=masked) + assert_equal(dx._data, N.r_[0,difx_d,0]) + assert_equal(dx._mask, N.r_[1,difx_m,1]) + dx = mediff1d(x, to_end=[1,2,3], to_begin=masked) + assert_equal(dx._data, N.r_[0,difx_d,[1,2,3]]) + assert_equal(dx._mask, N.r_[1,difx_m,[0,0,0]]) + # + dx = mediff1d(x._data, to_end=masked, to_begin=masked) + assert_equal(dx._data, N.r_[0,difx_d,0]) + assert_equal(dx._mask, N.r_[1,0,0,0,0,1]) + +class TestApplyAlongAxis(TestCase): + "Tests 2D functions" + def test_3d(self): + a = arange(12.).reshape(2,2,3) + def myfunc(b): + return b[1] + xa = apply_along_axis(myfunc,2,a) + assert_equal(xa,[[1,4],[7,10]]) + +############################################################################### +#------------------------------------------------------------------------------ +if __name__ == "__main__": + unittest.main() Added: trunk/scipy/sandbox/maskedarray/tests/test_morestats.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_morestats.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/tests/test_morestats.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,109 @@ +# pylint: disable-msg=W0611, W0612, W0511,R0201 +"""Tests suite for maskedArray statistics. + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: test_morestats.py 317 2007-10-04 19:31:14Z backtopop $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: backtopop $)" +__version__ = '1.0' +__revision__ = "$Revision: 317 $" +__date__ = '$Date: 2007-10-04 15:31:14 -0400 (Thu, 04 Oct 2007) $' + +import numpy +from scipy.testing import * +from scipy.sandbox.maskedarray import masked, masked_array +import scipy.sandbox.maskedarray.mstats +from scipy.sandbox.maskedarray.mstats import * +from scipy.sandbox.maskedarray.morestats import * +from scipy.sandbox.maskedarray.testutils import * + + +class TestMisc(TestCase): + # + def __init__(self, *args, **kwargs): + TestCase.__init__(self, *args, **kwargs) + # + def test_mjci(self): + "Tests the Marits-Jarrett estimator" + data = masked_array([ 77, 87, 88,114,151,210,219,246,253,262, + 296,299,306,376,428,515,666,1310,2611]) + assert_almost_equal(mjci(data),[55.76819,45.84028,198.8788],5) + # + def test_trimmedmeanci(self): + "Tests the confidence intervals of the trimmed mean." + data = masked_array([545,555,558,572,575,576,578,580, + 594,605,635,651,653,661,666]) + assert_almost_equal(trimmed_mean(data,0.2), 596.2, 1) + assert_equal(numpy.round(trimmed_mean_ci(data,0.2),1), [561.8, 630.6]) + +#.............................................................................. +class TestRanking(TestCase): + # + def __init__(self, *args, **kwargs): + TestCase.__init__(self, *args, **kwargs) + # + def test_ranking(self): + x = masked_array([0,1,1,1,2,3,4,5,5,6,]) + assert_almost_equal(rank_data(x),[1,3,3,3,5,6,7,8.5,8.5,10]) + x[[3,4]] = masked + assert_almost_equal(rank_data(x),[1,2.5,2.5,0,0,4,5,6.5,6.5,8]) + assert_almost_equal(rank_data(x,use_missing=True), + [1,2.5,2.5,4.5,4.5,4,5,6.5,6.5,8]) + x = masked_array([0,1,5,1,2,4,3,5,1,6,]) + assert_almost_equal(rank_data(x),[1,3,8.5,3,5,7,6,8.5,3,10]) + x = masked_array([[0,1,1,1,2], [3,4,5,5,6,]]) + assert_almost_equal(rank_data(x),[[1,3,3,3,5],[6,7,8.5,8.5,10]]) + assert_almost_equal(rank_data(x,axis=1),[[1,3,3,3,5],[1,2,3.5,3.5,5]]) + assert_almost_equal(rank_data(x,axis=0),[[1,1,1,1,1],[2,2,2,2,2,]]) + +#.............................................................................. +class TestQuantiles(TestCase): + # + def __init__(self, *args, **kwargs): + TestCase.__init__(self, *args, **kwargs) + # + def test_hdquantiles(self): + data = [0.706560797,0.727229578,0.990399276,0.927065621,0.158953014, + 0.887764025,0.239407086,0.349638551,0.972791145,0.149789972, + 0.936947700,0.132359948,0.046041972,0.641675031,0.945530547, + 0.224218684,0.771450991,0.820257774,0.336458052,0.589113496, + 0.509736129,0.696838829,0.491323573,0.622767425,0.775189248, + 0.641461450,0.118455200,0.773029450,0.319280007,0.752229111, + 0.047841438,0.466295911,0.583850781,0.840581845,0.550086491, + 0.466470062,0.504765074,0.226855960,0.362641207,0.891620942, + 0.127898691,0.490094097,0.044882048,0.041441695,0.317976349, + 0.504135618,0.567353033,0.434617473,0.636243375,0.231803616, + 0.230154113,0.160011327,0.819464108,0.854706985,0.438809221, + 0.487427267,0.786907310,0.408367937,0.405534192,0.250444460, + 0.995309248,0.144389588,0.739947527,0.953543606,0.680051621, + 0.388382017,0.863530727,0.006514031,0.118007779,0.924024803, + 0.384236354,0.893687694,0.626534881,0.473051932,0.750134705, + 0.241843555,0.432947602,0.689538104,0.136934797,0.150206859, + 0.474335206,0.907775349,0.525869295,0.189184225,0.854284286, + 0.831089744,0.251637345,0.587038213,0.254475554,0.237781276, + 0.827928620,0.480283781,0.594514455,0.213641488,0.024194386, + 0.536668589,0.699497811,0.892804071,0.093835427,0.731107772] + # + assert_almost_equal(hdquantiles(data,[0., 1.]), + [0.006514031, 0.995309248]) + hdq = hdquantiles(data,[0.25, 0.5, 0.75]) + assert_almost_equal(hdq, [0.253210762, 0.512847491, 0.762232442,]) + hdq = hdquantiles_sd(data,[0.25, 0.5, 0.75]) + assert_almost_equal(hdq, [0.03786954, 0.03805389, 0.03800152,], 4) + # + data = numpy.array(data).reshape(10,10) + hdq = hdquantiles(data,[0.25,0.5,0.75],axis=0) + assert_almost_equal(hdq[:,0], hdquantiles(data[:,0],[0.25,0.5,0.75])) + assert_almost_equal(hdq[:,-1], hdquantiles(data[:,-1],[0.25,0.5,0.75])) + hdq = hdquantiles(data,[0.25,0.5,0.75],axis=0,var=True) + assert_almost_equal(hdq[...,0], + hdquantiles(data[:,0],[0.25,0.5,0.75],var=True)) + assert_almost_equal(hdq[...,-1], + hdquantiles(data[:,-1],[0.25,0.5,0.75], var=True)) + + +############################################################################### +#------------------------------------------------------------------------------ +if __name__ == "__main__": + unittest.main() Added: trunk/scipy/sandbox/maskedarray/tests/test_mrecords.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_mrecords.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/tests/test_mrecords.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,176 @@ +# pylint: disable-msg=W0611, W0612, W0511,R0201 +"""Tests suite for mrecarray. + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: test_mrecords.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + +import types + +import numpy as N +import numpy.core.fromnumeric as fromnumeric +from scipy.testing import * + +from scipy.sandbox.maskedarray.testutils import * +from scipy.sandbox import maskedarray +from scipy.sandbox.maskedarray import masked_array, masked, nomask + +#import maskedarray.mrecords +#from maskedarray.mrecords import mrecarray, fromarrays, fromtextfile, fromrecords +from scipy.sandbox.maskedarray.mrecords import MaskedRecords, \ + fromarrays, fromtextfile, fromrecords, addfield + +#.............................................................................. +class TestMRecords(TestCase): + "Base test class for MaskedArrays." + def __init__(self, *args, **kwds): + TestCase.__init__(self, *args, **kwds) + self.setup() + + def setup(self): + "Generic setup" + d = N.arange(5) + m = maskedarray.make_mask([1,0,0,1,1]) + base_d = N.r_[d,d[::-1]].reshape(2,-1).T + base_m = N.r_[[m, m[::-1]]].T + base = masked_array(base_d, mask=base_m) + mrecord = fromarrays(base.T, dtype=[('a',N.float_),('b',N.float_)]) + self.data = [d, m, mrecord] + + def test_get(self): + "Tests fields retrieval" + [d, m, mrec] = self.data + mrec = mrec.copy() + assert_equal(mrec.a, masked_array(d,mask=m)) + assert_equal(mrec.b, masked_array(d[::-1],mask=m[::-1])) + assert((mrec._fieldmask == N.core.records.fromarrays([m, m[::-1]], dtype=mrec._fieldmask.dtype)).all()) + assert_equal(mrec._mask, N.r_[[m,m[::-1]]].all(0)) + assert_equal(mrec.a[1], mrec[1].a) + # + assert(isinstance(mrec[:2], MaskedRecords)) + assert_equal(mrec[:2]['a'], d[:2]) + + def test_set(self): + "Tests setting fields/attributes." + [d, m, mrecord] = self.data + mrecord.a._data[:] = 5 + assert_equal(mrecord['a']._data, [5,5,5,5,5]) + mrecord.a = 1 + assert_equal(mrecord['a']._data, [1]*5) + assert_equal(getmaskarray(mrecord['a']), [0]*5) + mrecord.b = masked + assert_equal(mrecord.b.mask, [1]*5) + assert_equal(getmaskarray(mrecord['b']), [1]*5) + mrecord._mask = masked + assert_equal(getmaskarray(mrecord['b']), [1]*5) + assert_equal(mrecord['a']._mask, mrecord['b']._mask) + mrecord._mask = nomask + assert_equal(getmaskarray(mrecord['b']), [0]*5) + assert_equal(mrecord['a']._mask, mrecord['b']._mask) + # + def test_setfields(self): + "Tests setting fields." + [d, m, mrecord] = self.data + mrecord.a[3:] = 5 + assert_equal(mrecord.a, [0,1,2,5,5]) + assert_equal(mrecord.a._mask, [1,0,0,0,0]) + # + mrecord.b[3:] = masked + assert_equal(mrecord.b, [4,3,2,1,0]) + assert_equal(mrecord.b._mask, [1,1,0,1,1]) + + def test_setslices(self): + "Tests setting slices." + [d, m, mrec] = self.data + mrec[:2] = 5 + assert_equal(mrec.a._data, [5,5,2,3,4]) + assert_equal(mrec.b._data, [5,5,2,1,0]) + assert_equal(mrec.a._mask, [0,0,0,1,1]) + assert_equal(mrec.b._mask, [0,0,0,0,1]) + # + mrec[:2] = masked + assert_equal(mrec._mask, [1,1,0,0,1]) + mrec[-2] = masked + assert_equal(mrec._mask, [1,1,0,1,1]) + # + def test_setslices_hardmask(self): + "Tests setting slices w/ hardmask." + [d, m, mrec] = self.data + mrec.harden_mask() + mrec[-2:] = 5 + assert_equal(mrec.a._data, [0,1,2,3,4]) + assert_equal(mrec.b._data, [4,3,2,5,0]) + assert_equal(mrec.a._mask, [1,0,0,1,1]) + assert_equal(mrec.b._mask, [1,1,0,0,1]) + + def test_hardmask(self): + "Test hardmask" + [d, m, mrec] = self.data + mrec = mrec.copy() + mrec.harden_mask() + assert(mrec._hardmask) + mrec._mask = nomask + assert_equal(mrec._mask, N.r_[[m,m[::-1]]].all(0)) + mrec.soften_mask() + assert(not mrec._hardmask) + mrec._mask = nomask + assert(mrec['b']._mask is nomask) + assert_equal(mrec['a']._mask,mrec['b']._mask) + + def test_fromrecords(self): + "Test from recarray." + [d, m, mrec] = self.data + nrec = N.core.records.fromarrays(N.r_[[d,d[::-1]]], + dtype=[('a',N.float_),('b',N.float_)]) + #.................... + mrecfr = fromrecords(nrec) + assert_equal(mrecfr.a, mrec.a) + assert_equal(mrecfr.dtype, mrec.dtype) + #.................... + tmp = mrec[::-1] #.tolist() + mrecfr = fromrecords(tmp) + assert_equal(mrecfr.a, mrec.a[::-1]) + #.................... + mrecfr = fromrecords(nrec.tolist(), names=nrec.dtype.names) + assert_equal(mrecfr.a, mrec.a) + assert_equal(mrecfr.dtype, mrec.dtype) + + def test_fromtextfile(self): + "Tests reading from a text file." + fcontent = """# +'One (S)','Two (I)','Three (F)','Four (M)','Five (-)','Six (C)' +'strings',1,1.0,'mixed column',,1 +'with embedded "double quotes"',2,2.0,1.0,,1 +'strings',3,3.0E5,3,,1 +'strings',4,-1e-10,,,1 +""" + import os + from datetime import datetime + fname = 'tmp%s' % datetime.now().strftime("%y%m%d%H%M%S%s") + f = open(fname, 'w') + f.write(fcontent) + f.close() + mrectxt = fromtextfile(fname,delimitor=',',varnames='ABCDEFG') + os.unlink(fname) + # + assert(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]) + + def test_addfield(self): + "Tests addfield" + [d, m, mrec] = self.data + mrec = addfield(mrec, masked_array(d+10, mask=m[::-1])) + assert_equal(mrec.f2, d+10) + assert_equal(mrec.f2._mask, m[::-1]) + +############################################################################### +#------------------------------------------------------------------------------ +if __name__ == "__main__": + unittest.main() Added: trunk/scipy/sandbox/maskedarray/tests/test_mstats.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_mstats.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/tests/test_mstats.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,173 @@ +# pylint: disable-msg=W0611, W0612, W0511,R0201 +"""Tests suite for maskedArray statistics. + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: test_mstats.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + +import numpy + +from scipy.testing import * +from scipy.sandbox import maskedarray +from scipy.sandbox.maskedarray import masked, masked_array + +from scipy.sandbox.maskedarray.testutils import * +from scipy.sandbox.maskedarray.mstats import * + +#.............................................................................. +class TestQuantiles(TestCase): + "Base test class for MaskedArrays." + def __init__(self, *args, **kwds): + TestCase.__init__(self, *args, **kwds) + self.a = maskedarray.arange(1,101) + # + def test_1d_nomask(self): + "Test quantiles 1D - w/o mask." + a = self.a + assert_almost_equal(mquantiles(a, alphap=1., betap=1.), + [25.75, 50.5, 75.25]) + assert_almost_equal(mquantiles(a, alphap=0, betap=1.), + [25., 50., 75.]) + assert_almost_equal(mquantiles(a, alphap=0.5, betap=0.5), + [25.5, 50.5, 75.5]) + assert_almost_equal(mquantiles(a, alphap=0., betap=0.), + [25.25, 50.5, 75.75]) + assert_almost_equal(mquantiles(a, alphap=1./3, betap=1./3), + [25.41666667, 50.5, 75.5833333]) + assert_almost_equal(mquantiles(a, alphap=3./8, betap=3./8), + [25.4375, 50.5, 75.5625]) + assert_almost_equal(mquantiles(a), [25.45, 50.5, 75.55])# + # + def test_1d_mask(self): + "Test quantiles 1D - w/ mask." + a = self.a + a[1::2] = masked + assert_almost_equal(mquantiles(a, alphap=1., betap=1.), + [25.5, 50.0, 74.5]) + assert_almost_equal(mquantiles(a, alphap=0, betap=1.), + [24., 49., 74.]) + assert_almost_equal(mquantiles(a, alphap=0.5, betap=0.5), + [25., 50., 75.]) + assert_almost_equal(mquantiles(a, alphap=0., betap=0.), + [24.5, 50.0, 75.5]) + assert_almost_equal(mquantiles(a, alphap=1./3, betap=1./3), + [24.833333, 50.0, 75.166666]) + assert_almost_equal(mquantiles(a, alphap=3./8, betap=3./8), + [24.875, 50., 75.125]) + assert_almost_equal(mquantiles(a), [24.9, 50., 75.1]) + # + def test_2d_nomask(self): + "Test quantiles 2D - w/o mask." + a = self.a + b = maskedarray.resize(a, (100,100)) + assert_almost_equal(mquantiles(b), [25.45, 50.5, 75.55]) + assert_almost_equal(mquantiles(b, axis=0), maskedarray.resize(a,(3,100))) + assert_almost_equal(mquantiles(b, axis=1), + maskedarray.resize([25.45, 50.5, 75.55], (100,3))) + # + def test_2d_mask(self): + "Test quantiles 2D - w/ mask." + a = self.a + a[1::2] = masked + b = maskedarray.resize(a, (100,100)) + assert_almost_equal(mquantiles(b), [25., 50., 75.]) + assert_almost_equal(mquantiles(b, axis=0), maskedarray.resize(a,(3,100))) + assert_almost_equal(mquantiles(b, axis=1), + maskedarray.resize([24.9, 50., 75.1], (100,3))) + +class TestMedian(TestCase): + def __init__(self, *args, **kwds): + TestCase.__init__(self, *args, **kwds) + + def test_2d(self): + "Tests median w/ 2D" + (n,p) = (101,30) + x = masked_array(numpy.linspace(-1.,1.,n),) + x[:10] = x[-10:] = masked + z = masked_array(numpy.empty((n,p), dtype=numpy.float_)) + z[:,0] = x[:] + idx = numpy.arange(len(x)) + for i in range(1,p): + numpy.random.shuffle(idx) + z[:,i] = x[idx] + assert_equal(mmedian(z[:,0]), 0) + assert_equal(mmedian(z), numpy.zeros((p,))) + + def test_3d(self): + "Tests median w/ 3D" + x = maskedarray.arange(24).reshape(3,4,2) + x[x%3==0] = masked + assert_equal(mmedian(x,0), [[12,9],[6,15],[12,9],[18,15]]) + x.shape = (4,3,2) + assert_equal(mmedian(x,0),[[99,10],[11,99],[13,14]]) + x = maskedarray.arange(24).reshape(4,3,2) + x[x%5==0] = masked + assert_equal(mmedian(x,0), [[12,10],[8,9],[16,17]]) + +#.............................................................................. +class TestTrimming(TestCase): + # + def __init__(self, *args, **kwds): + TestCase.__init__(self, *args, **kwds) + # + def test_trim(self): + "Tests trimming." + x = maskedarray.arange(100) + assert_equal(trim_both(x).count(), 60) + assert_equal(trim_tail(x,tail='r').count(), 80) + x[50:70] = masked + trimx = trim_both(x) + assert_equal(trimx.count(), 48) + assert_equal(trimx._mask, [1]*16 + [0]*34 + [1]*20 + [0]*14 + [1]*16) + x._mask = nomask + x.shape = (10,10) + assert_equal(trim_both(x).count(), 60) + assert_equal(trim_tail(x).count(), 80) + # + def test_trimmedmean(self): + "Tests the trimmed mean." + data = masked_array([ 77, 87, 88,114,151,210,219,246,253,262, + 296,299,306,376,428,515,666,1310,2611]) + assert_almost_equal(trimmed_mean(data,0.1), 343, 0) + assert_almost_equal(trimmed_mean(data,0.2), 283, 0) + # + def test_trimmed_stde(self): + "Tests the trimmed mean standard error." + data = masked_array([ 77, 87, 88,114,151,210,219,246,253,262, + 296,299,306,376,428,515,666,1310,2611]) + assert_almost_equal(trimmed_stde(data,0.2), 56.1, 1) + # + def test_winsorization(self): + "Tests the Winsorization of the data." + data = masked_array([ 77, 87, 88,114,151,210,219,246,253,262, + 296,299,306,376,428,515,666,1310,2611]) + assert_almost_equal(winsorize(data).varu(), 21551.4, 1) + data[5] = masked + winsorized = winsorize(data) + assert_equal(winsorized.mask, data.mask) +#.............................................................................. + +class TestMisc(TestCase): + def __init__(self, *args, **kwds): + TestCase.__init__(self, *args, **kwds) + + def test_cov(self): + "Tests the cov function." + x = masked_array([[1,2,3],[4,5,6]], mask=[[1,0,0],[0,0,0]]) + c = cov(x[0]) + assert_equal(c, (x[0].anom()**2).sum()) + c = cov(x[1]) + assert_equal(c, (x[1].anom()**2).sum()/2.) + c = cov(x) + assert_equal(c[1,0], (x[0].anom()*x[1].anom()).sum()) + + +############################################################################### +#------------------------------------------------------------------------------ +if __name__ == "__main__": + unittest.main() Added: trunk/scipy/sandbox/maskedarray/tests/test_subclassing.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_subclassing.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/tests/test_subclassing.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,182 @@ +# pylint: disable-msg=W0611, W0612, W0511,R0201 +"""Tests suite for MaskedArray & subclassing. + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: test_subclassing.py 3778 2008-01-04 01:29:56Z matthew.brett at gmail.com $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: matthew.brett at gmail.com $)" +__version__ = '1.0' +__revision__ = "$Revision: 3778 $" +__date__ = '$Date: 2008-01-03 17:29:56 -0800 (Thu, 03 Jan 2008) $' + +import numpy as N +import numpy.core.numeric as numeric + +from scipy.testing import * + +from scipy.sandbox.maskedarray.testutils import * + +import scipy.sandbox.maskedarray.core as coremodule +from scipy.sandbox.maskedarray.core import * + + +class SubArray(N.ndarray): + """Defines a generic N.ndarray subclass, that stores some metadata + in the dictionary `info`.""" + def __new__(cls,arr,info={}): + x = N.asanyarray(arr).view(cls) + x.info = info + return x + def __array_finalize__(self, obj): + self.info = getattr(obj,'info',{}) + return + def __add__(self, other): + result = N.ndarray.__add__(self, other) + result.info.update({'added':result.info.pop('added',0)+1}) + return result +subarray = SubArray + +class MSubArray(SubArray,MaskedArray): + def __new__(cls, data, info=None, mask=nomask): + subarr = SubArray(data, info) + _data = MaskedArray.__new__(cls, data=subarr, mask=mask) + _data.info = subarr.info + return _data + def __array_finalize__(self,obj): + MaskedArray.__array_finalize__(self,obj) + SubArray.__array_finalize__(self, obj) + return + def _get_series(self): + _view = self.view(MaskedArray) + _view._sharedmask = False + return _view + _series = property(fget=_get_series) +msubarray = MSubArray + +class MMatrix(MaskedArray, N.matrix,): + def __new__(cls, data, mask=nomask): + mat = N.matrix(data) + _data = MaskedArray.__new__(cls, data=mat, mask=mask) + return _data + def __array_finalize__(self,obj): + N.matrix.__array_finalize__(self, obj) + MaskedArray.__array_finalize__(self,obj) + return + def _get_series(self): + _view = self.view(MaskedArray) + _view._sharedmask = False + return _view + _series = property(fget=_get_series) +mmatrix = MMatrix + + + +class TestSubclassing(TestCase): + """Test suite for masked subclasses of ndarray.""" + + def test_data_subclassing(self): + "Tests whether the subclass is kept." + x = N.arange(5) + m = [0,0,1,0,0] + xsub = SubArray(x) + xmsub = masked_array(xsub, mask=m) + assert isinstance(xmsub, MaskedArray) + assert_equal(xmsub._data, xsub) + assert isinstance(xmsub._data, SubArray) + + def test_maskedarray_subclassing(self): + "Tests subclassing MaskedArray" + x = N.arange(5) + mx = mmatrix(x,mask=[0,1,0,0,0]) + assert isinstance(mx._data, N.matrix) + "Tests masked_unary_operation" + assert isinstance(add(mx,mx), mmatrix) + assert isinstance(add(mx,x), mmatrix) + assert_equal(add(mx,x), mx+x) + assert isinstance(add(mx,mx)._data, N.matrix) + assert isinstance(add.outer(mx,mx), mmatrix) + "Tests masked_binary_operation" + assert isinstance(hypot(mx,mx), mmatrix) + assert isinstance(hypot(mx,x), mmatrix) + + def test_attributepropagation(self): + x = array(arange(5), mask=[0]+[1]*4) + my = masked_array(subarray(x)) + ym = msubarray(x) + # + z = (my+1) + assert isinstance(z,MaskedArray) + assert not isinstance(z, MSubArray) + assert 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 + # + ym._set_mask([1,0,0,0,1]) + assert_equal(ym._mask, [1,0,0,0,1]) + ym._series._set_mask([0,0,0,0,1]) + assert_equal(ym._mask, [0,0,0,0,1]) + # + xsub = subarray(x, info={'name':'x'}) + mxsub = masked_array(xsub) + assert hasattr(mxsub, 'info') + assert_equal(mxsub.info, xsub.info) + + def test_subclasspreservation(self): + "Checks that masked_array(...,subok=True) preserves the class." + x = N.arange(5) + m = [0,0,1,0,0] + xinfo = [(i,j) for (i,j) in zip(x,m)] + xsub = MSubArray(x, mask=m, info={'xsub':xinfo}) + # + mxsub = masked_array(xsub, subok=False) + assert not isinstance(mxsub, MSubArray) + assert isinstance(mxsub, MaskedArray) + assert_equal(mxsub._mask, m) + # + mxsub = asarray(xsub) + assert not isinstance(mxsub, MSubArray) + assert isinstance(mxsub, MaskedArray) + assert_equal(mxsub._mask, m) + # + mxsub = masked_array(xsub, subok=True) + assert isinstance(mxsub, MSubArray) + assert_equal(mxsub.info, xsub.info) + assert_equal(mxsub._mask, xsub._mask) + # + mxsub = asanyarray(xsub) + assert isinstance(mxsub, MSubArray) + assert_equal(mxsub.info, xsub.info) + assert_equal(mxsub._mask, m) + + +################################################################################ +if __name__ == '__main__': + unittest.main() + # + if 0: + x = array(arange(5), mask=[0]+[1]*4) + my = masked_array(subarray(x)) + ym = msubarray(x) + # + z = (my+1) + assert isinstance(z,MaskedArray) + assert not isinstance(z, MSubArray) + assert 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 + # + ym._set_mask([1,0,0,0,1]) + assert_equal(ym._mask, [1,0,0,0,1]) + ym._series._set_mask([0,0,0,0,1]) + assert_equal(ym._mask, [0,0,0,0,1]) Added: trunk/scipy/sandbox/maskedarray/testutils.py =================================================================== --- trunk/scipy/sandbox/maskedarray/testutils.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/testutils.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,220 @@ +"""Miscellaneous functions for testing masked arrays and subclasses + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu +:version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $ +""" +__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" +__version__ = "1.0" +__revision__ = "$Revision: 3529 $" +__date__ = "$Date: 2007-11-13 00:01:14 -0800 (Tue, 13 Nov 2007) $" + + +import numpy as N +from numpy.core import ndarray +from numpy.core.numerictypes import float_ +import numpy.core.umath as umath +from numpy.testing import NumpyTest, NumpyTestCase +from numpy.testing.utils import build_err_msg, rand + +import core +from core import mask_or, getmask, getmaskarray, masked_array, nomask, masked +from core import filled, equal, less + +#------------------------------------------------------------------------------ +def approx (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8): + """Returns true if all components of a and b are equal subject to given tolerances. + +If fill_value is True, masked values considered equal. Otherwise, masked values +are considered unequal. +The relative error rtol should be positive and << 1.0 +The absolute error atol comes into play for those elements of b that are very +small or zero; it says how small a must be also. + """ + m = mask_or(getmask(a), getmask(b)) + d1 = filled(a) + d2 = filled(b) + if d1.dtype.char == "O" or d2.dtype.char == "O": + return N.equal(d1,d2).ravel() + x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_) + y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_) + d = N.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y)) + return d.ravel() +#................................................ +def _assert_equal_on_sequences(actual, desired, err_msg=''): + "Asserts the equality of two non-array sequences." + assert_equal(len(actual),len(desired),err_msg) + for k in range(len(desired)): + assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg)) + return + +def assert_equal_records(a,b): + """Asserts that two records are equal. Pretty crude for now.""" + assert_equal(a.dtype, b.dtype) + for f in a.dtype.names: + (af, bf) = (getattr(a,f), getattr(b,f)) + if not (af is masked) and not (bf is masked): + assert_equal(getattr(a,f), getattr(b,f)) + return + +def assert_equal(actual,desired,err_msg=''): + """Asserts that two items are equal. + """ + # Case #1: dictionary ..... + if isinstance(desired, dict): + assert isinstance(actual, dict), repr(type(actual)) + assert_equal(len(actual),len(desired),err_msg) + for k,i in desired.items(): + assert k in actual, repr(k) + assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) + return + # Case #2: lists ..... + if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)): + 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 + return + # Case #4. arrays or equivalent + if ((actual is masked) and not (desired is masked)) or \ + ((desired is masked) and not (actual is masked)): + msg = build_err_msg([actual, desired], err_msg, header='', names=('x', 'y')) + raise ValueError(msg) + actual = N.array(actual, copy=False, subok=True) + desired = N.array(desired, copy=False, subok=True) + if actual.dtype.char in "OS" and desired.dtype.char in "OS": + return _assert_equal_on_sequences(actual.tolist(), + desired.tolist(), + err_msg='') + return assert_array_equal(actual, desired, err_msg) +#............................. +def fail_if_equal(actual,desired,err_msg='',): + """Raises an assertion error if two items are equal. + """ + if isinstance(desired, dict): + assert isinstance(actual, dict), repr(type(actual)) + fail_if_equal(len(actual),len(desired),err_msg) + for k,i in desired.items(): + assert k in actual, 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)): + fail_if_equal(len(actual),len(desired),err_msg) + for k in range(len(desired)): + fail_if_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg)) + return + if isinstance(actual, N.ndarray) or isinstance(desired, N.ndarray): + return fail_if_array_equal(actual, desired, err_msg) + msg = build_err_msg([actual, desired], err_msg) + assert desired != actual, msg +assert_not_equal = fail_if_equal +#............................ +def assert_almost_equal(actual,desired,decimal=7,err_msg=''): + """Asserts that two items are almost equal. + The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal) + """ + if isinstance(actual, N.ndarray) or isinstance(desired, N.ndarray): + return assert_array_almost_equal(actual, desired, decimal, err_msg) + msg = build_err_msg([actual, desired], err_msg) + assert round(abs(desired - actual),decimal) == 0, msg +#............................ +def assert_array_compare(comparison, x, y, err_msg='', header='', + fill_value=True): + """Asserts that a comparison relation between two masked arrays is satisfied + elementwise.""" + xf = filled(x) + yf = filled(y) + m = mask_or(getmask(x), getmask(y)) + + x = masked_array(xf, copy=False, subok=False, mask=m).filled(fill_value) + y = masked_array(yf, copy=False, subok=False, mask=m).filled(fill_value) + + if ((x is masked) and not (y is masked)) or \ + ((y is masked) and not (x is masked)): + msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y')) + raise ValueError(msg) + + if (x.dtype.char != "O") and (x.dtype.char != "S"): + x = x.astype(float_) + if isinstance(x, N.ndarray) and x.size > 1: + x[N.isnan(x)] = 0 + elif N.isnan(x): + x = 0 + if (y.dtype.char != "O") and (y.dtype.char != "S"): + y = y.astype(float_) + if isinstance(y, N.ndarray) and y.size > 1: + y[N.isnan(y)] = 0 + elif N.isnan(y): + y = 0 + try: + cond = (x.shape==() or y.shape==()) or x.shape == y.shape + if not cond: + msg = build_err_msg([x, y], + err_msg + + '\n(shapes %s, %s mismatch)' % (x.shape, + y.shape), + header=header, + names=('x', 'y')) + assert cond, msg + val = comparison(x,y) + if m is not nomask and fill_value: + val = masked_array(val, mask=m, copy=False) + if isinstance(val, bool): + cond = val + reduced = [0] + else: + reduced = val.ravel() + cond = reduced.all() + reduced = reduced.tolist() + if not cond: + match = 100-100.0*reduced.count(1)/len(reduced) + msg = build_err_msg([x, y], + err_msg + + '\n(mismatch %s%%)' % (match,), + header=header, + names=('x', 'y')) + assert cond, msg + except ValueError: + msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y')) + raise ValueError(msg) +#............................ +def assert_array_equal(x, y, err_msg=''): + """Checks the elementwise equality of two masked arrays.""" + assert_array_compare(equal, x, y, err_msg=err_msg, + header='Arrays are not equal') +##............................ +def fail_if_array_equal(x, y, err_msg=''): + "Raises an assertion error if two masked arrays are not equal (elementwise)." + def compare(x,y): + + return (not N.alltrue(approx(x, y))) + assert_array_compare(compare, x, y, err_msg=err_msg, + header='Arrays are not equal') +#............................ +def assert_array_almost_equal(x, y, decimal=6, err_msg=''): + """Checks the elementwise equality of two masked arrays, up to a given + number of decimals.""" + def compare(x, y): + "Returns the result of the loose comparison between x and y)." + return approx(x,y, rtol=10.**-decimal) + assert_array_compare(compare, x, y, err_msg=err_msg, + header='Arrays are not almost equal') +#............................ +def assert_array_less(x, y, err_msg=''): + "Checks that x is smaller than y elementwise." + assert_array_compare(less, x, y, err_msg=err_msg, + header='Arrays are not less-ordered') +#............................ +assert_close = assert_almost_equal +#............................ +def assert_mask_equal(m1, m2): + """Asserts the equality of two masks.""" + if m1 is nomask: + assert(m2 is nomask) + if m2 is nomask: + assert(m1 is nomask) + assert_array_equal(m1, m2) + +if __name__ == '__main__': + a = 12 + assert_equal(a, masked) Added: trunk/scipy/sandbox/maskedarray/timer_comparison.py =================================================================== --- trunk/scipy/sandbox/maskedarray/timer_comparison.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/timer_comparison.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,461 @@ + +import timeit + +import numpy +from numpy import int_, float_, bool_ +import numpy.core.fromnumeric as fromnumeric + +from numpy.testing.utils import build_err_msg, rand + + +numpy.seterr(all='ignore') + +pi = numpy.pi + +class moduletester: + #----------------------------------- + def __init__(self, module): + self.module = module + self.allequal = module.allequal + self.arange = module.arange + self.array = module.array +# self.average = module.average + self.concatenate = module.concatenate + self.count = module.count + self.equal = module.equal + self.filled = module.filled + self.getmask = module.getmask + self.getmaskarray = module.getmaskarray + self.id = id + self.inner = module.inner + self.make_mask = module.make_mask + self.masked = module.masked + self.masked_array = module.masked_array + self.masked_values = module.masked_values + self.mask_or = module.mask_or + self.nomask = module.nomask + self.ones = module.ones + self.outer = module.outer + self.repeat = module.repeat + self.resize = module.resize + self.sort = module.sort + self.take = module.take + self.transpose = module.transpose + self.zeros = module.zeros + self.MaskType = module.MaskType + try: + self.umath = module.umath + except AttributeError: + self.umath = module.core.umath + self.testnames = [] + #........................ + def assert_array_compare(self, comparison, x, y, err_msg='', header='', + fill_value=True): + """Asserts that a comparison relation between two masked arrays is satisfied + elementwise.""" + xf = self.filled(x) + yf = self.filled(y) + m = self.mask_or(self.getmask(x), self.getmask(y)) + + x = self.filled(self.masked_array(xf, mask=m), fill_value) + 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): + 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): + y = 0 + try: + cond = (x.shape==() or y.shape==()) or x.shape == y.shape + if not cond: + msg = build_err_msg([x, y], + err_msg + + '\n(shapes %s, %s mismatch)' % (x.shape, + y.shape), + header=header, + names=('x', 'y')) + assert cond, msg + val = comparison(x,y) + if m is not self.nomask and fill_value: + val = self.masked_array(val, mask=m) + if isinstance(val, bool): + cond = val + reduced = [0] + else: + reduced = val.ravel() + cond = reduced.all() + reduced = reduced.tolist() + if not cond: + match = 100-100.0*reduced.count(1)/len(reduced) + msg = build_err_msg([x, y], + err_msg + + '\n(mismatch %s%%)' % (match,), + header=header, + names=('x', 'y')) + assert cond, msg + except ValueError: + msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y')) + raise ValueError(msg) + #............................ + def assert_array_equal(self, x, y, err_msg=''): + """Checks the elementwise equality of two masked arrays.""" + self.assert_array_compare(self.equal, x, y, err_msg=err_msg, + header='Arrays are not equal') + #---------------------------------- + def test_0(self): + "Tests creation" + x = numpy.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.]) + 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]) + zm = self.masked_array(z, mask=[0,1,0,0]) + xf = numpy.where(m1, 1.e+20, x) + xm.set_fill_value(1.e+20) + #..... + assert((xm-ym).filled(0).any()) + #fail_if_equal(xm.mask.astype(int_), ym.mask.astype(int_)) + s = x.shape + assert(xm.size == reduce(lambda x,y:x*y, s)) + assert(self.count(xm) == len(m1) - reduce(lambda x,y:x+y, m1)) + #..... + for s in [(4,3), (6,2)]: + x.shape = s + y.shape = s + xm.shape = s + ym.shape = s + xf.shape = s + + assert(self.count(xm) == len(m1) - reduce(lambda x,y:x+y, m1)) + #---------------------------------- + def test_2(self): + "Tests conversions and indexing" + x1 = numpy.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)) + # tests of indexing + assert type(x2[1]) is type(x1[1]) + assert x1[1] == x2[1] +# assert self.allequal(x1[2],x2[2]) +# assert self.allequal(x1[2:5],x2[2:5]) +# assert self.allequal(x1[:],x2[:]) +# assert self.allequal(x1[1:], x3[1:]) + x1[2] = 9 + x2[2] = 9 + self.assert_array_equal(x1,x2) + x1[1:3] = 99 + x2[1:3] = 99 +# assert self.allequal(x1,x2) + x2[1] = self.masked +# assert self.allequal(x1,x2) + x2[1:3] = self.masked +# assert self.allequal(x1,x2) + x2[:] = x1 + x2[1] = self.masked +# assert self.allequal(self.getmask(x2),self.array([0,1,0,0])) + x3[:] = self.masked_array([1,2,3,4],[0,1,1,0]) +# assert self.allequal(self.getmask(x3), self.array([0,1,1,0])) + 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 + 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) + s1 = x1[1] + s2 = x2[1] + assert x1[1:1].shape == (0,) + # Tests copy-size + n = [0,0,1,0,0] + m = self.make_mask(n) + m2 = self.make_mask(m) + assert(m is m2) + m3 = self.make_mask(m, copy=1) + assert(m is not m3) + + #---------------------------------- + def test_3(self): + "Tests resize/repeat" + x4 = self.arange(4) + x4[2] = self.masked + y4 = self.resize(x4, (8,)) + assert self.allequal(self.concatenate([x4,x4]), y4) + assert self.allequal(self.getmask(y4),[0,0,1,0,0,0,1,0]) + y5 = self.repeat(x4, (2,2,2,2), axis=0) + self.assert_array_equal(y5, [0,0,1,1,2,2,3,3]) + y6 = self.repeat(x4, 2, axis=0) + assert self.allequal(y5, y6) + y7 = x4.repeat((2,2,2,2), axis=0) + assert self.allequal(y5,y7) + y8 = x4.repeat(2,0) + assert self.allequal(y5,y8) + + #---------------------------------- + def test_4(self): + "Test of take, transpose, inner, outer products" + x = self.arange(24) + y = numpy.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)), + self.inner(x, y)) + assert self.allequal(numpy.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 + t = self.take(y,[0,3,4]) + assert t[0] == 'abc' + assert t[1] == 2 + assert t[2] == 3 + #---------------------------------- + def test_5(self): + "Tests inplace w/ scalar" + + x = self.arange(10) + y = self.arange(10) + xm = self.arange(10) + xm[2] = self.masked + x += 1 + assert self.allequal(x, y+1) + xm += 1 + assert self.allequal(xm, y+1) + + x = self.arange(10) + xm = self.arange(10) + xm[2] = self.masked + x -= 1 + assert self.allequal(x, y-1) + xm -= 1 + assert self.allequal(xm, y-1) + + x = self.arange(10)*1.0 + xm = self.arange(10)*1.0 + xm[2] = self.masked + x *= 2.0 + assert self.allequal(x, y*2) + xm *= 2.0 + assert self.allequal(xm, y*2) + + x = self.arange(10)*2 + xm = self.arange(10)*2 + xm[2] = self.masked + x /= 2 + assert self.allequal(x, y) + xm /= 2 + assert self.allequal(xm, y) + + x = self.arange(10)*1.0 + xm = self.arange(10)*1.0 + xm[2] = self.masked + x /= 2.0 + assert self.allequal(x, y/2.0) + xm /= self.arange(10) + self.assert_array_equal(xm, self.ones((10,))) + + x = self.arange(10).astype(float_) + xm = self.arange(10) + xm[2] = self.masked + id1 = self.id(x.raw_data()) + x += 1. + #assert id1 == self.id(x.raw_data()) + assert self.allequal(x, y+1.) + + + def test_6(self): + "Tests inplace w/ array" + + x = self.arange(10, dtype=float_) + y = self.arange(10) + xm = self.arange(10, dtype=float_) + xm[2] = self.masked + m = xm.mask + a = self.arange(10, dtype=float_) + a[-1] = self.masked + x += a + xm += a + assert self.allequal(x,y+a) + assert self.allequal(xm,y+a) + assert self.allequal(xm.mask, self.mask_or(m,a.mask)) + + x = self.arange(10, dtype=float_) + xm = self.arange(10, dtype=float_) + xm[2] = self.masked + m = xm.mask + a = self.arange(10, dtype=float_) + a[-1] = self.masked + x -= a + xm -= a + assert self.allequal(x,y-a) + assert self.allequal(xm,y-a) + assert self.allequal(xm.mask, self.mask_or(m,a.mask)) + + x = self.arange(10, dtype=float_) + xm = self.arange(10, dtype=float_) + xm[2] = self.masked + m = xm.mask + a = self.arange(10, dtype=float_) + a[-1] = self.masked + x *= a + xm *= a + assert self.allequal(x,y*a) + assert self.allequal(xm,y*a) + assert self.allequal(xm.mask, self.mask_or(m,a.mask)) + + x = self.arange(10, dtype=float_) + xm = self.arange(10, dtype=float_) + xm[2] = self.masked + m = xm.mask + a = self.arange(10, dtype=float_) + a[-1] = self.masked + x /= a + xm /= a + + #---------------------------------- + def test_7(self): + "Tests ufunc" + d = (self.array([1.0, 0, -1, pi/2]*2, mask=[0,1]+[0]*6), + self.array([1.0, 0, -1, pi/2]*2, mask=[1,0]+[0]*6),) + for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', +# 'sin', 'cos', 'tan', +# 'arcsin', 'arccos', 'arctan', +# 'sinh', 'cosh', 'tanh', +# 'arcsinh', +# 'arccosh', +# 'arctanh', +# 'absolute', 'fabs', 'negative', +# # 'nonzero', 'around', +# 'floor', 'ceil', +# # 'sometrue', 'alltrue', +# 'logical_not', +# 'add', 'subtract', 'multiply', +# 'divide', 'true_divide', 'floor_divide', +# 'remainder', 'fmod', 'hypot', 'arctan2', +# 'equal', 'not_equal', 'less_equal', 'greater_equal', +# 'less', 'greater', +# 'logical_and', 'logical_or', 'logical_xor', + ]: + #print f + try: + uf = getattr(self.umath, f) + except AttributeError: + uf = getattr(fromnumeric, f) + mf = getattr(self.module, f) + args = d[:uf.nin] + ur = uf(*args) + mr = mf(*args) + self.assert_array_equal(ur.filled(0), mr.filled(0), f) + self.assert_array_equal(ur._mask, mr._mask) + + #---------------------------------- + def test_99(self): + # test average + ott = self.array([0.,1.,2.,3.], mask=[1,0,0,0]) + self.assert_array_equal(2.0, self.average(ott,axis=0)) + self.assert_array_equal(2.0, self.average(ott, weights=[1., 1., 2., 1.])) + result, wts = self.average(ott, weights=[1.,1.,2.,1.], returned=1) + self.assert_array_equal(2.0, result) + assert(wts == 4.0) + ott[:] = self.masked + assert(self.average(ott,axis=0) is self.masked) + ott = self.array([0.,1.,2.,3.], mask=[1,0,0,0]) + ott = ott.reshape(2,2) + ott[:,1] = self.masked + self.assert_array_equal(self.average(ott,axis=0), [2.0, 0.0]) + assert(self.average(ott,axis=1)[0] is self.masked) + self.assert_array_equal([2.,0.], self.average(ott, axis=0)) + result, wts = self.average(ott, axis=0, returned=1) + self.assert_array_equal(wts, [1., 0.]) + w1 = [0,1,1,1,1,0] + w2 = [[0,1,1,1,1,0],[1,0,0,0,0,1]] + x = self.arange(6) + 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, 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.]) + self.assert_array_equal(self.average(y, axis=1), [self.average(x,axis=0), self.average(x,axis=0) * 2.0]) + m1 = self.zeros(6) + m2 = [0,0,1,1,0,0] + m3 = [[0,0,1,1,0,0],[0,1,1,1,1,0]] + m4 = self.ones(6) + m5 = [0, 1, 1, 1, 1, 1] + self.assert_array_equal(self.average(self.masked_array(x, m1),axis=0), 2.5) + self.assert_array_equal(self.average(self.masked_array(x, m2),axis=0), 2.5) + # assert(self.average(masked_array(x, m4),axis=0) is masked) + self.assert_array_equal(self.average(self.masked_array(x, m5),axis=0), 0.0) + self.assert_array_equal(self.count(self.average(self.masked_array(x, m4),axis=0)), 0) + z = self.masked_array(y, m3) + self.assert_array_equal(self.average(z, None), 20./6.) + self.assert_array_equal(self.average(z, axis=0), [0.,1.,99.,99.,4.0, 7.5]) + self.assert_array_equal(self.average(z, axis=1), [2.5, 5.0]) + self.assert_array_equal(self.average(z,axis=0, weights=w2), [0.,1., 99., 99., 4.0, 10.0]) + #------------------------ + def test_A(self): + x = self.arange(24) + y = numpy.arange(24) + x[5:6] = self.masked + x = x.reshape(2,3,4) + + +################################################################################ +if __name__ == '__main__': + + setup_base = "from __main__ import moduletester \n"\ + "import numpy\n" \ + "tester = moduletester(module)\n" + setup_old = "import numpy.core.ma as module\n"+setup_base + setup_new = "import maskedarray.core_ini as module\n"+setup_base + setup_cur = "import maskedarray.core as module\n"+setup_base +# setup_alt = "import maskedarray.core_alt as module\n"+setup_base +# setup_tmp = "import maskedarray.core_tmp as module\n"+setup_base + + (nrepeat, nloop) = (10, 10) + + if 1: + for i in range(1,8): + func = 'tester.test_%i()' % i + old = timeit.Timer(func, setup_old).repeat(nrepeat, nloop*10) + new = timeit.Timer(func, setup_new).repeat(nrepeat, nloop*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) + old = numpy.sort(old) + new = numpy.sort(new) + cur = numpy.sort(cur) +# alt = numpy.sort(alt) +# tmp = numpy.sort(tmp) + print "#%i" % i +50*'.' + print eval("moduletester.test_%i.__doc__" % i) + print "numpy.core.ma: %.3f - %.3f" % (old[0], old[1]) + print "core_ini : %.3f - %.3f" % (new[0], new[1]) + print "core_current : %.3f - %.3f" % (cur[0], cur[1]) +# print "core_alt : %.3f - %.3f" % (alt[0], alt[1]) +# print "core_tmp : %.3f - %.3f" % (tmp[0], tmp[1]) Added: trunk/scipy/sandbox/maskedarray/version.py =================================================================== --- trunk/scipy/sandbox/maskedarray/version.py 2008-01-12 02:06:23 UTC (rev 3816) +++ trunk/scipy/sandbox/maskedarray/version.py 2008-01-12 06:53:41 UTC (rev 3817) @@ -0,0 +1,11 @@ +"""Version number""" + +version = '1.00' +release = False + +if not release: + import core + import extras + revision = [core.__revision__.split(':')[-1][:-1].strip(), + extras.__revision__.split(':')[-1][:-1].strip(),] + version += '.dev%04i' % max([int(rev) for rev in revision]) From scipy-svn at scipy.org Sat Jan 12 02:02:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 01:02:16 -0600 (CST) Subject: [Scipy-svn] r3818 - trunk/scipy/io/tests Message-ID: <20080112070216.F1AD5C7C09C@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-12 01:02:12 -0600 (Sat, 12 Jan 2008) New Revision: 3818 Removed: trunk/scipy/io/tests/test_datasource.py Modified: trunk/scipy/io/tests/test_array_import.py trunk/scipy/io/tests/test_mmio.py trunk/scipy/io/tests/test_npfile.py trunk/scipy/io/tests/test_recaster.py Log: Datasource moved to numpy, this removes the tests for it Modified: trunk/scipy/io/tests/test_array_import.py =================================================================== --- trunk/scipy/io/tests/test_array_import.py 2008-01-12 06:53:41 UTC (rev 3817) +++ trunk/scipy/io/tests/test_array_import.py 2008-01-12 07:02:12 UTC (rev 3818) @@ -6,18 +6,15 @@ # also check out numpyio.fread.__doc__ and other method docstrings. import os -from numpy.testing import * -set_package_path() -import io -from io import numpyio -restore_path() +from scipy.testing import * +import scipy.io as io +from scipy.io import numpyio - import numpy.oldnumeric as N import tempfile -class TestNumpyio(NumpyTestCase): - def check_basic(self): +class TestNumpyio(TestCase): + def test_basic(self): # Generate some data a = 255*rand(20) # Open a file @@ -34,8 +31,8 @@ assert(N.product(a.astype(N.Int16) == b,axis=0)) os.remove(fname) -class TestReadArray(NumpyTestCase): - def check_complex(self): +class TestReadArray(TestCase): + def test_complex(self): a = rand(13,4) + 1j*rand(13,4) fname = tempfile.mktemp('.dat') io.write_array(fname,a) @@ -43,7 +40,7 @@ assert_array_almost_equal(a,b,decimal=4) os.remove(fname) - def check_float(self): + def test_float(self): a = rand(3,4)*30 fname = tempfile.mktemp('.dat') io.write_array(fname,a) @@ -51,7 +48,7 @@ assert_array_almost_equal(a,b,decimal=4) os.remove(fname) - def check_integer(self): + def test_integer(self): from scipy import stats a = stats.randint.rvs(1,20,size=(3,4)) fname = tempfile.mktemp('.dat') @@ -61,4 +58,4 @@ os.remove(fname) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Deleted: trunk/scipy/io/tests/test_datasource.py =================================================================== --- trunk/scipy/io/tests/test_datasource.py 2008-01-12 06:53:41 UTC (rev 3817) +++ trunk/scipy/io/tests/test_datasource.py 2008-01-12 07:02:12 UTC (rev 3818) @@ -1,256 +0,0 @@ - -import bz2 -import gzip -import os -import sys -import struct -from tempfile import mkdtemp, mkstemp, NamedTemporaryFile -from shutil import rmtree -from urlparse import urlparse - -from numpy.testing import * - -# HACK: import the src datasource -# Until datasource is robust enough to include in scipy.io package -sys.path.insert(0, os.path.abspath('..')) -import datasource -del sys.path[0] - -#set_package_path() -#from scipy.io import datasource -#restore_path() - -def urlopen_stub(url, data=None): - '''Stub to replace urlopen for testing.''' - if url == valid_httpurl(): - tmpfile = NamedTemporaryFile(prefix='urltmp_') - return tmpfile - else: - raise datasource.URLError('Name or service not known') - -# Rebind urlopen during testing. For a 'real' test, uncomment the rebinding -# below. -datasource.urlopen = urlopen_stub - -# A valid website for more robust testing -http_path = 'http://www.google.com/' -http_file = 'index.html' - -http_fakepath = 'http://fake.abc.web/site/' -http_fakefile = 'fake.txt' - -magic_line = 'three is the magic number' - - -# Utility functions used by many TestCases -def valid_textfile(filedir): - # Generate and return a valid temporary file. - fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir, text=True) - os.close(fd) - return path - -def invalid_textfile(filedir): - # Generate and return an invalid filename. - fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir) - os.close(fd) - os.remove(path) - return path - -def valid_httpurl(): - return http_path+http_file - -def invalid_httpurl(): - return http_fakepath+http_fakefile - -def valid_baseurl(): - return http_path - -def invalid_baseurl(): - return http_fakepath - -def valid_httpfile(): - return http_file - -def invalid_httpfile(): - return http_fakefile - -class TestDataSourceOpen(NumpyTestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.ds = datasource.DataSource(self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.ds - - def test_ValidHTTP(self): - assert self.ds.open(valid_httpurl()) - - def test_InvalidHTTP(self): - self.assertRaises(IOError, self.ds.open, invalid_httpurl()) - - def test_ValidFile(self): - local_file = valid_textfile(self.tmpdir) - assert self.ds.open(local_file) - - def test_InvalidFile(self): - invalid_file = invalid_textfile(self.tmpdir) - self.assertRaises(IOError, self.ds.open, invalid_file) - - def test_ValidGzipFile(self): - # Test datasource's internal file_opener for Gzip files. - filepath = os.path.join(self.tmpdir, 'foobar.txt.gz') - fp = gzip.open(filepath, 'w') - fp.write(magic_line) - fp.close() - fp = self.ds.open(filepath) - result = fp.readline() - fp.close() - self.assertEqual(magic_line, result) - - def test_ValidBz2File(self): - # Test datasource's internal file_opener for BZip2 files. - filepath = os.path.join(self.tmpdir, 'foobar.txt.bz2') - fp = bz2.BZ2File(filepath, 'w') - fp.write(magic_line) - fp.close() - fp = self.ds.open(filepath) - result = fp.readline() - fp.close() - self.assertEqual(magic_line, result) - - -class TestDataSourceExists(NumpyTestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.ds = datasource.DataSource(self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.ds - - def test_ValidHTTP(self): - assert self.ds.exists(valid_httpurl()) - - def test_InvalidHTTP(self): - self.assertEqual(self.ds.exists(invalid_httpurl()), False) - - def test_ValidFile(self): - # Test valid file in destpath - tmpfile = valid_textfile(self.tmpdir) - assert self.ds.exists(tmpfile) - # Test valid local file not in destpath - localdir = mkdtemp() - tmpfile = valid_textfile(localdir) - assert self.ds.exists(tmpfile) - rmtree(localdir) - - def test_InvalidFile(self): - tmpfile = invalid_textfile(self.tmpdir) - self.assertEqual(self.ds.exists(tmpfile), False) - - -class TestDataSourceAbspath(NumpyTestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.ds = datasource.DataSource(self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.ds - - def test_ValidHTTP(self): - scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl()) - local_path = os.path.join(self.tmpdir, netloc, upath.strip(os.sep)) - self.assertEqual(local_path, self.ds.abspath(valid_httpurl())) - - def test_ValidFile(self): - tmpfile = valid_textfile(self.tmpdir) - tmpfilename = os.path.split(tmpfile)[-1] - # Test with filename only - self.assertEqual(tmpfile, self.ds.abspath(os.path.split(tmpfile)[-1])) - # Test filename with complete path - self.assertEqual(tmpfile, self.ds.abspath(tmpfile)) - - def test_InvalidHTTP(self): - scheme, netloc, upath, pms, qry, frg = urlparse(invalid_httpurl()) - invalidhttp = os.path.join(self.tmpdir, netloc, upath.strip(os.sep)) - self.assertNotEqual(invalidhttp, self.ds.abspath(valid_httpurl())) - - def test_InvalidFile(self): - invalidfile = valid_textfile(self.tmpdir) - tmpfile = valid_textfile(self.tmpdir) - tmpfilename = os.path.split(tmpfile)[-1] - # Test with filename only - self.assertNotEqual(invalidfile, self.ds.abspath(tmpfilename)) - # Test filename with complete path - self.assertNotEqual(invalidfile, self.ds.abspath(tmpfile)) - - -class TestRespositoryAbspath(NumpyTestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.repos = datasource.Repository(valid_baseurl(), self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.repos - - def test_ValidHTTP(self): - scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl()) - local_path = os.path.join(self.repos._destpath, netloc, \ - upath.strip(os.sep)) - filepath = self.repos.abspath(valid_httpfile()) - self.assertEqual(local_path, filepath) - - -class TestRepositoryExists(NumpyTestCase): - def setUp(self): - self.tmpdir = mkdtemp() - self.repos = datasource.Repository(valid_baseurl(), self.tmpdir) - - def tearDown(self): - rmtree(self.tmpdir) - del self.repos - - def test_ValidFile(self): - # Create local temp file - tmpfile = valid_textfile(self.tmpdir) - assert self.repos.exists(tmpfile) - - def test_InvalidFile(self): - tmpfile = invalid_textfile(self.tmpdir) - self.assertEqual(self.repos.exists(tmpfile), False) - - def test_RemoveHTTPFile(self): - assert self.repos.exists(valid_httpurl()) - - def test_CachedHTTPFile(self): - localfile = valid_httpurl() - # Create a locally cached temp file with an URL based - # directory structure. This is similar to what Repository.open - # would do. - scheme, netloc, upath, pms, qry, frg = urlparse(localfile) - local_path = os.path.join(self.repos._destpath, netloc) - os.mkdir(local_path, 0700) - tmpfile = valid_textfile(local_path) - assert self.repos.exists(tmpfile) - - -class TestOpenFunc(NumpyTestCase): - def setUp(self): - self.tmpdir = mkdtemp() - - def tearDown(self): - rmtree(self.tmpdir) - - def test_DataSourceOpen(self): - local_file = valid_textfile(self.tmpdir) - # Test case where destpath is passed in - assert datasource.open(local_file, destpath=self.tmpdir) - # Test case where default destpath is used - assert datasource.open(local_file) - - -if __name__ == "__main__": - NumpyTest().run() Modified: trunk/scipy/io/tests/test_mmio.py =================================================================== --- trunk/scipy/io/tests/test_mmio.py 2008-01-12 06:53:41 UTC (rev 3817) +++ trunk/scipy/io/tests/test_mmio.py 2008-01-12 07:02:12 UTC (rev 3818) @@ -1,17 +1,16 @@ #!/usr/bin/env python from tempfile import mktemp -from numpy.testing import * from numpy import array,transpose +from scipy.testing import * -set_package_path() -from io.mmio import mminfo,mmread,mmwrite import scipy -restore_path() +import scipy.sparse +from scipy.io.mmio import mminfo,mmread,mmwrite -class TestMMIOArray(NumpyTestCase): +class TestMMIOArray(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2],[3,4]] fn = mktemp() mmwrite(fn,a) @@ -19,7 +18,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_simple_rectangular(self): + def test_simple_rectangular(self): a = [[1,2,3],[4,5,6]] fn = mktemp() mmwrite(fn,a) @@ -27,7 +26,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_simple_rectangular_real(self): + def test_simple_rectangular_real(self): a = [[1,2],[3.5,4],[5,6]] fn = mktemp() mmwrite(fn,a) @@ -35,7 +34,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_simple_real(self): + def test_simple_real(self): a = [[1,2],[3,4.0]] fn = mktemp() mmwrite(fn,a) @@ -43,7 +42,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2],[3,4j]] fn = mktemp() mmwrite(fn,a) @@ -51,7 +50,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_simple_symmetric(self): + def test_simple_symmetric(self): a = [[1,2],[2,4]] fn = mktemp() mmwrite(fn,a) @@ -59,7 +58,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_simple_skew_symmetric(self): + def test_simple_skew_symmetric(self): a = [[1,2],[-2,4]] fn = mktemp() mmwrite(fn,a) @@ -67,7 +66,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_simple_skew_symmetric_float(self): + def test_simple_skew_symmetric_float(self): a = array([[1,2],[-2.0,4]],'f') fn = mktemp() mmwrite(fn,a) @@ -75,7 +74,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_simple_hermitian(self): + def test_simple_hermitian(self): a = [[1,2+3j],[2-3j,4]] fn = mktemp() mmwrite(fn,a) @@ -83,7 +82,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_random_symmetric_real(self): + def test_random_symmetric_real(self): sz = (20,20) a = rand(*sz) a = a + transpose(a) @@ -93,7 +92,7 @@ b = mmread(fn) assert_array_almost_equal(a,b) - def check_random_rect_real(self): + def test_random_rect_real(self): sz = (20,15) a = rand(*sz) fn = mktemp() @@ -184,8 +183,8 @@ 5 4 ''' -class TestMMIOCoordinate(NumpyTestCase): - def check_read_geneal(self): +class TestMMIOCoordinate(TestCase): + def test_read_geneal(self): """read a general matrix""" fn = mktemp() f = open(fn,'w') @@ -200,7 +199,7 @@ b = mmread(fn).todense() assert_array_almost_equal(a,b) - def check_read_hermitian(self): + def test_read_hermitian(self): """read a hermitian matrix""" fn = mktemp() f = open(fn,'w') @@ -215,7 +214,7 @@ b = mmread(fn).todense() assert_array_almost_equal(a,b) - def check_read_skew(self): + def test_read_skew(self): """read a skew-symmetric matrix""" fn = mktemp() f = open(fn,'w') @@ -230,7 +229,7 @@ b = mmread(fn).todense() assert_array_almost_equal(a,b) - def check_read_symmetric(self): + def test_read_symmetric(self): """read a symmetric matrix""" fn = mktemp() f = open(fn,'w') @@ -245,7 +244,7 @@ b = mmread(fn).todense() assert_array_almost_equal(a,b) - def check_read_symmetric(self): + def test_read_symmetric(self): """read a symmetric pattern matrix""" fn = mktemp() f = open(fn,'w') @@ -261,7 +260,7 @@ assert_array_almost_equal(a,b) - def check_real_write_read(self): + def test_real_write_read(self): I = array([0, 0, 1, 2, 3, 3, 3, 4]) J = array([0, 3, 1, 2, 1, 3, 4, 4]) V = array([ 1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0 ]) @@ -276,7 +275,7 @@ b = mmread(fn).todense() assert_array_almost_equal(a,b) - def check_complex_write_read(self): + def test_complex_write_read(self): I = array([0, 0, 1, 2, 3, 3, 3, 4]) J = array([0, 3, 1, 2, 1, 3, 4, 4]) V = array([ 1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j, @@ -293,4 +292,4 @@ assert_array_almost_equal(a,b) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/io/tests/test_npfile.py =================================================================== --- trunk/scipy/io/tests/test_npfile.py 2008-01-12 06:53:41 UTC (rev 3817) +++ trunk/scipy/io/tests/test_npfile.py 2008-01-12 07:02:12 UTC (rev 3818) @@ -1,14 +1,12 @@ +import os from StringIO import StringIO -import os from tempfile import mkstemp -from numpy.testing import * +from scipy.testing import * import numpy as N -set_package_path() -from io.npfile import npfile, sys_endian_code -restore_path() +from scipy.io.npfile import npfile, sys_endian_code -class TestNpFile(NumpyTestCase): +class TestNpFile(TestCase): def test_init(self): fd, fname = mkstemp() @@ -102,3 +100,6 @@ assert_array_equal(npf.read_array(adt, shp, endian='dtype'), bs_arr) npf.rewind() assert_array_equal(npf.read_array(adt, shp, order='C'), cf_arr) + +if __name__ == "__main__": + unittest.main() Modified: trunk/scipy/io/tests/test_recaster.py =================================================================== --- trunk/scipy/io/tests/test_recaster.py 2008-01-12 06:53:41 UTC (rev 3817) +++ trunk/scipy/io/tests/test_recaster.py 2008-01-12 07:02:12 UTC (rev 3818) @@ -1,16 +1,14 @@ -from numpy.testing import * import numpy as N +from scipy.testing import * -set_package_path() -from io.recaster import sctype_attributes, Recaster, RecastError -restore_path() +from scipy.io.recaster import sctype_attributes, Recaster, RecastError try: # Python 2.3 support from sets import Set as set except: pass -class TestRecaster(NumpyTestCase): +class TestRecaster(TestCase): def test_init(self): # Setting sctype_list @@ -173,3 +171,7 @@ dtt = arr.dtype.type assert dtt is outp, \ 'Expected %s from %s, got %s' % (outp, inp, dtt) + +if __name__ == "__main__": + unittest.main() + From scipy-svn at scipy.org Sat Jan 12 02:24:58 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 01:24:58 -0600 (CST) Subject: [Scipy-svn] r3819 - in trunk/scipy: . testing testing/examples Message-ID: <20080112072458.C0BFA39C01A@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-12 01:24:52 -0600 (Sat, 12 Jan 2008) New Revision: 3819 Added: trunk/scipy/testing/ trunk/scipy/testing/__init__.py trunk/scipy/testing/decorators.py trunk/scipy/testing/examples/ trunk/scipy/testing/examples/README.txt trunk/scipy/testing/examples/test_foo.py trunk/scipy/testing/nosetester.py trunk/scipy/testing/nulltester.py trunk/scipy/testing/pkgtester.py trunk/scipy/testing/setup.py trunk/scipy/testing/utils.py Log: Added nose testing utilities Added: trunk/scipy/testing/__init__.py =================================================================== --- trunk/scipy/testing/__init__.py 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/__init__.py 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,19 @@ +"""Common test support for all scipy test scripts. + +This single module should provide all the common functionality for scipy tests +in a single location, so that test script can just import it and work right +away. +""" + +import unittest +from unittest import TestCase + +try: + import nose +except ImportError: + print 'Need nose testing framework installed for scipy tests' + raise + +import decorators as dec +from numpy.testing.utils import * +from utils import * Added: trunk/scipy/testing/decorators.py =================================================================== --- trunk/scipy/testing/decorators.py 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/decorators.py 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,42 @@ +"""Decorators for labeling test objects.""" + +def slow(t): + """Labels a test as 'slow'. + + The exact definition of a slow test is obviously both subjective and + hardware-dependent, but in general any individual test that requires more + than a second or two should be labeled as slow (the whole suite consits of + thousands of tests, so even a second is significant).""" + + t.slow = True + return t + +def bench(t): + ''' Labels a test as a benchmark. + + Benchmark tests are often slow, and intended to test timings + between different algorithms rather than validity of the result. ''' + + t.bench = True + return t + +def willfail(t): + ''' Labels test as known failure + + This label allows the tester to deselect the test in standard cases ''' + t.willfail = True + return t + +def is_nosetest(tf): + ''' Signals to nose that this function is or is not a test + + e.g + >>> @is_nosetest(False) + >>> def func_with_test_in_name(arg1, arg2): pass + ... + >>> + ''' + def set_test(t): + t.__test__ = tf + return t + return set_test Added: trunk/scipy/testing/examples/README.txt =================================================================== --- trunk/scipy/testing/examples/README.txt 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/examples/README.txt 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,66 @@ +============ + Nose tests +============ + +SciPy will use, and require nose for all testing. It will be possible for +users to use all of scipy without nose on their systems, but *not* to run the +test suite. + +Labels +====== + +We are going to use labels for tests, instead of the old level system. For +now, we'll use 'slow' as a label for slow-running tests, and will make more if +needed in the future for speed considerations. + +Labels will be implemented as one decorator per test. All pre-defined labels +are implemented in numpy.testing.decorators + +This would run all tests, since nose by default discovers everything:: + nosetests -s test_foo.py + +this:: + nosetests -s -A slow test_foo.py + +will only run tests labeled 'slow' (for which there's a decorator) and this:: + nosetests -s -A "not slow" test_foo.py + +will *exclude* all slow tests from a run. + +The scipy.test() function call will expose the above with convenient syntax. + +Initially we only have the @slow decorator, later we may provide new ones as +the need for them arises in actual use. + + +Benchmark tests +=============== + +Routines that don't actually test correctness but instead do performance +benchmarking will live in a benchmarks/ directory next to the tests/ directory +of each module. There will be a scipy.benchmark() call that does benchmarking, +similar to scipy.test() but separate from it. + +Scipy test + +For each package, there will be a function that takes level arguments, +and performs tests per level + +import scipy.mypackage +scipy.mypackage.test() # fast, unlabeled tests +scipy.mypackage.test('full') # unlabeled, not slow, not villfail +scipy.mypackage.test('slow') # just slow tests +scipy.mypackage.test('bench') # just benchmarks +scipy.mypackage.test(None) # all possible tests, including benchmarks +scipy.mypackage.test(doctests=True) # fast tests, with doctests + +At the base level, scipy.test(*args) collects the test suite from each +package, and runs it, with *args as above. + +scipy.mypackage.test() + +Runs all plausible tests in this package, and package test directory, +and runs any subpackage tests such as +scipy.mypackage.mysubpackage.test() + + Property changes on: trunk/scipy/testing/examples/README.txt ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/scipy/testing/examples/test_foo.py =================================================================== --- trunk/scipy/testing/examples/test_foo.py 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/examples/test_foo.py 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,106 @@ +"""Example SciPy test module, using nose features. + +For information on nose, see: + + http://somethingaboutorange.com/mrl/projects/nose + +To run it in its simplest form:: + nosetests test_foo.py + + +Labels will be implemented as one decorator per test. All pre-defined labels +are implemented in numpy.testing.decorators + +This would run all tests, since nose by default discovers everything:: + nosetests -s test_foo.py + +this:: + nosetests -s -A slow test_foo.py + +will only run tests labeled 'slow' (for which there's a decorator) and this:: + nosetests -s -A "not slow" test_foo.py + +will *exclude* all slow tests from a run. +""" + +# This single import statement should provide all the common functionality for +# scipy tests in a single location. +from scipy.testing import * + +def setup(): + """Module-level setup""" + print 'doing setup' + +def teardown(): + """Module-level teardown""" + print 'doing teardown' + + +class ClassicTest(TestCase): + """A regular unittest, with the extra Numpy features.""" + def test_1(self): + print 'First test' + + def test_2(self): + print 'Second test' + + # This is how to tag a test as slow + @dec.slow + def test_big(self,level=5): + print 'Big, slow test' + + +def test_simplefunction(): + """A simple test function.""" + assert True + +def check_even(n, nn): + """A check function to be used in a test generator.""" + assert n % 2 == 0 or nn % 2 == 0 + +# Test generators are best left without docstring, so nose (in verbose mode) +# shows the actual call they produce automatically, including arguments. +def test_evens(): + for i in range(0,4,2): + yield check_even, i, i*3 + +def setup_func(): + """A trivial setup function.""" + print "In setup_func" + +def teardown_func(): + """A trivial teardown function.""" + print "In teardown_func" + + at nose.with_setup(setup_func, teardown_func) +def test_with_extras(): + """This test uses the setup/teardown functions.""" + print " In test_with_extras" + +# Setup and teardown functions may be used with test generators. The setup and +# teardown attributes must be attached to the generator function: + at nose.with_setup(setup_func, teardown_func) +def test_generator(): + for i in range(6,10,2): + yield check_even, i, i*3 + + at dec.slow +def test_nasty(): + "A difficult test that takes a long time..." + print '*** nasty slow test ***' + + +def test_time(): + "A simple test that times things" + x = 1 + time = measure("x+1",times=100,label='test_time') + info('Time taken: %s' % time) + +def test_warn(): + "A simple test that prints a warning." + warn('Bad things are happening...') + +def test_error(): + "A simple test that prints an error message." + error('Really bad things are happening...') + Added: trunk/scipy/testing/nosetester.py =================================================================== --- trunk/scipy/testing/nosetester.py 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/nosetester.py 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,56 @@ +''' Nose tester object ''' +import os +import sys + +import nose + +class NoseTester(object): + """ Scipy nose test runner. + + Usage: NoseTester().test() + + is package path or module - None finds calling module path + """ + def __init__(self, package=None): + if package is None: + f = sys._getframe(1) + package = f.f_locals.get('__file__', None) + assert package is not None + package = os.path.dirname(package) + else isinstance(package, type(os)): + package = os.path.dirname(package.__file__) + self.package_path = package + + def test(self, labels='fast', verbose=1, doctests=False, extra_argv=None): + ''' Module testing function + + labels - identifies tests to run. This can be a string to + pass to the nosetests executable with the '-A' + option, or one of several special values. + Special values are: + 'fast' - the default - which corresponds to + nosetests -A option of + 'not slow and not bench and not willfail'. + 'full' - fast (as above) and slow tests as in + nosetests -A option of 'not bench and not willfail'. + None or '' - run all tests and benchmarks + + verbose - verbosity value 1-10 + doctests - if True, run doctests in module + extra_argv - list with any extra args to pass to nosetest + ''' + argv = ['scipy module test', self.package_path, '-s'] + if labels: + if labels == 'fast': + labels = 'not slow and not bench and not willfail' + elif labels == 'full': + labels = 'not bench and not willfail' + argv += ['-A', labels] + argv += ['--verbosity', str(verbose)] + if doctests: + argv+=['--with-doctest'] + if extra_argv: + argv+= extra_argv + nose.run(argv=argv) + + Added: trunk/scipy/testing/nulltester.py =================================================================== --- trunk/scipy/testing/nulltester.py 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/nulltester.py 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,8 @@ +''' Null tester (when nose not importable ''' + +class NullTester(object): + def __init__(self, *args, **kwargs): + pass + def test(self, labels=None, *args, **kwargs): + raise ImportError, 'Need nose testing on path for tests' + Added: trunk/scipy/testing/pkgtester.py =================================================================== --- trunk/scipy/testing/pkgtester.py 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/pkgtester.py 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,8 @@ +''' Define test function for scipy package ''' +try: + import nose +except ImportError: + from scipy.testing.nulltester import NullTester as Tester +else: + from scipy.testing.nosetester import NoseTester as Tester + Added: trunk/scipy/testing/setup.py =================================================================== --- trunk/scipy/testing/setup.py 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/setup.py 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,10 @@ +#!/usr/bin/env python + +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + config = Configuration('testing', parent_package, top_path) + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) Added: trunk/scipy/testing/utils.py =================================================================== --- trunk/scipy/testing/utils.py 2008-01-12 07:02:12 UTC (rev 3818) +++ trunk/scipy/testing/utils.py 2008-01-12 07:24:52 UTC (rev 3819) @@ -0,0 +1,60 @@ +"""Simple testing utilities +""" + +__all__ = ['set_local_path', 'restore_path', 'measure', 'info', 'warn', 'error'] + +import os +import sys + +from numpy.distutils.misc_util import yellow_text, red_text +from numpy.testing.utils import jiffies + +def set_local_path(): + """ Prepend local directory to sys.path. + + The caller is responsible for removing this path by using + + restore_path() + """ + f = sys._getframe(1) + if f.f_locals['__name__']=='__main__': + testfile = sys.argv[0] + else: + testfile = f.f_locals['__file__'] + local_path = os.path.normpath(os.path.dirname(os.path.abspath(testfile))) + sys.path.insert(0,local_path) + return + +def restore_path(): + del sys.path[0] + return + +def measure(code_str,times=1,label=None): + """ Return elapsed time for executing code_str in the + namespace of the caller for given times. + """ + frame = sys._getframe(1) + locs,globs = frame.f_locals,frame.f_globals + + code = compile(code_str, + 'Test name: %s ' % label, + 'exec') + i = 0 + elapsed = jiffies() + while i> sys.stdout, message + sys.stdout.flush() + +def warn(message): + print >> sys.stderr,yellow_text('Warning: %s' % (message)) + sys.stderr.flush() + +def error(message): + print >> sys.stderr,red_text('Error: %s' % (message)) + sys.stderr.flush() From scipy-svn at scipy.org Sat Jan 12 03:50:44 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 02:50:44 -0600 (CST) Subject: [Scipy-svn] r3820 - in trunk/scipy: sandbox/multigrid sandbox/multigrid/tests sparse sparse/sparsetools sparse/tests Message-ID: <20080112085044.7C35A39C0FE@new.scipy.org> Author: wnbell Date: 2008-01-12 02:49:56 -0600 (Sat, 12 Jan 2008) New Revision: 3820 Modified: trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sandbox/multigrid/sa.py trunk/scipy/sandbox/multigrid/simple_test.py trunk/scipy/sandbox/multigrid/tests/test_sa.py trunk/scipy/sandbox/multigrid/utils.py trunk/scipy/sparse/sparsetools/sparsetools.h trunk/scipy/sparse/sparsetools/sparsetools.i trunk/scipy/sparse/sparsetools/sparsetools.py trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx trunk/scipy/sparse/spfuncs.py trunk/scipy/sparse/tests/test_spfuncs.py Log: multigrid now uses BSR format Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-12 08:49:56 UTC (rev 3820) @@ -78,7 +78,7 @@ -def smoothed_aggregation_solver(A, B=None, blocks=None, \ +def smoothed_aggregation_solver(A, B=None, \ aggregation=None, max_levels=10, \ max_coarse=500, epsilon=0.0, \ omega=4.0/3.0, symmetric=True, \ @@ -153,7 +153,7 @@ if aggregation is None: while len(As) < max_levels and A.shape[0] > max_coarse: - P,B,blocks = sa_interpolation(A,B,epsilon*0.5**(len(As)-1),omega=omega,blocks=blocks) + P,B = sa_interpolation(A,B,epsilon*0.5**(len(As)-1),omega=omega) A = (P.T.tocsr() * A) * P #galerkin operator @@ -162,7 +162,7 @@ else: #use user-defined aggregation for AggOp in aggregation: - P,B,blocks = sa_interpolation(A,B,omega=omega,AggOp=AggOp) + P,B = sa_interpolation(A,B,omega=omega,AggOp=AggOp) A = (P.T.tocsr() * A) * P #galerkin operator @@ -279,8 +279,8 @@ if __name__ == '__main__': from scipy import * + from scipy.sandbox.multigrid import * candidates = None - blocks = None A = poisson_problem2D(40,1e-2) #A = io.mmread("rocker_arm_surface.mtx").tocsr() #A = io.mmread("9pt-100x100.mtx").tocsr() @@ -291,7 +291,11 @@ #candidates = io.mmread('tests/sample_data/elas30_nullspace.mtx') #blocks = arange(A.shape[0]/2).repeat(2) - ml = smoothed_aggregation_solver(A,candidates,blocks=blocks,epsilon=0.08,max_coarse=100,max_levels=10) + mats = io.loadmat('/home/nathan/Work/ogroup/matrices/elasticity/simple_grid_2d/elasticity_50x50.mat') + A = mats['A'] + candidates = mats['B'] + + ml = smoothed_aggregation_solver(A,candidates,epsilon=0.08,max_coarse=100,max_levels=10) #ml = ruge_stuben_solver(A) x = rand(A.shape[0]) Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-12 08:49:56 UTC (rev 3820) @@ -2,10 +2,10 @@ import numpy from numpy import array,arange,ones,zeros,sqrt,isinf,asarray,empty,diff,\ ascontiguousarray -from scipy.sparse import csr_matrix,isspmatrix_csr +from scipy.sparse import csr_matrix, isspmatrix_csr, bsr_matrix, isspmatrix_bsr from utils import diag_sparse, approximate_spectral_radius, \ - symmetric_rescaling, expand_into_blocks + symmetric_rescaling, expand_into_blocks, scale_columns import multigridtools __all__ = ['sa_filtered_matrix','sa_strong_connections','sa_constant_interpolation', @@ -13,7 +13,7 @@ -def sa_filtered_matrix(A,epsilon,blocks=None): +def sa_filtered_matrix(A,epsilon): """The filtered matrix is obtained from A by lumping all weak off-diagonal entries onto the diagonal. Weak off-diagonals are determined by the standard strength of connection measure using the parameter epsilon. @@ -21,16 +21,16 @@ In the case epsilon = 0.0, (i.e. no weak connections) A is returned. """ - if not isspmatrix_csr(A): raise TypeError('expected csr_matrix') - if epsilon == 0: - A_filtered = A + return A + + if isspmatrix_csr(A): + Sp,Sj,Sx = multigridtools.sa_strong_connections(A.shape[0],epsilon,A.indptr,A.indices,A.data) + return csr_matrix((Sx,Sj,Sp),shape=A.shape) + elif ispmatrix_bsr(A): + raise NotImplementedError,'blocks not handled yet' else: - if blocks is None: - Sp,Sj,Sx = multigridtools.sa_strong_connections(A.shape[0],epsilon,A.indptr,A.indices,A.data) - A_filtered = csr_matrix((Sx,Sj,Sp),A.shape) - else: - raise NotImplementedError,'blocks not handled yet' + return sa_filtered_matrix(csr_matrix(A),epsilon) ## #TODO subtract weak blocks from diagonal blocks? ## num_dofs = A.shape[0] ## num_blocks = blocks.max() + 1 @@ -66,100 +66,94 @@ return csr_matrix((Sx,Sj,Sp),A.shape) -def sa_constant_interpolation(A,epsilon,blocks=None): - if not isspmatrix_csr(A): raise TypeError('expected csr_matrix') +def sa_constant_interpolation(A,epsilon): + """Compute the sparsity pattern of the tentative prolongator + """ + if isspmatrix_csr(A): + S = sa_strong_connections(A,epsilon) - if blocks is not None: - num_dofs = A.shape[0] - num_blocks = blocks.max() + 1 + Pj = multigridtools.sa_get_aggregates(S.shape[0],S.indptr,S.indices) + Pp = numpy.arange(len(Pj)+1) + Px = numpy.ones(len(Pj)) #TODO replace this with something else? + + return csr_matrix((Px,Pj,Pp)) - if num_dofs != len(blocks): - raise ValueError,'improper block specification' + elif isspmatrix_bsr(A): - #print "SA has blocks" - # for non-scalar problems, use pre-defined blocks in aggregation # the strength of connection matrix is based on the Frobenius norms of the blocks + M,N = A.shape + R,C = A.blocksize - B = csr_matrix((ones(num_dofs),blocks,arange(num_dofs + 1)),shape=(num_dofs,num_blocks)) - #1-norms of blocks entries of A - #TODO figure out what to do for blocks here - Block_A = B.T.tocsr() * csr_matrix((abs(A.data),A.indices,A.indptr),shape=A.shape) * B + if R != C: + raise ValueError,'matrix must have square blocks' - S = sa_strong_connections(Block_A,epsilon) + f_norms = (A.data*A.data).reshape(-1,R*C).sum(axis=1) #Frobenius norm of each block + + A = csr_matrix((f_norms,A.indices,A.indptr),shape=(M/R,N/C)) - Pj = multigridtools.sa_get_aggregates(S.shape[0],S.indptr,S.indices) - Pj = Pj[blocks] #expand block aggregates into constituent dofs - Pp = B.indptr - Px = B.data + return sa_constant_interpolation(A,epsilon) else: - S = sa_strong_connections(A,epsilon) + sa_constant_interpolation(csr_matrix(A),epsilon) - Pj = multigridtools.sa_get_aggregates(S.shape[0],S.indptr,S.indices) - Pp = numpy.arange(len(Pj)+1) - Px = numpy.ones(len(Pj)) - - return csr_matrix((Px,Pj,Pp)) - - def sa_fit_candidates(AggOp,candidates,tol=1e-10): if candidates.dtype != 'float32': candidates = asarray(candidates,dtype='float64') - K = candidates.shape[1] # num candidates + K = candidates.shape[1] # number of near-nullspace candidates + blocksize = candidates.shape[0] / AggOp.shape[0] N_fine,N_coarse = AggOp.shape - if K > 1 and candidates.shape[0] == K*N_fine: - #see if fine space has been expanded (all levels except for first) - AggOp = expand_into_blocks(AggOp,K,1).tocsr() - N_fine = K*N_fine + #if blocksize > 1: + # #see if fine space has been expanded (all levels except for first) + # AggOp = expand_into_blocks(AggOp,blocksize,1).tocsr() - R = zeros((N_coarse,K,K)) #storage for coarse candidates + R = zeros((N_coarse,K,K),dtype=candidates.dtype) #storage for coarse candidates candidate_matrices = [] + threshold = tol * abs(candidates).max() # cutoff for small basis functions + for i in range(K): c = candidates[:,i] - c = c[diff(AggOp.indptr) == 1] # eliminate DOFs that aggregation misses + c = c.reshape(-1,blocksize,1)[diff(AggOp.indptr) == 1] # eliminate DOFs that aggregation misses - threshold = tol * abs(c).max() # cutoff for small basis functions + X = bsr_matrix( (c, AggOp.indices, AggOp.indptr), \ + shape=(blocksize*N_fine, N_coarse) ) - X = csr_matrix((c,AggOp.indices,AggOp.indptr),shape=AggOp.shape) - #orthogonalize X against previous for j,A in enumerate(candidate_matrices): - D_AtX = csr_matrix((A.data*X.data,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of A.T * X + #import pdb; pdb.set_trace() + D_AtX = bsr_matrix((A.data*X.data,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of A.T * X R[:,j,i] = D_AtX - X.data -= D_AtX[X.indices] * A.data + X.data -= scale_columns(A,D_AtX).data #normalize X - D_XtX = csr_matrix((X.data**2,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of X.T * X + D_XtX = bsr_matrix((X.data**2,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of X.T * X col_norms = sqrt(D_XtX) mask = col_norms < threshold # set small basis functions to 0 col_norms[mask] = 0 R[:,i,i] = col_norms col_norms = 1.0/col_norms col_norms[mask] = 0 - X.data *= col_norms[X.indices] + scale_columns(X,col_norms,copy=False) candidate_matrices.append(X) # expand AggOp blocks horizontally - Q_indptr = K*AggOp.indptr - Q_indices = (K*AggOp.indices).repeat(K) - for i in range(K): - Q_indices[i::K] += i - Q_data = empty(AggOp.indptr[-1] * K) #if AggOp includes all nodes, then this is (N_fine * K) + Q_indptr = AggOp.indptr + Q_indices = AggOp.indices + Q_data = empty((AggOp.nnz,blocksize,K)) #if AggOp includes all nodes, then this is (N_fine * K) for i,X in enumerate(candidate_matrices): - Q_data[i::K] = X.data - Q = csr_matrix((Q_data,Q_indices,Q_indptr),shape=(N_fine,K*N_coarse)) + Q_data[:,:,i] = X.data.reshape(-1,blocksize) + Q = bsr_matrix((Q_data,Q_indices,Q_indptr),shape=(blocksize*N_fine,K*N_coarse)) R = R.reshape(-1,K) return Q,R -def sa_smoothed_prolongator(A,T,epsilon,omega,blocks=None): +def sa_smoothed_prolongator(A,T,epsilon,omega): """For a given matrix A and tentative prolongator T return the smoothed prolongator P @@ -174,7 +168,7 @@ """ - A_filtered = sa_filtered_matrix(A,epsilon,blocks) #use filtered matrix for anisotropic problems + A_filtered = sa_filtered_matrix(A,epsilon) #use filtered matrix for anisotropic problems D_inv = diag_sparse(1.0/diag_sparse(A_filtered)) D_inv_A = D_inv * A_filtered @@ -185,24 +179,21 @@ return P -def sa_interpolation(A,candidates,epsilon=0.0,omega=4.0/3.0,blocks=None,AggOp=None): - if not isspmatrix_csr(A): raise TypeError('expected csr_matrix') +def sa_interpolation(A,candidates,epsilon=0.0,omega=4.0/3.0,AggOp=None): + if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): + A = csr_matrix(A) + if AggOp is None: - AggOp = sa_constant_interpolation(A,epsilon=epsilon,blocks=blocks) + AggOp = sa_constant_interpolation(A,epsilon=epsilon) else: if not isspmatrix_csr(AggOp): - raise TypeError,'expected csr_matrix for argument AggOp' + AggOp = csr_matrix(AggOp) if A.shape[1] != AggOp.shape[0]: raise ValueError,'incompatible aggregation operator' T,coarse_candidates = sa_fit_candidates(AggOp,candidates) - #T = AggOp #TODO test + P = sa_smoothed_prolongator(A,T,epsilon,omega) + return P,coarse_candidates - P = sa_smoothed_prolongator(A,T,epsilon,omega,blocks) - - if blocks is not None: - blocks = arange(AggOp.shape[1]).repeat(candidates.shape[1]) - - return P,coarse_candidates,blocks Modified: trunk/scipy/sandbox/multigrid/simple_test.py =================================================================== --- trunk/scipy/sandbox/multigrid/simple_test.py 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sandbox/multigrid/simple_test.py 2008-01-12 08:49:56 UTC (rev 3820) @@ -4,10 +4,15 @@ from scipy.sandbox.multigrid.utils import * from time import clock -A = poisson_problem2D(500) +mats = io.loadmat('/home/nathan/Work/ogroup/matrices/elasticity/simple_grid_2d/elasticity_50x50.mat') +A = mats['A'].tobsr(blocksize=(2,2)) +B = mats['B'] +#A = poisson_problem2D(500) +#B = None + start = clock() -sa = smoothed_aggregation_solver(A) +sa = smoothed_aggregation_solver(A,B=B) print "constructed solver in %s seconds" % (clock() - start) b = rand(A.shape[0]) Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-12 08:49:56 UTC (rev 3820) @@ -67,12 +67,12 @@ for epsilon in [0.0,0.1,0.5,1.0]: S_expected = reference_sa_constant_interpolation(A,epsilon) - S_result = sa_constant_interpolation(A,epsilon,blocks=None) + S_result = sa_constant_interpolation(A,epsilon) assert_array_equal(S_result.todense(),S_expected.todense()) - #blocks=1...N should be the same as blocks=None - S_result = sa_constant_interpolation(A,epsilon,blocks=arange(A.shape[0])) - assert_array_equal(S_result.todense(),S_expected.todense()) + #A = A.tobsr( blocksize=(1,1) ) + #S_result = sa_constant_interpolation(A,epsilon) + #assert_array_equal(S_result.todense(),S_expected.todense()) # two aggregates in 1D A = poisson_problem1D(6) @@ -86,18 +86,18 @@ #check simple block examples A = csr_matrix(arange(16).reshape(4,4)) A = A + A.T - blocks = array([0,0,1,1]) + A = A.tobsr(blocksize=(2,2)) - S_result = sa_constant_interpolation(A,epsilon=0.0,blocks=blocks) - S_expected = matrix([1,1,1,1]).T + S_result = sa_constant_interpolation(A,epsilon=0.0) + S_expected = matrix([1,1]).T assert_array_equal(S_result.todense(),S_expected) - S_result = sa_constant_interpolation(A,epsilon=0.5,blocks=blocks) - S_expected = matrix([1,1,1,1]).T + S_result = sa_constant_interpolation(A,epsilon=0.5) + S_expected = matrix([1,1]).T assert_array_equal(S_result.todense(),S_expected) - S_result = sa_constant_interpolation(A,epsilon=2.0,blocks=blocks) - S_expected = matrix([[1,0],[1,0],[0,1],[0,1]]) + S_result = sa_constant_interpolation(A,epsilon=2.0) + S_expected = matrix([[1,0],[0,1]]) assert_array_equal(S_result.todense(),S_expected) @@ -132,27 +132,36 @@ def setUp(self): self.cases = [] - ## tests where AggOp includes all DOFs - #one candidate - #self.cases.append((csr_matrix((ones(5),array([0,0,0,1,1]),arange(6)),shape=(5,2)), ones((5,1)) )) - #self.cases.append((csr_matrix((ones(5),array([1,1,0,0,0]),arange(6)),shape=(5,2)), ones((5,1)) )) - #self.cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), ones((9,1)) )) + ### tests where AggOp includes all DOFs + # one candidate + self.cases.append((csr_matrix((ones(5),array([0,0,0,1,1]),arange(6)),shape=(5,2)), ones((5,1)) )) + self.cases.append((csr_matrix((ones(5),array([1,1,0,0,0]),arange(6)),shape=(5,2)), ones((5,1)) )) + self.cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), ones((9,1)) )) self.cases.append((csr_matrix((ones(9),array([2,1,0,0,1,2,1,0,2]),arange(10)),shape=(9,3)), arange(9).reshape(9,1) )) - #two candidates - #self.cases.append((csr_matrix((ones(4),array([0,0,1,1]),arange(5)),shape=(4,2)), vstack((ones(4),arange(4))).T )) - #self.cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), vstack((ones(9),arange(9))).T )) - #self.cases.append((csr_matrix((ones(9),array([0,0,1,1,2,2,3,3,3]),arange(10)),shape=(9,4)), vstack((ones(9),arange(9))).T )) - ##block candidates - #self.cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), vstack((array([1]*9 + [0]*9),arange(2*9))).T )) - # + # two candidates + self.cases.append((csr_matrix((ones(4),array([0,0,1,1]),arange(5)),shape=(4,2)), vstack((ones(4),arange(4))).T )) + self.cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), vstack((ones(9),arange(9))).T )) + self.cases.append((csr_matrix((ones(9),array([0,0,1,1,2,2,3,3,3]),arange(10)),shape=(9,4)), vstack((ones(9),arange(9))).T )) + + # block aggregates, one candidate + self.cases.append((csr_matrix((ones(3),array([0,1,1]),arange(4)),shape=(3,2)), ones((6,1)) )) + self.cases.append((csr_matrix((ones(3),array([0,1,1]),arange(4)),shape=(3,2)), ones((9,1)) )) + self.cases.append((csr_matrix((ones(5),array([2,0,2,1,1]),arange(6)),shape=(5,3)), ones((10,1)) )) + + # block aggregates, two candidates + self.cases.append((csr_matrix((ones(3),array([0,1,1]),arange(4)),shape=(3,2)), vstack((ones(6),arange(6))).T )) + self.cases.append((csr_matrix((ones(3),array([0,1,1]),arange(4)),shape=(3,2)), vstack((ones(9),arange(9))).T )) + self.cases.append((csr_matrix((ones(5),array([2,0,2,1,1]),arange(6)),shape=(5,3)), vstack((ones(10),arange(10))).T )) + ### tests where AggOp excludes some DOFs - #self.cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), ones((5,1)) )) - #self.cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), vstack((ones(5),arange(5))).T )) + # one candidate + self.cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), ones((5,1)) )) + self.cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), vstack((ones(5),arange(5))).T )) - ## overdetermined blocks - #self.cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), vstack((ones(5),arange(5),arange(5)**2)).T )) - #self.cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9),arange(9)**2)).T )) - #self.cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9))).T )) + # overdetermined blocks + self.cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), vstack((ones(5),arange(5),arange(5)**2)).T )) + self.cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9),arange(9)**2)).T )) + self.cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9))).T )) def check_all_cases(self): """Test case where aggregation includes all fine nodes""" Modified: trunk/scipy/sandbox/multigrid/utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/utils.py 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sandbox/multigrid/utils.py 2008-01-12 08:49:56 UTC (rev 3820) @@ -6,9 +6,10 @@ from scipy import ravel,arange,concatenate,tile,asarray,sqrt,diff, \ rand,zeros,empty,asmatrix,dot from scipy.linalg import norm,eigvals -from scipy.sparse import isspmatrix,isspmatrix_csr,isspmatrix_csc, \ - csr_matrix,csc_matrix,extract_diagonal, \ - coo_matrix +from scipy.sparse import isspmatrix, isspmatrix_csr, isspmatrix_csc, \ + isspmatrix_bsr, csr_matrix, csc_matrix, bsr_matrix, coo_matrix, \ + extract_diagonal +from scipy.sparse.sputils import upcast def approximate_spectral_radius(A,tol=0.1,maxiter=10,symmetric=None): @@ -130,31 +131,83 @@ else: return csr_matrix((asarray(A),arange(len(A)),arange(len(A)+1)),(len(A),len(A))) +def scale_rows(A,v,copy=True): + from scipy.sparse.sparsetools import csr_scale_rows, bsr_scale_rows -def symmetric_rescaling(A): - if not (isspmatrix_csr(A) or isspmatrix_csc(A)): - raise TypeError,'expected csr_matrix or csc_matrix' + v = ravel(v) - if A.shape[0] != A.shape[1]: - raise ValueError,'expected square matrix' + if isspmatrix_csr(A) or isspmatrix_bsr(A): + M,N = A.shape + if M != len(v): + raise ValueError,'scale vector has incompatible shape' - D = diag_sparse(A) - mask = D == 0 + if copy: + A = A.copy() + A.data = asarray(A.data,dtype=upcast(A.dtype,v.dtype)) + else: + v = asarray(v,dtype=A.dtype) - #D[mask] = 0 - D_sqrt = sqrt(abs(D)) - D_sqrt_inv = 1.0/D_sqrt - D_sqrt_inv[mask] = 0 + if isspmatrix_csr(A): + csr_scale_rows(M, N, A.indptr, A.indices, A.data, v) + else: + R,C = A.blocksize + bsr_scale_rows(M/R, N/C, R, C, A.indptr, A.indices, ravel(A.data), v) - Acoo = A.tocoo(copy=False) - data = A.data[:A.nnz] * D_sqrt_inv[Acoo.row] - data *= D_sqrt_inv[Acoo.col] + return A + elif isspmatrix_csc(A): + return scale_columns(A.T,v) + else: + return scale_rows(csr_matrix(A),v) + +def scale_columns(A,v,copy=True): + from scipy.sparse.sparsetools import csr_scale_columns, bsr_scale_columns - DAD = A.__class__((data,A.indices[:A.nnz],A.indptr),shape=A.shape) + v = ravel(v) - return D_sqrt,D_sqrt_inv,DAD + if isspmatrix_csr(A) or isspmatrix_bsr(A): + M,N = A.shape + if N != len(v): + raise ValueError,'scale vector has incompatible shape' + if copy: + A = A.copy() + A.data = asarray(A.data,dtype=upcast(A.dtype,v.dtype)) + else: + v = asarray(v,dtype=A.dtype) + if isspmatrix_csr(A): + csr_scale_columns(M, N, A.indptr, A.indices, A.data, v) + else: + R,C = A.blocksize + bsr_scale_columns(M/R, N/C, R, C, A.indptr, A.indices, ravel(A.data), v) + + return A + elif isspmatrix_csc(A): + return scale_rows(A.T,v) + else: + return scale_rows(csr_matrix(A),v) + +def symmetric_rescaling(A,copy=True): + if isspmatrix_csr(A) or isspmatrix_csc(A) or isspmatrix_bsr(A): + if A.shape[0] != A.shape[1]: + raise ValueError,'expected square matrix' + + D = diag_sparse(A) + mask = D == 0 + + D_sqrt = sqrt(abs(D)) + D_sqrt_inv = 1.0/D_sqrt + D_sqrt_inv[mask] = 0 + + DAD = scale_rows(A,D_sqrt_inv,copy=copy) + DAD = scale_columns(DAD,D_sqrt_inv,copy=False) + + return D_sqrt,D_sqrt_inv,DAD + + else: + return symmetric_rescaling(csr_matrix(A)) + + def hstack_csr(A,B): if not isspmatrix(A) or not isspmatrix(B): raise TypeError,'expected sparse matrix' Modified: trunk/scipy/sparse/sparsetools/sparsetools.h =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.h 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sparse/sparsetools/sparsetools.h 2008-01-12 08:49:56 UTC (rev 3820) @@ -64,7 +64,65 @@ } } +template +void bsr_diagonal(const I n_brow, + const I n_bcol, + const I R, + const I C, + const I Ap[], + const I Aj[], + const T Ax[], + T Yx[]) +{ + const I N = std::min(R*n_brow, C*n_bcol); + const I RC = R*C; + for(I i = 0; i < N; i++){ + Yx[i] = 0; + } + + if ( R == C ){ + //main diagonal with square blocks + const I end = std::min(n_brow,n_bcol); + for(I i = 0; i < end; i++){ + for(I jj = Ap[i]; jj < Ap[i+1]; jj++){ + if (i == Aj[jj]){ + I row = R*i; + const T * val = Ax + RC*jj; + for(I bi = 0; bi < R; bi++){ + Yx[row + bi] = *val; + val += C + 1; + } + } + } + } + } + else + { + //This could be made faster + const I end = (N/R) + (N % R == 0 ? 0 : 1); + for(I i = 0; i < end; i++){ + for(I jj = Ap[i]; jj < Ap[i+1]; jj++){ + const I base_row = R*i; + const I base_col = C*Aj[jj]; + const T * base_val = Ax + RC*jj; + + for(I bi = 0; bi < R; bi++){ + const I row = base_row + bi; + if (row >= N) break; + + for(I bj = 0; bj < C; bj++){ + const I col = base_col + bj; + if (row == col){ + Yx[row] = base_val[bi*C + bj]; + } + } + } + } + } + } +} + /* * Expand a compressed row pointer into a row array * @@ -95,6 +153,110 @@ } /* + * Scale the rows of a CSR matrix *in place* + * + * A[i,:] *= X[i] + * + */ +template +void csr_scale_rows(const I n_row, + const I n_col, + const I Ap[], + const I Aj[], + T Ax[], + const T Xx[]) +{ + for(I i = 0; i < n_row; i++){ + for(I jj = Ap[i]; jj < Ap[i+1]; jj++){ + Ax[jj] *= Xx[i]; + } + } +} + +/* + * Scale the columns of a CSR matrix *in place* + * + * A[:,i] *= X[i] + * + */ +template +void csr_scale_columns(const I n_row, + const I n_col, + const I Ap[], + const I Aj[], + T Ax[], + const T Xx[]) +{ + const I nnz = Ap[n_row]; + for(I i = 0; i < nnz; i++){ + Ax[i] *= Xx[Aj[i]]; + } +} + +/* + * Scale the rows of a BSR matrix *in place* + * + * A[i,:] *= X[i] + * + */ +template +void bsr_scale_rows(const I n_brow, + const I n_bcol, + const I R, + const I C, + const I Ap[], + const I Aj[], + T Ax[], + const T Xx[]) +{ + const I RC = R*C; + for(I i = 0; i < n_brow; i++){ + for(I jj = Ap[i]; jj < Ap[i+1]; jj++){ + for(I bi = 0; bi < R; bi++){ + const T s = Xx[R*i + bi]; + T * block_row = Ax + RC*jj + C*bi; + + for(I bj = 0; bj < C; bj++){ + block_row[bj] *= s; + } + + } + } + } +} + +/* + * Scale the columns of a BSR matrix *in place* + * + * A[:,i] *= X[i] + * + */ +template +void bsr_scale_columns(const I n_brow, + const I n_bcol, + const I R, + const I C, + const I Ap[], + const I Aj[], + T Ax[], + const T Xx[]) +{ + const I bnnz = Ap[n_brow]; + const I RC = R*C; + for(I i = 0; i < bnnz; i++){ + const T * scales = Xx + C*Aj[i] ; + T * block = Ax + RC*i; + + for(I bi = 0; bi < R; bi++){ + for(I bj = 0; bj < C; bj++){ + block[C*bi + bj] *= scales[bj]; + } + } + + } +} + +/* * Compute the number of occupied RxC blocks in a matrix * * Input Arguments: Modified: trunk/scipy/sparse/sparsetools/sparsetools.i =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.i 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sparse/sparsetools/sparsetools.i 2008-01-12 08:49:56 UTC (rev 3820) @@ -191,13 +191,23 @@ /* - * diag(CSR) and diag(CSC) + * diag(A) */ INSTANTIATE_ALL(csr_diagonal) INSTANTIATE_ALL(csc_diagonal) +INSTANTIATE_ALL(bsr_diagonal) /* + * scale columns + */ +INSTANTIATE_ALL(csr_scale_rows) +INSTANTIATE_ALL(csr_scale_columns) +INSTANTIATE_ALL(bsr_scale_rows) +INSTANTIATE_ALL(bsr_scale_columns) + + +/* * CSR->CSC or CSC->CSR or CSR = CSR^T or CSC = CSC^T */ INSTANTIATE_ALL(csr_tocsc) Modified: trunk/scipy/sparse/sparsetools/sparsetools.py =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.py 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sparse/sparsetools/sparsetools.py 2008-01-12 08:49:56 UTC (rev 3820) @@ -134,6 +134,163 @@ """ return _sparsetools.csc_diagonal(*args) +def bsr_diagonal(*args): + """ + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + signed char Ax, signed char Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned char Ax, unsigned char Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + short Ax, short Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned short Ax, unsigned short Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + int Ax, int Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned int Ax, unsigned int Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + long long Ax, long long Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned long long Ax, unsigned long long Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + float Ax, float Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + double Ax, double Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + long double Ax, long double Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_cfloat_wrapper Ax, npy_cfloat_wrapper Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_cdouble_wrapper Ax, npy_cdouble_wrapper Yx) + bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_clongdouble_wrapper Ax, npy_clongdouble_wrapper Yx) + """ + return _sparsetools.bsr_diagonal(*args) + +def csr_scale_rows(*args): + """ + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, signed char Ax, + signed char Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, unsigned char Ax, + unsigned char Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, short Ax, short Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, unsigned short Ax, + unsigned short Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, int Ax, int Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, unsigned int Ax, + unsigned int Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, long long Ax, + long long Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, unsigned long long Ax, + unsigned long long Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, float Ax, float Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, double Ax, double Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, long double Ax, + long double Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, npy_cfloat_wrapper Ax, + npy_cfloat_wrapper Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, npy_cdouble_wrapper Ax, + npy_cdouble_wrapper Xx) + csr_scale_rows(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax, + npy_clongdouble_wrapper Xx) + """ + return _sparsetools.csr_scale_rows(*args) + +def csr_scale_columns(*args): + """ + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, signed char Ax, + signed char Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned char Ax, + unsigned char Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, short Ax, short Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned short Ax, + unsigned short Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, int Ax, int Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned int Ax, + unsigned int Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, long long Ax, + long long Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned long long Ax, + unsigned long long Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, float Ax, float Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, double Ax, double Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, long double Ax, + long double Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, npy_cfloat_wrapper Ax, + npy_cfloat_wrapper Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, npy_cdouble_wrapper Ax, + npy_cdouble_wrapper Xx) + csr_scale_columns(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax, + npy_clongdouble_wrapper Xx) + """ + return _sparsetools.csr_scale_columns(*args) + +def bsr_scale_rows(*args): + """ + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + signed char Ax, signed char Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned char Ax, unsigned char Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + short Ax, short Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned short Ax, unsigned short Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + int Ax, int Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned int Ax, unsigned int Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + long long Ax, long long Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned long long Ax, unsigned long long Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + float Ax, float Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + double Ax, double Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + long double Ax, long double Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_cfloat_wrapper Ax, npy_cfloat_wrapper Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_cdouble_wrapper Ax, npy_cdouble_wrapper Xx) + bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_clongdouble_wrapper Ax, npy_clongdouble_wrapper Xx) + """ + return _sparsetools.bsr_scale_rows(*args) + +def bsr_scale_columns(*args): + """ + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + signed char Ax, signed char Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned char Ax, unsigned char Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + short Ax, short Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned short Ax, unsigned short Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + int Ax, int Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned int Ax, unsigned int Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + long long Ax, long long Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + unsigned long long Ax, unsigned long long Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + float Ax, float Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + double Ax, double Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + long double Ax, long double Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_cfloat_wrapper Ax, npy_cfloat_wrapper Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_cdouble_wrapper Ax, npy_cdouble_wrapper Xx) + bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, + npy_clongdouble_wrapper Ax, npy_clongdouble_wrapper Xx) + """ + return _sparsetools.bsr_scale_columns(*args) + def csr_tocsc(*args): """ csr_tocsc(int n_row, int n_col, int Ap, int Aj, signed char Ax, Modified: trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-01-12 08:49:56 UTC (rev 3820) @@ -6888,6 +6888,10731 @@ } +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + signed char *arg7 ; + signed char *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_BYTE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (signed char*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_BYTE); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (signed char*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(signed char const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned char *arg7 ; + unsigned char *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_UBYTE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (unsigned char*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_UBYTE); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (unsigned char*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(unsigned char const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + short *arg7 ; + short *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_SHORT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (short*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_SHORT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (short*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(short const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned short *arg7 ; + unsigned short *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_USHORT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (unsigned short*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_USHORT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (unsigned short*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(unsigned short const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + int *arg7 ; + int *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_INT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (int*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(int const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned int *arg7 ; + unsigned int *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_UINT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (unsigned int*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_UINT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (unsigned int*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(unsigned int const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + long long *arg7 ; + long long *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_LONGLONG, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (long long*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_LONGLONG); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (long long*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(long long const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned long long *arg7 ; + unsigned long long *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_ULONGLONG, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (unsigned long long*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_ULONGLONG); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (unsigned long long*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(unsigned long long const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + float *arg7 ; + float *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_FLOAT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (float*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_FLOAT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (float*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(float const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + double *arg7 ; + double *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_DOUBLE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (double*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_DOUBLE); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (double*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(double const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + long double *arg7 ; + long double *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_LONGDOUBLE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (long double*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_LONGDOUBLE); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (long double*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(long double const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_cfloat_wrapper *arg7 ; + npy_cfloat_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_CFLOAT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (npy_cfloat_wrapper*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_CFLOAT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (npy_cfloat_wrapper*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(npy_cfloat_wrapper const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_cdouble_wrapper *arg7 ; + npy_cdouble_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_CDOUBLE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (npy_cdouble_wrapper*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_CDOUBLE); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (npy_cdouble_wrapper*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(npy_cdouble_wrapper const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_clongdouble_wrapper *arg7 ; + npy_clongdouble_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_diagonal",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_diagonal" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_diagonal" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_diagonal" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_diagonal" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_CLONGDOUBLE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (npy_clongdouble_wrapper*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_CLONGDOUBLE); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (npy_clongdouble_wrapper*) array_data(temp8); + } + bsr_diagonal(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(npy_clongdouble_wrapper const (*))arg7,arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_diagonal(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[9]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 8); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_1(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_2(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_3(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_4(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_5(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_6(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_7(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_8(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_9(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_10(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_11(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_12(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_13(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_diagonal__SWIG_14(self, args); + } + } + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'bsr_diagonal'.\n Possible C/C++ prototypes are:\n"" bsr_diagonal<(int,signed char)>(int const,int const,int const,int const,int const [],int const [],signed char const [],signed char [])\n"" bsr_diagonal<(int,unsigned char)>(int const,int const,int const,int const,int const [],int const [],unsigned char const [],unsigned char [])\n"" bsr_diagonal<(int,short)>(int const,int const,int const,int const,int const [],int const [],short const [],short [])\n"" bsr_diagonal<(int,unsigned short)>(int const,int const,int const,int const,int const [],int const [],unsigned short const [],unsigned short [])\n"" bsr_diagonal<(int,int)>(int const,int const,int const,int const,int const [],int const [],int const [],int [])\n"" bsr_diagonal<(int,unsigned int)>(int const,int const,int const,int const,int const [],int const [],unsigned int const [],unsigned int [])\n"" bsr_diagonal<(int,long long)>(int const,int const,int const,int const,int const [],int const [],long long const [],long long [])\n"" bsr_diagonal<(int,unsigned long long)>(int const,int const,int const,int const,int const [],int const [],unsigned long long const [],unsigned long long [])\n"" bsr_diagonal<(int,float)>(int const,int const,int const,int const,int const [],int const [],float const [],float [])\n"" bsr_diagonal<(int,double)>(int const,int const,int const,int const,int const [],int const [],double const [],double [])\n"" bsr_diagonal<(int,long double)>(int const,int const,int const,int const,int const [],int const [],long double const [],long double [])\n"" bsr_diagonal<(int,npy_cfloat_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_cfloat_wrapper const [],npy_cfloat_wrapper [])\n"" bsr_diagonal<(int,npy_cdouble_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_cdouble_wrapper const [],npy_cdouble_wrapper [])\n"" bsr_diagonal<(int,npy_clongdouble_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_clongdouble_wrapper const [],npy_clongdouble_wrapper [])\n"); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + signed char *arg5 ; + signed char *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_BYTE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (signed char*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_BYTE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (signed char*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(signed char const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned char *arg5 ; + unsigned char *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_UBYTE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned char*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_UBYTE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned char*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(unsigned char const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + short *arg5 ; + short *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_SHORT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (short*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_SHORT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (short*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(short const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned short *arg5 ; + unsigned short *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_USHORT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned short*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_USHORT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned short*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(unsigned short const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + int *arg5 ; + int *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_INT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (int*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(int const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned int *arg5 ; + unsigned int *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_UINT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned int*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_UINT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned int*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(unsigned int const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + long long *arg5 ; + long long *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_LONGLONG); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (long long*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_LONGLONG, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (long long*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(long long const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned long long *arg5 ; + unsigned long long *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_ULONGLONG); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned long long*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_ULONGLONG, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned long long*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(unsigned long long const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + float *arg5 ; + float *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_FLOAT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (float*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_FLOAT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (float*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(float const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + double *arg5 ; + double *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_DOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (double*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_DOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (double*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(double const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + long double *arg5 ; + long double *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_LONGDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (long double*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_LONGDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (long double*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(long double const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_cfloat_wrapper *arg5 ; + npy_cfloat_wrapper *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CFLOAT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_cfloat_wrapper*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CFLOAT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_cfloat_wrapper*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(npy_cfloat_wrapper const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_cdouble_wrapper *arg5 ; + npy_cdouble_wrapper *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_cdouble_wrapper*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_cdouble_wrapper*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(npy_cdouble_wrapper const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_clongdouble_wrapper *arg5 ; + npy_clongdouble_wrapper *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CLONGDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_clongdouble_wrapper*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CLONGDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_clongdouble_wrapper*) array6->data; + } + csr_scale_rows(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(npy_clongdouble_wrapper const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_rows(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[7]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 6); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_1(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_2(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_3(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_4(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_5(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_6(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_7(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_8(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_9(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_10(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_11(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_12(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_13(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_rows__SWIG_14(self, args); + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'csr_scale_rows'.\n Possible C/C++ prototypes are:\n"" csr_scale_rows<(int,signed char)>(int const,int const,int const [],int const [],signed char [],signed char const [])\n"" csr_scale_rows<(int,unsigned char)>(int const,int const,int const [],int const [],unsigned char [],unsigned char const [])\n"" csr_scale_rows<(int,short)>(int const,int const,int const [],int const [],short [],short const [])\n"" csr_scale_rows<(int,unsigned short)>(int const,int const,int const [],int const [],unsigned short [],unsigned short const [])\n"" csr_scale_rows<(int,int)>(int const,int const,int const [],int const [],int [],int const [])\n"" csr_scale_rows<(int,unsigned int)>(int const,int const,int const [],int const [],unsigned int [],unsigned int const [])\n"" csr_scale_rows<(int,long long)>(int const,int const,int const [],int const [],long long [],long long const [])\n"" csr_scale_rows<(int,unsigned long long)>(int const,int const,int const [],int const [],unsigned long long [],unsigned long long const [])\n"" csr_scale_rows<(int,float)>(int const,int const,int const [],int const [],float [],float const [])\n"" csr_scale_rows<(int,double)>(int const,int const,int const [],int const [],double [],double const [])\n"" csr_scale_rows<(int,long double)>(int const,int const,int const [],int const [],long double [],long double const [])\n"" csr_scale_rows<(int,npy_cfloat_wrapper)>(int const,int const,int const [],int const [],npy_cfloat_wrapper [],npy_cfloat_wrapper const [])\n"" csr_scale_rows<(int,npy_cdouble_wrapper)>(int const,int const,int const [],int const [],npy_cdouble_wrapper [],npy_cdouble_wrapper const [])\n"" csr_scale_rows<(int,npy_clongdouble_wrapper)>(int const,int const,int const [],int const [],npy_clongdouble_wrapper [],npy_clongdouble_wrapper const [])\n"); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + signed char *arg5 ; + signed char *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_BYTE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (signed char*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_BYTE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (signed char*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(signed char const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned char *arg5 ; + unsigned char *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_UBYTE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned char*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_UBYTE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned char*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(unsigned char const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + short *arg5 ; + short *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_SHORT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (short*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_SHORT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (short*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(short const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned short *arg5 ; + unsigned short *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_USHORT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned short*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_USHORT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned short*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(unsigned short const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + int *arg5 ; + int *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_INT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (int*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(int const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned int *arg5 ; + unsigned int *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_UINT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned int*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_UINT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned int*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(unsigned int const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + long long *arg5 ; + long long *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_LONGLONG); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (long long*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_LONGLONG, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (long long*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(long long const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + unsigned long long *arg5 ; + unsigned long long *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_ULONGLONG); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (unsigned long long*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_ULONGLONG, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned long long*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(unsigned long long const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + float *arg5 ; + float *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_FLOAT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (float*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_FLOAT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (float*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(float const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + double *arg5 ; + double *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_DOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (double*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_DOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (double*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(double const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + long double *arg5 ; + long double *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_LONGDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (long double*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_LONGDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (long double*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(long double const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_cfloat_wrapper *arg5 ; + npy_cfloat_wrapper *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CFLOAT); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_cfloat_wrapper*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CFLOAT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_cfloat_wrapper*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(npy_cfloat_wrapper const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_cdouble_wrapper *arg5 ; + npy_cdouble_wrapper *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_cdouble_wrapper*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_cdouble_wrapper*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(npy_cdouble_wrapper const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int *arg3 ; + int *arg4 ; + npy_clongdouble_wrapper *arg5 ; + npy_clongdouble_wrapper *arg6 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyArrayObject *array3 = NULL ; + int is_new_object3 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *temp5 = NULL ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOO:csr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + npy_intp size[1] = { + -1 + }; + array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); + if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) + || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; + + arg3 = (int*) array3->data; + } + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + temp5 = obj_to_array_no_conversion(obj4,PyArray_CLONGDOUBLE); + if (!temp5 || !require_contiguous(temp5) || !require_native(temp5)) SWIG_fail; + arg5 = (npy_clongdouble_wrapper*) array_data(temp5); + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CLONGDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_clongdouble_wrapper*) array6->data; + } + csr_scale_columns(arg1,arg2,(int const (*))arg3,(int const (*))arg4,arg5,(npy_clongdouble_wrapper const (*))arg6); + resultobj = SWIG_Py_Void(); + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object3 && array3) Py_DECREF(array3); + } + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_scale_columns(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[7]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 6); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_1(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_2(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_3(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_4(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_5(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_6(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_7(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_8(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_9(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_10(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_11(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_12(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_13(self, args); + } + } + } + } + } + } + } + if (argc == 6) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[2]) && PyArray_CanCastSafely(PyArray_TYPE(argv[2]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_scale_columns__SWIG_14(self, args); + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'csr_scale_columns'.\n Possible C/C++ prototypes are:\n"" csr_scale_columns<(int,signed char)>(int const,int const,int const [],int const [],signed char [],signed char const [])\n"" csr_scale_columns<(int,unsigned char)>(int const,int const,int const [],int const [],unsigned char [],unsigned char const [])\n"" csr_scale_columns<(int,short)>(int const,int const,int const [],int const [],short [],short const [])\n"" csr_scale_columns<(int,unsigned short)>(int const,int const,int const [],int const [],unsigned short [],unsigned short const [])\n"" csr_scale_columns<(int,int)>(int const,int const,int const [],int const [],int [],int const [])\n"" csr_scale_columns<(int,unsigned int)>(int const,int const,int const [],int const [],unsigned int [],unsigned int const [])\n"" csr_scale_columns<(int,long long)>(int const,int const,int const [],int const [],long long [],long long const [])\n"" csr_scale_columns<(int,unsigned long long)>(int const,int const,int const [],int const [],unsigned long long [],unsigned long long const [])\n"" csr_scale_columns<(int,float)>(int const,int const,int const [],int const [],float [],float const [])\n"" csr_scale_columns<(int,double)>(int const,int const,int const [],int const [],double [],double const [])\n"" csr_scale_columns<(int,long double)>(int const,int const,int const [],int const [],long double [],long double const [])\n"" csr_scale_columns<(int,npy_cfloat_wrapper)>(int const,int const,int const [],int const [],npy_cfloat_wrapper [],npy_cfloat_wrapper const [])\n"" csr_scale_columns<(int,npy_cdouble_wrapper)>(int const,int const,int const [],int const [],npy_cdouble_wrapper [],npy_cdouble_wrapper const [])\n"" csr_scale_columns<(int,npy_clongdouble_wrapper)>(int const,int const,int const [],int const [],npy_clongdouble_wrapper [],npy_clongdouble_wrapper const [])\n"); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + signed char *arg7 ; + signed char *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_BYTE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (signed char*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_BYTE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (signed char*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(signed char const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned char *arg7 ; + unsigned char *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_UBYTE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned char*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_UBYTE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (unsigned char*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(unsigned char const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + short *arg7 ; + short *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_SHORT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (short*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_SHORT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (short*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(short const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned short *arg7 ; + unsigned short *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_USHORT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned short*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_USHORT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (unsigned short*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(unsigned short const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + int *arg7 ; + int *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_INT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (int*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_INT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (int*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(int const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned int *arg7 ; + unsigned int *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_UINT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned int*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_UINT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (unsigned int*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(unsigned int const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + long long *arg7 ; + long long *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_LONGLONG); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (long long*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_LONGLONG, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (long long*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(long long const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned long long *arg7 ; + unsigned long long *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_ULONGLONG); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned long long*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_ULONGLONG, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (unsigned long long*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(unsigned long long const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + float *arg7 ; + float *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_FLOAT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (float*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_FLOAT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (float*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(float const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + double *arg7 ; + double *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_DOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (double*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_DOUBLE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (double*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(double const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + long double *arg7 ; + long double *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_LONGDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (long double*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_LONGDOUBLE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (long double*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(long double const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_cfloat_wrapper *arg7 ; + npy_cfloat_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CFLOAT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_cfloat_wrapper*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_CFLOAT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (npy_cfloat_wrapper*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(npy_cfloat_wrapper const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_cdouble_wrapper *arg7 ; + npy_cdouble_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_cdouble_wrapper*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_CDOUBLE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (npy_cdouble_wrapper*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(npy_cdouble_wrapper const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_clongdouble_wrapper *arg7 ; + npy_clongdouble_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_rows",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_rows" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_rows" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_rows" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_rows" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CLONGDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_clongdouble_wrapper*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_CLONGDOUBLE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (npy_clongdouble_wrapper*) array8->data; + } + bsr_scale_rows(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(npy_clongdouble_wrapper const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_rows(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[9]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 8); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_1(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_2(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_3(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_4(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_5(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_6(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_7(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_8(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_9(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_10(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_11(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_12(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_13(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_rows__SWIG_14(self, args); + } + } + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'bsr_scale_rows'.\n Possible C/C++ prototypes are:\n"" bsr_scale_rows<(int,signed char)>(int const,int const,int const,int const,int const [],int const [],signed char [],signed char const [])\n"" bsr_scale_rows<(int,unsigned char)>(int const,int const,int const,int const,int const [],int const [],unsigned char [],unsigned char const [])\n"" bsr_scale_rows<(int,short)>(int const,int const,int const,int const,int const [],int const [],short [],short const [])\n"" bsr_scale_rows<(int,unsigned short)>(int const,int const,int const,int const,int const [],int const [],unsigned short [],unsigned short const [])\n"" bsr_scale_rows<(int,int)>(int const,int const,int const,int const,int const [],int const [],int [],int const [])\n"" bsr_scale_rows<(int,unsigned int)>(int const,int const,int const,int const,int const [],int const [],unsigned int [],unsigned int const [])\n"" bsr_scale_rows<(int,long long)>(int const,int const,int const,int const,int const [],int const [],long long [],long long const [])\n"" bsr_scale_rows<(int,unsigned long long)>(int const,int const,int const,int const,int const [],int const [],unsigned long long [],unsigned long long const [])\n"" bsr_scale_rows<(int,float)>(int const,int const,int const,int const,int const [],int const [],float [],float const [])\n"" bsr_scale_rows<(int,double)>(int const,int const,int const,int const,int const [],int const [],double [],double const [])\n"" bsr_scale_rows<(int,long double)>(int const,int const,int const,int const,int const [],int const [],long double [],long double const [])\n"" bsr_scale_rows<(int,npy_cfloat_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_cfloat_wrapper [],npy_cfloat_wrapper const [])\n"" bsr_scale_rows<(int,npy_cdouble_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_cdouble_wrapper [],npy_cdouble_wrapper const [])\n"" bsr_scale_rows<(int,npy_clongdouble_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_clongdouble_wrapper [],npy_clongdouble_wrapper const [])\n"); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + signed char *arg7 ; + signed char *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_BYTE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (signed char*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_BYTE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (signed char*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(signed char const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned char *arg7 ; + unsigned char *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_UBYTE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned char*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_UBYTE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (unsigned char*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(unsigned char const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + short *arg7 ; + short *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_SHORT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (short*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_SHORT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (short*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(short const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned short *arg7 ; + unsigned short *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_USHORT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned short*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_USHORT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (unsigned short*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(unsigned short const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + int *arg7 ; + int *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_INT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (int*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_INT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (int*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(int const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned int *arg7 ; + unsigned int *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_UINT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned int*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_UINT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (unsigned int*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(unsigned int const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + long long *arg7 ; + long long *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_LONGLONG); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (long long*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_LONGLONG, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (long long*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(long long const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned long long *arg7 ; + unsigned long long *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_ULONGLONG); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned long long*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_ULONGLONG, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (unsigned long long*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(unsigned long long const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + float *arg7 ; + float *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_FLOAT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (float*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_FLOAT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (float*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(float const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + double *arg7 ; + double *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_DOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (double*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_DOUBLE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (double*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(double const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + long double *arg7 ; + long double *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_LONGDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (long double*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_LONGDOUBLE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (long double*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(long double const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_cfloat_wrapper *arg7 ; + npy_cfloat_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CFLOAT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_cfloat_wrapper*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_CFLOAT, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (npy_cfloat_wrapper*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(npy_cfloat_wrapper const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_cdouble_wrapper *arg7 ; + npy_cdouble_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_cdouble_wrapper*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_CDOUBLE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (npy_cdouble_wrapper*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(npy_cdouble_wrapper const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_clongdouble_wrapper *arg7 ; + npy_clongdouble_wrapper *arg8 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyArrayObject *array8 = NULL ; + int is_new_object8 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:bsr_scale_columns",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "bsr_scale_columns" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "bsr_scale_columns" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "bsr_scale_columns" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "bsr_scale_columns" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CLONGDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_clongdouble_wrapper*) array_data(temp7); + } + { + npy_intp size[1] = { + -1 + }; + array8 = obj_to_array_contiguous_allow_conversion(obj7, PyArray_CLONGDOUBLE, &is_new_object8); + if (!array8 || !require_dimensions(array8,1) || !require_size(array8,size,1) + || !require_contiguous(array8) || !require_native(array8)) SWIG_fail; + + arg8 = (npy_clongdouble_wrapper*) array8->data; + } + bsr_scale_columns(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,arg7,(npy_clongdouble_wrapper const (*))arg8); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object8 && array8) Py_DECREF(array8); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_bsr_scale_columns(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[9]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 8); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_1(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_2(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_3(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_4(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_5(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_6(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_7(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_8(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_9(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_10(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_11(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_12(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_13(self, args); + } + } + } + } + } + } + } + } + } + if (argc == 8) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_bsr_scale_columns__SWIG_14(self, args); + } + } + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'bsr_scale_columns'.\n Possible C/C++ prototypes are:\n"" bsr_scale_columns<(int,signed char)>(int const,int const,int const,int const,int const [],int const [],signed char [],signed char const [])\n"" bsr_scale_columns<(int,unsigned char)>(int const,int const,int const,int const,int const [],int const [],unsigned char [],unsigned char const [])\n"" bsr_scale_columns<(int,short)>(int const,int const,int const,int const,int const [],int const [],short [],short const [])\n"" bsr_scale_columns<(int,unsigned short)>(int const,int const,int const,int const,int const [],int const [],unsigned short [],unsigned short const [])\n"" bsr_scale_columns<(int,int)>(int const,int const,int const,int const,int const [],int const [],int [],int const [])\n"" bsr_scale_columns<(int,unsigned int)>(int const,int const,int const,int const,int const [],int const [],unsigned int [],unsigned int const [])\n"" bsr_scale_columns<(int,long long)>(int const,int const,int const,int const,int const [],int const [],long long [],long long const [])\n"" bsr_scale_columns<(int,unsigned long long)>(int const,int const,int const,int const,int const [],int const [],unsigned long long [],unsigned long long const [])\n"" bsr_scale_columns<(int,float)>(int const,int const,int const,int const,int const [],int const [],float [],float const [])\n"" bsr_scale_columns<(int,double)>(int const,int const,int const,int const,int const [],int const [],double [],double const [])\n"" bsr_scale_columns<(int,long double)>(int const,int const,int const,int const,int const [],int const [],long double [],long double const [])\n"" bsr_scale_columns<(int,npy_cfloat_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_cfloat_wrapper [],npy_cfloat_wrapper const [])\n"" bsr_scale_columns<(int,npy_cdouble_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_cdouble_wrapper [],npy_cdouble_wrapper const [])\n"" bsr_scale_columns<(int,npy_clongdouble_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_clongdouble_wrapper [],npy_clongdouble_wrapper const [])\n"); + return NULL; +} + + SWIGINTERN PyObject *_wrap_csr_tocsc__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int arg1 ; @@ -82565,6 +93290,148 @@ "csc_diagonal(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax, \n" " npy_clongdouble_wrapper Yx)\n" ""}, + { (char *)"bsr_diagonal", _wrap_bsr_diagonal, METH_VARARGS, (char *)"\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " signed char Ax, signed char Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned char Ax, unsigned char Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " short Ax, short Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned short Ax, unsigned short Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " int Ax, int Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned int Ax, unsigned int Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " long long Ax, long long Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned long long Ax, unsigned long long Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " float Ax, float Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " double Ax, double Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " long double Ax, long double Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_cfloat_wrapper Ax, npy_cfloat_wrapper Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_cdouble_wrapper Ax, npy_cdouble_wrapper Yx)\n" + "bsr_diagonal(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_clongdouble_wrapper Ax, npy_clongdouble_wrapper Yx)\n" + ""}, + { (char *)"csr_scale_rows", _wrap_csr_scale_rows, METH_VARARGS, (char *)"\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, signed char Ax, \n" + " signed char Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, unsigned char Ax, \n" + " unsigned char Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, short Ax, short Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, unsigned short Ax, \n" + " unsigned short Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, int Ax, int Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, unsigned int Ax, \n" + " unsigned int Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, long long Ax, \n" + " long long Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, unsigned long long Ax, \n" + " unsigned long long Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, float Ax, float Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, double Ax, double Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, long double Ax, \n" + " long double Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, npy_cfloat_wrapper Ax, \n" + " npy_cfloat_wrapper Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, npy_cdouble_wrapper Ax, \n" + " npy_cdouble_wrapper Xx)\n" + "csr_scale_rows(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax, \n" + " npy_clongdouble_wrapper Xx)\n" + ""}, + { (char *)"csr_scale_columns", _wrap_csr_scale_columns, METH_VARARGS, (char *)"\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, signed char Ax, \n" + " signed char Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned char Ax, \n" + " unsigned char Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, short Ax, short Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned short Ax, \n" + " unsigned short Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, int Ax, int Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned int Ax, \n" + " unsigned int Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, long long Ax, \n" + " long long Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned long long Ax, \n" + " unsigned long long Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, float Ax, float Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, double Ax, double Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, long double Ax, \n" + " long double Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, npy_cfloat_wrapper Ax, \n" + " npy_cfloat_wrapper Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, npy_cdouble_wrapper Ax, \n" + " npy_cdouble_wrapper Xx)\n" + "csr_scale_columns(int n_row, int n_col, int Ap, int Aj, npy_clongdouble_wrapper Ax, \n" + " npy_clongdouble_wrapper Xx)\n" + ""}, + { (char *)"bsr_scale_rows", _wrap_bsr_scale_rows, METH_VARARGS, (char *)"\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " signed char Ax, signed char Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned char Ax, unsigned char Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " short Ax, short Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned short Ax, unsigned short Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " int Ax, int Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned int Ax, unsigned int Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " long long Ax, long long Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned long long Ax, unsigned long long Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " float Ax, float Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " double Ax, double Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " long double Ax, long double Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_cfloat_wrapper Ax, npy_cfloat_wrapper Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_cdouble_wrapper Ax, npy_cdouble_wrapper Xx)\n" + "bsr_scale_rows(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_clongdouble_wrapper Ax, npy_clongdouble_wrapper Xx)\n" + ""}, + { (char *)"bsr_scale_columns", _wrap_bsr_scale_columns, METH_VARARGS, (char *)"\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " signed char Ax, signed char Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned char Ax, unsigned char Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " short Ax, short Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned short Ax, unsigned short Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " int Ax, int Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned int Ax, unsigned int Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " long long Ax, long long Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " unsigned long long Ax, unsigned long long Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " float Ax, float Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " double Ax, double Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " long double Ax, long double Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_cfloat_wrapper Ax, npy_cfloat_wrapper Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_cdouble_wrapper Ax, npy_cdouble_wrapper Xx)\n" + "bsr_scale_columns(int n_brow, int n_bcol, int R, int C, int Ap, int Aj, \n" + " npy_clongdouble_wrapper Ax, npy_clongdouble_wrapper Xx)\n" + ""}, { (char *)"csr_tocsc", _wrap_csr_tocsc, METH_VARARGS, (char *)"\n" "csr_tocsc(int n_row, int n_col, int Ap, int Aj, signed char Ax, \n" " int Bp, int Bi, signed char Bx)\n" Modified: trunk/scipy/sparse/spfuncs.py =================================================================== --- trunk/scipy/sparse/spfuncs.py 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sparse/spfuncs.py 2008-01-12 08:49:56 UTC (rev 3820) @@ -3,11 +3,12 @@ __all__ = ['extract_diagonal','count_blocks','estimate_blocksize'] -from numpy import empty +from numpy import empty, ravel from base import isspmatrix from csr import isspmatrix_csr, csr_matrix from csc import isspmatrix_csc +from bsr import isspmatrix_bsr from sputils import upcast import sparsetools @@ -21,12 +22,16 @@ y = empty( min(A.shape), dtype=upcast(A.dtype) ) fn(A.shape[0],A.shape[1],A.indptr,A.indices,A.data,y) return y - elif isspmatrix(A): - return extract_diagonal(A.tocsr()) + elif isspmatrix_bsr(A): + M,N = A.shape + R,C = A.blocksize + y = empty( min(M,N), dtype=upcast(A.dtype) ) + fn = sparsetools.bsr_diagonal(M/R, N/C, R, C, \ + A.indptr, A.indices, ravel(A.data), y) + return y else: - raise ValueError,'expected sparse matrix' + return extract_diagonal(csr_matrix(A)) - def estimate_blocksize(A,efficiency=0.7): """Attempt to determine the blocksize of a sparse matrix Modified: trunk/scipy/sparse/tests/test_spfuncs.py =================================================================== --- trunk/scipy/sparse/tests/test_spfuncs.py 2008-01-12 07:24:52 UTC (rev 3819) +++ trunk/scipy/sparse/tests/test_spfuncs.py 2008-01-12 08:49:56 UTC (rev 3820) @@ -1,12 +1,86 @@ -from numpy import array, kron +from numpy import array, kron, diag, matrix from numpy.testing import * set_package_path() from scipy.sparse.spfuncs import * -from scipy.sparse import csr_matrix, csc_matrix +from scipy.sparse import csr_matrix, csc_matrix, bsr_matrix +from scipy.sparse.sparsetools import csr_scale_rows, csr_scale_columns, \ + bsr_scale_rows, bsr_scale_columns restore_path() class TestSparseFunctions(NumpyTestCase): + def check_scale_rows_and_cols(self): + D = matrix([[1,0,0,2,3], + [0,4,0,5,0], + [0,0,6,7,0]]) + + + #TODO expose through function + S = csr_matrix(D) + v = array([1,2,3]) + csr_scale_rows(3,5,S.indptr,S.indices,S.data,v) + assert_equal(S.todense(), diag(v)*D ) + + S = csr_matrix(D) + v = array([1,2,3,4,5]) + csr_scale_columns(3,5,S.indptr,S.indices,S.data,v) + assert_equal(S.todense(), D*diag(v) ) + + # blocks + E = kron(D,[[1,2],[3,4]]) + S = bsr_matrix(E,blocksize=(2,2)) + v = array([1,2,3,4,5,6]) + bsr_scale_rows(3,5,2,2,S.indptr,S.indices,S.data,v) + assert_equal(S.todense(), diag(v)*E ) + + S = bsr_matrix(E,blocksize=(2,2)) + v = array([1,2,3,4,5,6,7,8,9,10]) + bsr_scale_columns(3,5,2,2,S.indptr,S.indices,S.data,v) + assert_equal(S.todense(), E*diag(v) ) + + E = kron(D,[[1,2,3],[4,5,6]]) + S = bsr_matrix(E,blocksize=(2,3)) + v = array([1,2,3,4,5,6]) + bsr_scale_rows(3,5,2,3,S.indptr,S.indices,S.data,v) + assert_equal(S.todense(), diag(v)*E ) + + S = bsr_matrix(E,blocksize=(2,3)) + v = array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) + bsr_scale_columns(3,5,2,3,S.indptr,S.indices,S.data,v) + assert_equal(S.todense(), E*diag(v) ) + + + + def check_extract_diagonal(self): + mats = [] + mats.append( [[1,0,2]] ) + mats.append( [[1],[0],[2]] ) + mats.append( [[0,1],[0,2],[0,3]] ) + mats.append( [[0,0,1],[0,0,2],[0,3,0]] ) + + mats.append( kron(mats[0],[[1,2]]) ) + mats.append( kron(mats[0],[[1],[2]]) ) + mats.append( kron(mats[1],[[1,2],[3,4]]) ) + mats.append( kron(mats[2],[[1,2],[3,4]]) ) + mats.append( kron(mats[3],[[1,2],[3,4]]) ) + + for m in mats: + expected = diag(m) + assert_equal(extract_diagonal(m),expected) + assert_equal(extract_diagonal(csr_matrix(m)),expected) + assert_equal(extract_diagonal(csc_matrix(m)),expected) + + for m in mats: + m = array(m) + M,N = m.shape + expected = diag(m) + for R in range(1,M+1): + for C in range(1,N+1): + if M % R == 0 and N % C == 0: + result = extract_diagonal( bsr_matrix(m,blocksize=(R,C)) ) + assert_equal(result,expected) + + def check_estimate_blocksize(self): mats = [] From scipy-svn at scipy.org Sat Jan 12 04:23:52 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 03:23:52 -0600 (CST) Subject: [Scipy-svn] r3821 - trunk/scipy/sandbox/cdavid/tests Message-ID: <20080112092352.2FDEE39C03E@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-12 03:23:49 -0600 (Sat, 12 Jan 2008) New Revision: 3821 Modified: trunk/scipy/sandbox/cdavid/tests/test_autocorr.py trunk/scipy/sandbox/cdavid/tests/test_lpc.py trunk/scipy/sandbox/cdavid/tests/test_segmentaxis.py Log: Nose tests for cdavid sandbox Modified: trunk/scipy/sandbox/cdavid/tests/test_autocorr.py =================================================================== --- trunk/scipy/sandbox/cdavid/tests/test_autocorr.py 2008-01-12 08:49:56 UTC (rev 3820) +++ trunk/scipy/sandbox/cdavid/tests/test_autocorr.py 2008-01-12 09:23:49 UTC (rev 3821) @@ -1,7 +1,7 @@ #! /usr/bin/env python # Last Change: Fri Dec 15 10:00 PM 2006 J -from numpy.testing import * +from scipy.testing import * from numpy.random import randn, seed from numpy import correlate, array, concatenate, require, corrcoef from numpy.fft import fft, ifft @@ -9,12 +9,11 @@ from numpy.ctypeslib import ndpointer, load_library from ctypes import c_uint -set_package_path() -from cdavid.autocorr import _raw_autocorr_1d, _raw_autocorr_1d_noncontiguous -from cdavid.autocorr import autocorr_oneside_nofft as autocorr -from cdavid.autocorr import autocorr_fft , nextpow2 -from cdavid.autocorr import _autocorr_oneside_nofft_py as autocorr_py -restore_path() +from scipy.sandbox.cdavid.autocorr import _raw_autocorr_1d, \ + _raw_autocorr_1d_noncontiguous, \ + autocorr_oneside_nofft as autocorr,\ + autocorr_fft , nextpow2, \ + _autocorr_oneside_nofft_py as autocorr_py import numpy @@ -42,8 +41,8 @@ # This class tests the C functions directly. This is more a debugging tool # that a test case, as the tested functions are not part of the public API -class TestCType1D(NumpyTestCase): - def check_contiguous_double(self): +class TestCType1D(TestCase): + def test_contiguous_double(self): # double test xt = xc1 yt = _raw_autocorr_1d(xt, xt.size - 1) @@ -53,7 +52,7 @@ assert_array_equal(yt, yr) - def check_contiguous_float(self): + def test_contiguous_float(self): # float test xt = xcf1 @@ -64,7 +63,7 @@ assert_array_equal(yt, yr) - def check_non_contiguous_double(self): + def test_non_contiguous_double(self): # double test xt = xf1 yt = _raw_autocorr_1d_noncontiguous(xt, xt.size - 1) @@ -74,7 +73,7 @@ assert_array_equal(yt, yr) - def check_non_contiguous_float(self): + def test_non_contiguous_float(self): # float test xt = xff1 yt = _raw_autocorr_1d_noncontiguous(xt, xt.size - 1) @@ -85,8 +84,8 @@ assert_array_equal(yt, yr) # Test autocorrelation for rank 1 arrays -class TestAutoCorr1D(NumpyTestCase): - def check_contiguous_double(self): +class TestAutoCorr1D(TestCase): + def test_contiguous_double(self): # double test xt = xc1 yt = autocorr(xt, xt.size - 1) @@ -96,7 +95,7 @@ assert_array_equal(yt, yr) - def check_contiguous_float(self): + def test_contiguous_float(self): # float test xt = xcf1 @@ -107,7 +106,7 @@ assert_array_equal(yt, yr) - def check_non_contiguous_double(self): + def test_non_contiguous_double(self): # double test xt = xf1 yt = autocorr(xt, xt.size - 1) @@ -117,7 +116,7 @@ assert_array_equal(yt, yr) - def check_non_contiguous_float(self): + def test_non_contiguous_float(self): # float test xt = xff1 yt = autocorr(xt, xt.size - 1) @@ -131,8 +130,8 @@ # with rank 2 arrays. This will be used in the above test cases; # this function implements the expected behaviour of the public # autocorr function. -class TestAutoCorrPy(NumpyTestCase): - def check_full(self): +class TestAutoCorrPy(TestCase): + def test_full(self): xt = xc axis = -1 lag = xt.shape[axis] - 1 @@ -155,7 +154,7 @@ center = xt[:,i].size - 1 assert_array_equal(tmp[center:center+1+lag], yt[:, i]) - def check_partial(self): + def test_partial(self): xt = xc axis = -1 lag = 1 @@ -179,8 +178,8 @@ assert_array_equal(tmp[center:center+1+lag], yt[:, i]) # Test autocorrelation for rank 2 arrays -class TestAutoCorr2D(NumpyTestCase): - def check_double_full(self): +class TestAutoCorr2D(TestCase): + def test_double_full(self): # C, axis 1 test xt = xc axis = -1 @@ -217,7 +216,7 @@ yr = autocorr_py(xt, lag, axis = axis) assert_array_equal(yt, yr) - def check_float(self): + def test_float(self): # C, axis 1 test xt = xcf axis = -1 @@ -254,7 +253,7 @@ yr = autocorr_py(xt, lag, axis = axis) assert_array_equal(yt, yr) - def check_double_partial(self): + def test_double_partial(self): # C, axis 1 test xt = xc axis = -1 @@ -291,15 +290,15 @@ yr = autocorr_py(xt, lag, axis = axis) assert_array_equal(yt, yr) -class TestAutoCorrFFT(NumpyTestCase): +class TestAutoCorrFFT(TestCase): n = 5 d = 3 - def check_nextpow2(self): + def test_nextpow2(self): assert(nextpow2(255) == 8) assert(nextpow2(256) == 8) assert(nextpow2(257) == 9) - def check_r1r(self): + def test_r1r(self): """real case, rank 1""" a = randn(self.n) @@ -308,7 +307,7 @@ assert_array_almost_equal(atest, aref, decimal = md) assert atest.dtype == a.dtype - def check_r1c(self): + def test_r1c(self): """complex case, rank 1""" a = randn(self.n) + 1.0j * randn(self.n) @@ -317,11 +316,11 @@ assert_array_almost_equal(atest[self.n - 1], aref, decimal = md) assert atest.dtype == a.dtype - def check_r2c(self): + def test_r2c(self): """complex case, rank 2""" pass - def check_r2r(self): + def test_r2r(self): """real case, rank 2""" # axis 0 @@ -345,10 +344,10 @@ assert_array_almost_equal(atest, aref, decimal = md) if __name__ == "__main__": - NumpyTest().run() + unittest.main() -#class TestAutocorr2d(NumpyTestCase): -# def check_double(self): +#class TestAutocorr2d(TestCase): +# def test_double(self): # # C, axis 1 test # xt = xc # axis = -1 @@ -393,7 +392,7 @@ # tmp = correlate(xt[i], xt[i], 'full') # assert_array_equal(tmp[lag:], yt[i]) # -# def check_float(self): +# def test_float(self): # # C, axis 1 test # xt = xcf # axis = -1 Modified: trunk/scipy/sandbox/cdavid/tests/test_lpc.py =================================================================== --- trunk/scipy/sandbox/cdavid/tests/test_lpc.py 2008-01-12 08:49:56 UTC (rev 3820) +++ trunk/scipy/sandbox/cdavid/tests/test_lpc.py 2008-01-12 09:23:49 UTC (rev 3821) @@ -1,19 +1,15 @@ #! /usr/bin/env python # Last Change: Tue Nov 28 05:00 PM 2006 J -from numpy.testing import * +from scipy.testing import * from numpy.random import randn, seed from numpy import correlate, array, concatenate, require from numpy.ctypeslib import ndpointer, load_library from ctypes import c_uint +from scipy.sandbox.cdavid.lpc import _lpc2_py as lpc_py, \ + lpc_ref, lpc2, autocorr_oneside_nofft -set_package_path() -from cdavid.lpc import _lpc2_py as lpc_py -from cdavid.lpc import lpc_ref, lpc2 -from cdavid.autocorr import autocorr_oneside_nofft -restore_path() - import numpy # number of decimals to check @@ -41,8 +37,8 @@ # This class uses lpc in 1 dimension and loop on the axis. Is tested against # a direct matrix inversion of the autocorrelation matrix (using matrix inverse # instead of levinson durbin) -class TestLpcPy(NumpyTestCase): - def check_float(self): +class TestLpcPy(TestCase): + def test_float(self): # Axis -1 xt = xcf axis = -1 @@ -71,7 +67,7 @@ assert_array_almost_equal(tmp, a) - def check_double(self): + def test_double(self): # Axis -1 xt = xc axis = -1 @@ -100,8 +96,8 @@ assert_array_almost_equal(tmp, a) -class TestLpc(NumpyTestCase): - def check_float(self): +class TestLpc(TestCase): + def test_float(self): # Axis -1 xt = xcf axis = -1 @@ -130,7 +126,7 @@ assert_array_almost_equal(e, et) assert_array_almost_equal(k, kt) - def check_float_rank1(self): + def test_float_rank1(self): # test rank 1 xt = xcf[0] axis = 0 @@ -145,7 +141,7 @@ assert_array_almost_equal(e, et) assert_array_almost_equal(k, kt) - def check_double(self): + def test_double(self): # Axis -1 xt = xc axis = -1 @@ -170,7 +166,7 @@ assert_array_almost_equal(e, et) assert_array_almost_equal(k, kt) - def check_double_rank1(self): + def test_double_rank1(self): # test rank 1 xt = xc[0] axis = 0 @@ -184,4 +180,4 @@ assert_array_almost_equal(k, kt) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/cdavid/tests/test_segmentaxis.py =================================================================== --- trunk/scipy/sandbox/cdavid/tests/test_segmentaxis.py 2008-01-12 08:49:56 UTC (rev 3820) +++ trunk/scipy/sandbox/cdavid/tests/test_segmentaxis.py 2008-01-12 09:23:49 UTC (rev 3821) @@ -1,21 +1,21 @@ #! /usr/bin/env python # Last Change: Fri Dec 15 10:00 PM 2006 J -from numpy.testing import * +from scipy.testing import * import numpy as N -set_package_path() -from cdavid.segmentaxis import segment_axis -restore_path() +from scipy.sandbox.cdavid.segmentaxis import segment_axis + + # #Optional: # set_local_path() # # import modules that are located in the same directory as this file. -# restore_path() -class TestSegment(NumpyTestCase): - def check_simple(self): + +class TestSegment(TestCase): + def test_simple(self): assert_equal(segment_axis(N.arange(6),length=3,overlap=0), N.array([[0,1,2],[3,4,5]])) @@ -25,7 +25,7 @@ assert_equal(segment_axis(N.arange(7),length=3,overlap=2), N.array([[0,1,2],[1,2,3],[2,3,4],[3,4,5],[4,5,6]])) - def check_error_checking(self): + def test_error_checking(self): self.assertRaises(ValueError, lambda: segment_axis(N.arange(7),length=3,overlap=-1)) self.assertRaises(ValueError, @@ -35,7 +35,7 @@ self.assertRaises(ValueError, lambda: segment_axis(N.arange(7),length=8,overlap=3)) - def check_ending(self): + def test_ending(self): assert_equal(segment_axis(N.arange(6),length=3,overlap=1,end='cut'), N.array([[0,1,2],[2,3,4]])) assert_equal(segment_axis(N.arange(6),length=3,overlap=1,end='wrap'), @@ -43,7 +43,7 @@ assert_equal(segment_axis(N.arange(6),length=3,overlap=1,end='pad',endvalue=-17), N.array([[0,1,2],[2,3,4],[4,5,-17]])) - def check_multidimensional(self): + def test_multidimensional(self): assert_equal(segment_axis(N.ones((2,3,4,5,6)),axis=3,length=3,overlap=1).shape, (2,3,4,2,3,6)) @@ -61,4 +61,4 @@ (2,3,2,3,5,6)) if __name__=='__main__': - NumpyTest().run() + unittest.main() From scipy-svn at scipy.org Sat Jan 12 05:08:45 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 04:08:45 -0600 (CST) Subject: [Scipy-svn] r3822 - in trunk/scipy: . cluster cluster/tests fftpack fftpack/tests integrate integrate/tests interpolate interpolate/tests io io/matlab/tests lib lib/blas lib/blas/tests lib/lapack lib/lapack/tests linalg linalg/tests linsolve linsolve/umfpack linsolve/umfpack/tests maxentropy maxentropy/tests misc misc/tests ndimage ndimage/segment/tests ndimage/tests odr odr/tests optimize optimize/tests sandbox/arpack/tests sandbox/buildgrid sandbox/cdavid sandbox/constants sandbox/delaunay/tests sandbox/dhuard sandbox/dhuard/tests sandbox/fdfpack/tests sandbox/lobpcg sandbox/lobpcg/tests sandbox/maskedarray sandbox/maskedarray/alternative_versions sandbox/montecarlo/tests sandbox/multigrid sandbox/multigrid/tests sandbox/numexpr sandbox/numexpr/tests sandbox/pyloess sandbox/pyloess/tests sandbox/rbf sandbox/rbf/tests sandbox/spline sandbox/spline/tests sandbox/timeseries sandbox/timeseries/lib sandbox/timeseries/lib/tests sandbox/timeseries/tests signal signal/tests sparse sparse/tests special special/tests stats stats/models stats/models/tests stats/tests testing weave weave/tests Message-ID: <20080112100845.EEDB839C145@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-12 04:06:39 -0600 (Sat, 12 Jan 2008) New Revision: 3822 Added: trunk/scipy/sandbox/dhuard/tests/ trunk/scipy/sandbox/dhuard/tests/test_histogram.py trunk/scipy/sandbox/dhuard/tests/test_stats.py Removed: trunk/scipy/sandbox/dhuard/test_histogram.py trunk/scipy/sandbox/dhuard/test_stats.py trunk/scipy/tests/ Modified: trunk/scipy/__init__.py trunk/scipy/cluster/__init__.py trunk/scipy/cluster/tests/test_vq.py trunk/scipy/fftpack/__init__.py trunk/scipy/fftpack/tests/test_basic.py trunk/scipy/fftpack/tests/test_helper.py trunk/scipy/fftpack/tests/test_pseudo_diffs.py trunk/scipy/integrate/__init__.py trunk/scipy/integrate/tests/test_integrate.py trunk/scipy/integrate/tests/test_quadpack.py trunk/scipy/integrate/tests/test_quadrature.py trunk/scipy/interpolate/__init__.py trunk/scipy/interpolate/tests/test_fitpack.py trunk/scipy/interpolate/tests/test_interpolate.py trunk/scipy/io/__init__.py trunk/scipy/io/matlab/tests/test_mio.py trunk/scipy/lib/__init__.py trunk/scipy/lib/blas/__init__.py trunk/scipy/lib/blas/tests/test_blas.py trunk/scipy/lib/blas/tests/test_fblas.py trunk/scipy/lib/lapack/__init__.py trunk/scipy/lib/lapack/tests/esv_tests.py trunk/scipy/lib/lapack/tests/gesv_tests.py trunk/scipy/lib/lapack/tests/test_lapack.py trunk/scipy/linalg/__init__.py trunk/scipy/linalg/tests/test_atlas_version.py trunk/scipy/linalg/tests/test_basic.py trunk/scipy/linalg/tests/test_blas.py trunk/scipy/linalg/tests/test_decomp.py trunk/scipy/linalg/tests/test_fblas.py trunk/scipy/linalg/tests/test_iterative.py trunk/scipy/linalg/tests/test_lapack.py trunk/scipy/linalg/tests/test_matfuncs.py trunk/scipy/linsolve/__init__.py trunk/scipy/linsolve/umfpack/__init__.py trunk/scipy/linsolve/umfpack/tests/test_umfpack.py trunk/scipy/maxentropy/__init__.py trunk/scipy/maxentropy/tests/test_maxentropy.py trunk/scipy/misc/__init__.py trunk/scipy/misc/ppimport.py trunk/scipy/misc/tests/test_pilutil.py trunk/scipy/ndimage/__init__.py trunk/scipy/ndimage/segment/tests/test_segment.py trunk/scipy/ndimage/tests/test_ndimage.py trunk/scipy/odr/__init__.py trunk/scipy/odr/tests/test_odr.py trunk/scipy/optimize/__init__.py trunk/scipy/optimize/tests/test_cobyla.py trunk/scipy/optimize/tests/test_nonlin.py trunk/scipy/optimize/tests/test_optimize.py trunk/scipy/optimize/tests/test_slsqp.py trunk/scipy/optimize/tests/test_zeros.py trunk/scipy/sandbox/arpack/tests/test_arpack.py trunk/scipy/sandbox/arpack/tests/test_speigs.py trunk/scipy/sandbox/buildgrid/test_build_grid.py trunk/scipy/sandbox/cdavid/__init__.py trunk/scipy/sandbox/cdavid/segmentaxis.py trunk/scipy/sandbox/constants/constants.py trunk/scipy/sandbox/delaunay/tests/test_triangulate.py trunk/scipy/sandbox/fdfpack/tests/test_fdf.py trunk/scipy/sandbox/lobpcg/__init__.py trunk/scipy/sandbox/lobpcg/tests/large_scale.py trunk/scipy/sandbox/lobpcg/tests/test_lobpcg.py trunk/scipy/sandbox/maskedarray/alternative_versions/test_mrecarray.py trunk/scipy/sandbox/maskedarray/testutils.py trunk/scipy/sandbox/montecarlo/tests/test_dictsampler.py trunk/scipy/sandbox/montecarlo/tests/test_intsampler.py trunk/scipy/sandbox/multigrid/__init__.py trunk/scipy/sandbox/multigrid/simple_test.py trunk/scipy/sandbox/multigrid/tests/test_adaptive.py trunk/scipy/sandbox/multigrid/tests/test_relaxation.py trunk/scipy/sandbox/multigrid/tests/test_sa.py trunk/scipy/sandbox/multigrid/tests/test_utils.py trunk/scipy/sandbox/numexpr/__init__.py trunk/scipy/sandbox/numexpr/compiler.py trunk/scipy/sandbox/numexpr/expressions.py trunk/scipy/sandbox/numexpr/tests/test_numexpr.py trunk/scipy/sandbox/pyloess/mpyloess.py trunk/scipy/sandbox/pyloess/tests/test_mpyloess.py trunk/scipy/sandbox/pyloess/tests/test_pyloess.py trunk/scipy/sandbox/rbf/__init__.py trunk/scipy/sandbox/rbf/tests/test_rbf.py trunk/scipy/sandbox/spline/__init__.py trunk/scipy/sandbox/spline/tests/test_fitpack.py trunk/scipy/sandbox/spline/tests/test_spline.py trunk/scipy/sandbox/timeseries/dates.py trunk/scipy/sandbox/timeseries/extras.py trunk/scipy/sandbox/timeseries/lib/filters.py trunk/scipy/sandbox/timeseries/lib/interpolate.py trunk/scipy/sandbox/timeseries/lib/moving_funcs.py trunk/scipy/sandbox/timeseries/lib/tests/test_interpolate.py trunk/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py trunk/scipy/sandbox/timeseries/report.py trunk/scipy/sandbox/timeseries/tests/test_dates.py trunk/scipy/sandbox/timeseries/tests/test_extras.py trunk/scipy/sandbox/timeseries/tests/test_timeseries.py trunk/scipy/sandbox/timeseries/tests/test_trecords.py trunk/scipy/sandbox/timeseries/trecords.py trunk/scipy/sandbox/timeseries/tseries.py trunk/scipy/setup.py trunk/scipy/signal/__init__.py trunk/scipy/signal/tests/test_signaltools.py trunk/scipy/signal/tests/test_wavelets.py trunk/scipy/sparse/__init__.py trunk/scipy/sparse/tests/test_base.py trunk/scipy/sparse/tests/test_construct.py trunk/scipy/sparse/tests/test_sparse.py trunk/scipy/sparse/tests/test_spfuncs.py trunk/scipy/sparse/tests/test_sputils.py trunk/scipy/special/__init__.py trunk/scipy/special/tests/test_basic.py trunk/scipy/special/tests/test_spfun_stats.py trunk/scipy/stats/__init__.py trunk/scipy/stats/models/__init__.py trunk/scipy/stats/models/tests/test_bspline.py trunk/scipy/stats/models/tests/test_formula.py trunk/scipy/stats/models/tests/test_glm.py trunk/scipy/stats/models/tests/test_regression.py trunk/scipy/stats/models/tests/test_rlm.py trunk/scipy/stats/models/tests/test_scale.py trunk/scipy/stats/models/tests/test_utils.py trunk/scipy/stats/morestats.py trunk/scipy/stats/tests/test_distributions.py trunk/scipy/stats/tests/test_morestats.py trunk/scipy/stats/tests/test_stats.py trunk/scipy/testing/nosetester.py trunk/scipy/weave/__init__.py trunk/scipy/weave/c_spec.py trunk/scipy/weave/size_check.py trunk/scipy/weave/tests/test_ast_tools.py trunk/scipy/weave/tests/test_blitz_tools.py trunk/scipy/weave/tests/test_build_tools.py trunk/scipy/weave/tests/test_c_spec.py trunk/scipy/weave/tests/test_catalog.py trunk/scipy/weave/tests/test_ext_tools.py trunk/scipy/weave/tests/test_inline_tools.py trunk/scipy/weave/tests/test_numpy_scalar_spec.py trunk/scipy/weave/tests/test_scxx.py trunk/scipy/weave/tests/test_scxx_dict.py trunk/scipy/weave/tests/test_scxx_object.py trunk/scipy/weave/tests/test_scxx_sequence.py trunk/scipy/weave/tests/test_size_check.py trunk/scipy/weave/tests/test_slice_handler.py trunk/scipy/weave/tests/test_standard_array_spec.py trunk/scipy/weave/tests/test_wx_spec.py trunk/scipy/weave/tests/weave_test_utils.py Log: Full changeset to implement nose testing Modified: trunk/scipy/__init__.py =================================================================== --- trunk/scipy/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -62,14 +62,9 @@ """ __doc__ += pkgload.get_pkgdocs() +from testing.pkgtester import Tester +test = Tester().test -def test(level=1, verbosity=1): - """ Run Scipy tests suite with level and verbosity.""" - from numpy.testing import NumpyTest - import scipy - scipy.pkgload() - return NumpyTest(scipy).test(level, verbosity) - __doc__ += """ Utility tools Modified: trunk/scipy/cluster/__init__.py =================================================================== --- trunk/scipy/cluster/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/cluster/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -7,5 +7,5 @@ __all__ = ['vq'] import vq -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/cluster/tests/test_vq.py =================================================================== --- trunk/scipy/cluster/tests/test_vq.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/cluster/tests/test_vq.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -7,26 +7,22 @@ # kmeans works OK for trivial examples. import sys -from numpy.testing import * +import os.path +from scipy.testing import * import numpy as N -set_package_path() -from cluster.vq import kmeans, kmeans2, py_vq, py_vq2, _py_vq_1d, vq, ClusterError +from scipy.cluster.vq import kmeans, kmeans2, py_vq, py_vq2, _py_vq_1d, vq, ClusterError try: - from cluster import _vq + from scipy.cluster import _vq TESTC=True except ImportError: print "== Error while importing _vq, not testing C imp of vq ==" TESTC=False -restore_path() -import os.path #Optional: -set_local_path() # import modules that are located in the same directory as this file. -DATAFILE1 = os.path.join(sys.path[0], "data.txt") -restore_path() +DATAFILE1 = os.path.join(os.path.dirname(__file__), "data.txt") # Global data X = N.array([[3.0, 3], [4, 3], [4, 2], @@ -43,20 +39,20 @@ LABEL1 = N.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1]) -class TestVq(NumpyTestCase): - def check_py_vq(self, level=1): +class TestVq(TestCase): + def test_py_vq(self): initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() label1 = py_vq(X, initc)[0] assert_array_equal(label1, LABEL1) - def check_py_vq2(self, level=1): + def test_py_vq2(self): initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() label1 = py_vq2(X, initc)[0] assert_array_equal(label1, LABEL1) - def check_vq(self, level=1): + def test_vq(self): initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() if TESTC: @@ -66,7 +62,7 @@ else: print "== not testing C imp of vq ==" - #def check_py_vq_1d(self, level=1): + #def test_py_vq_1d(self): # """Test special rank 1 vq algo, python implementation.""" # data = X[:, 0] # initc = data[:3] @@ -76,7 +72,7 @@ # assert_array_equal(a, ta) # assert_array_equal(b, tb) - def check_vq_1d(self, level=1): + def test_vq_1d(self): """Test special rank 1 vq algo, python implementation.""" data = X[:, 0] initc = data[:3] @@ -89,15 +85,15 @@ else: print "== not testing C imp of vq (rank 1) ==" -class TestKMean(NumpyTestCase): - def check_kmeans_simple(self, level=1): +class TestKMean(TestCase): + def test_kmeans_simple(self): initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() code1 = kmeans(X, code, iter = 1)[0] assert_array_almost_equal(code1, CODET2) - def check_kmeans_lost_cluster(self, level=1): + def test_kmeans_lost_cluster(self): """This will cause kmean to have a cluster with no points.""" data = N.fromfile(open(DATAFILE1), sep = ", ") data = data.reshape((200, 2)) @@ -113,7 +109,7 @@ except ClusterError, e: print "exception raised as expected: " + str(e) - def check_kmeans2_simple(self, level=1): + def test_kmeans2_simple(self): """Testing simple call to kmeans2 and its results.""" initc = N.concatenate(([[X[0]], [X[1]], [X[2]]])) code = initc.copy() @@ -123,7 +119,7 @@ assert_array_almost_equal(code1, CODET1) assert_array_almost_equal(code2, CODET2) - def check_kmeans2_rank1(self, level=1): + def test_kmeans2_rank1(self): """Testing simple call to kmeans2 with rank 1 data.""" data = N.fromfile(open(DATAFILE1), sep = ", ") data = data.reshape((200, 2)) @@ -135,7 +131,7 @@ code1 = kmeans2(data1, code, iter = 1)[0] code2 = kmeans2(data1, code, iter = 2)[0] - def check_kmeans2_init(self, level = 1): + def test_kmeans2_init(self): """Testing that kmeans2 init methods work.""" data = N.fromfile(open(DATAFILE1), sep = ", ") data = data.reshape((200, 2)) @@ -149,4 +145,4 @@ kmeans2(data, 3, minit = 'points') if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/fftpack/__init__.py =================================================================== --- trunk/scipy/fftpack/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/fftpack/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -17,5 +17,5 @@ del k, register_func -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/fftpack/tests/test_basic.py =================================================================== --- trunk/scipy/fftpack/tests/test_basic.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/fftpack/tests/test_basic.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -6,16 +6,14 @@ Build fftpack: python setup_fftpack.py build Run tests if scipy is installed: - python -c 'import scipy;scipy.fftpack.test()' + python -c 'import scipy;scipy.fftpack.test()' Run tests if fftpack is not installed: - python tests/test_basic.py [] + python tests/test_basic.py """ import sys -from numpy.testing import * -set_package_path() -from fftpack import ifft,fft,fftn,ifftn,rfft,irfft -from fftpack import _fftpack as fftpack -restore_path() +from scipy.testing import * +from scipy.fftpack import ifft,fft,fftn,ifftn,rfft,irfft +from scipy.fftpack import _fftpack as fftpack from numpy import arange, add, array, asarray, zeros, dot, exp, pi,\ swapaxes, double, cdouble @@ -90,9 +88,9 @@ x1[0] = x[0] return direct_idft(x1).real -class TestFft(NumpyTestCase): +class TestFft(TestCase): - def check_definition(self): + def test_definition(self): x = [1,2,3,4+1j,1,2,3,4+2j] y = fft(x) y1 = direct_dft(x) @@ -100,7 +98,7 @@ x = [1,2,3,4+0j,5] assert_array_almost_equal(fft(x),direct_dft(x)) - def check_n_argument_real(self): + def test_n_argument_real(self): x1 = [1,2,3,4] x2 = [1,2,3,4] y = fft([x1,x2],n=4) @@ -108,7 +106,7 @@ assert_array_almost_equal(y[0],direct_dft(x1)) assert_array_almost_equal(y[1],direct_dft(x2)) - def _check_n_argument_complex(self): + def _test_n_argument_complex(self): x1 = [1,2,3,4+1j] x2 = [1,2,3,4+1j] y = fft([x1,x2],n=4) @@ -116,7 +114,7 @@ assert_array_almost_equal(y[0],direct_dft(x1)) assert_array_almost_equal(y[1],direct_dft(x2)) - def check_djbfft(self): + def test_djbfft(self): for i in range(2,14): n = 2**i x = range(n) @@ -126,7 +124,8 @@ y = fftpack.zrfft(x) assert_array_almost_equal(y,y2) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import fft as numpy_fft print print ' Fast Fourier Transform' @@ -152,19 +151,19 @@ if size > 500: y = fft(x) else: y = direct_dft(x) assert_array_almost_equal(fft(x),y) - print '|%8.2f' % self.measure('fft(x)',repeat), + print '|%8.2f' % measure('fft(x)',repeat), sys.stdout.flush() assert_array_almost_equal(numpy_fft(x),y) - print '|%8.2f' % self.measure('numpy_fft(x)',repeat), + print '|%8.2f' % measure('numpy_fft(x)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) sys.stdout.flush() -class TestIfft(NumpyTestCase): +class TestIfft(TestCase): - def check_definition(self): + def test_definition(self): x = [1,2,3,4+1j,1,2,3,4+2j] y = ifft(x) y1 = direct_idft(x) @@ -178,7 +177,7 @@ x = [1,2,3,4,5] assert_array_almost_equal(ifft(x),direct_idft(x)) - def check_djbfft(self): + def test_djbfft(self): for i in range(2,14): n = 2**i x = range(n) @@ -188,20 +187,21 @@ y = fftpack.zrfft(x,direction=-1) assert_array_almost_equal(y,y2) - def check_random_complex(self): + def test_random_complex(self): for size in [1,51,111,100,200,64,128,256,1024]: x = random([size]).astype(cdouble) x = random([size]).astype(cdouble) +1j*x assert_array_almost_equal (ifft(fft(x)),x) assert_array_almost_equal (fft(ifft(x)),x) - def check_random_real(self): + def test_random_real(self): for size in [1,51,111,100,200,64,128,256,1024]: x = random([size]).astype(double) assert_array_almost_equal (ifft(fft(x)),x) assert_array_almost_equal (fft(ifft(x)),x) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import ifft as numpy_ifft print print ' Inverse Fast Fourier Transform' @@ -227,19 +227,19 @@ if size > 500: y = ifft(x) else: y = direct_idft(x) assert_array_almost_equal(ifft(x),y) - print '|%8.2f' % self.measure('ifft(x)',repeat), + print '|%8.2f' % measure('ifft(x)',repeat), sys.stdout.flush() assert_array_almost_equal(numpy_ifft(x),y) - print '|%8.2f' % self.measure('numpy_ifft(x)',repeat), + print '|%8.2f' % measure('numpy_ifft(x)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) sys.stdout.flush() -class TestRfft(NumpyTestCase): +class TestRfft(TestCase): - def check_definition(self): + def test_definition(self): x = [1,2,3,4,1,2,3,4] y = rfft(x) y1 = direct_rdft(x) @@ -249,7 +249,7 @@ y1 = direct_rdft(x) assert_array_almost_equal(y,y1) - def check_djbfft(self): + def test_djbfft(self): from numpy.fft import fft as numpy_fft for i in range(2,14): n = 2**i @@ -264,7 +264,8 @@ y = fftpack.drfft(x) assert_array_almost_equal(y,y1) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import rfft as numpy_rfft print print 'Fast Fourier Transform (real data)' @@ -283,18 +284,18 @@ sys.stdout.flush() x = random([size]).astype(double) - print '|%8.2f' % self.measure('rfft(x)',repeat), + print '|%8.2f' % measure('rfft(x)',repeat), sys.stdout.flush() - print '|%8.2f' % self.measure('numpy_rfft(x)',repeat), + print '|%8.2f' % measure('numpy_rfft(x)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) sys.stdout.flush() -class TestIrfft(NumpyTestCase): +class TestIrfft(TestCase): - def check_definition(self): + def test_definition(self): x = [1,2,3,4,1,2,3,4] x1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j] y = irfft(x) @@ -308,7 +309,7 @@ assert_array_almost_equal(y,y1) assert_array_almost_equal(y,ifft(x1)) - def check_djbfft(self): + def test_djbfft(self): from numpy.fft import ifft as numpy_ifft for i in range(2,14): n = 2**i @@ -323,13 +324,14 @@ y = fftpack.drfft(x,direction=-1) assert_array_almost_equal(y,y1) - def check_random_real(self): + def test_random_real(self): for size in [1,51,111,100,200,64,128,256,1024]: x = random([size]).astype(double) assert_array_almost_equal (irfft(rfft(x)),x) assert_array_almost_equal (rfft(irfft(x)),x) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import irfft as numpy_irfft print @@ -357,20 +359,20 @@ x1[-1] = x[-1] y = irfft(x) - print '|%8.2f' % self.measure('irfft(x)',repeat), + print '|%8.2f' % measure('irfft(x)',repeat), sys.stdout.flush() assert_array_almost_equal(numpy_irfft(x1,size),y) - print '|%8.2f' % self.measure('numpy_irfft(x1,size)',repeat), + print '|%8.2f' % measure('numpy_irfft(x1,size)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) sys.stdout.flush() -class TestFftn(NumpyTestCase): +class TestFftn(TestCase): - def check_definition(self): + def test_definition(self): x = [[1,2,3],[4,5,6],[7,8,9]] y = fftn(x) assert_array_almost_equal(y,direct_dftn(x)) @@ -379,7 +381,7 @@ x = random((5,4,3,20)) assert_array_almost_equal(fftn(x),direct_dftn(x)) - def check_axes_argument(self): + def test_axes_argument(self): #plane == ji_plane, x== kji_space plane1 = [[1,2,3],[4,5,6],[7,8,9]] plane2 = [[10,11,12],[13,14,15],[16,17,18]] @@ -469,7 +471,7 @@ y = fftn(x,axes=()) # point assert_array_almost_equal(y,x) - def check_shape_argument(self): + def test_shape_argument(self): small_x = [[1,2,3],[4,5,6]] large_x1 = [[1,2,3,0],[4,5,6,0],[0,0,0,0],[0,0,0,0]] y = fftn(small_x,shape=(4,4)) @@ -477,7 +479,7 @@ y = fftn(small_x,shape=(3,4)) assert_array_almost_equal (y,fftn(large_x1[:-1])) - def check_shape_axes_argument(self): + def test_shape_axes_argument(self): small_x = [[1,2,3],[4,5,6],[7,8,9]] large_x1 = array([[1,2,3,0], [4,5,6,0], @@ -495,7 +497,8 @@ assert_array_almost_equal (y,swapaxes(\ fftn(swapaxes(large_x1,-1,-2)),-1,-2)) - def bench_random(self,level=5): + @dec.bench + def test_random(self): from numpy.fft import fftn as numpy_fftn print print ' Multi-dimensional Fast Fourier Transform' @@ -518,20 +521,20 @@ #if size > 500: y = fftn(x) #else: y = direct_dft(x) assert_array_almost_equal(fftn(x),y) - print '|%8.2f' % self.measure('fftn(x)',repeat), + print '|%8.2f' % measure('fftn(x)',repeat), sys.stdout.flush() assert_array_almost_equal(numpy_fftn(x),y) - print '|%8.2f' % self.measure('numpy_fftn(x)',repeat), + print '|%8.2f' % measure('numpy_fftn(x)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) sys.stdout.flush() -class TestIfftn(NumpyTestCase): +class TestIfftn(TestCase): - def check_definition(self): + def test_definition(self): x = [[1,2,3],[4,5,6],[7,8,9]] y = ifftn(x) assert_array_almost_equal(y,direct_idftn(x)) @@ -540,11 +543,11 @@ x = random((5,4,3,20)) assert_array_almost_equal(ifftn(x),direct_idftn(x)) - def check_random_complex(self): + def test_random_complex(self): for size in [1,2,51,32,64,92]: x = random([size,size]) + 1j*random([size,size]) assert_array_almost_equal (ifftn(fftn(x)),x) assert_array_almost_equal (fftn(ifftn(x)),x) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/fftpack/tests/test_helper.py =================================================================== --- trunk/scipy/fftpack/tests/test_helper.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/fftpack/tests/test_helper.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -12,19 +12,17 @@ """ import sys -from numpy.testing import * -set_package_path() -from fftpack import fftshift,ifftshift,fftfreq,rfftfreq -restore_path() +from scipy.testing import * +from scipy.fftpack import fftshift,ifftshift,fftfreq,rfftfreq from numpy import pi def random(size): return rand(*size) -class TestFFTShift(NumpyTestCase): +class TestFFTShift(TestCase): - def check_definition(self): + def test_definition(self): x = [0,1,2,3,4,-4,-3,-2,-1] y = [-4,-3,-2,-1,0,1,2,3,4] assert_array_almost_equal(fftshift(x),y) @@ -34,14 +32,14 @@ assert_array_almost_equal(fftshift(x),y) assert_array_almost_equal(ifftshift(y),x) - def check_inverse(self): + def test_inverse(self): for n in [1,4,9,100,211]: x = random((n,)) assert_array_almost_equal(ifftshift(fftshift(x)),x) -class TestFFTFreq(NumpyTestCase): +class TestFFTFreq(TestCase): - def check_definition(self): + def test_definition(self): x = [0,1,2,3,4,-4,-3,-2,-1] assert_array_almost_equal(9*fftfreq(9),x) assert_array_almost_equal(9*pi*fftfreq(9,pi),x) @@ -49,9 +47,9 @@ assert_array_almost_equal(10*fftfreq(10),x) assert_array_almost_equal(10*pi*fftfreq(10,pi),x) -class TestRFFTFreq(NumpyTestCase): +class TestRFFTFreq(TestCase): - def check_definition(self): + def test_definition(self): x = [0,1,1,2,2,3,3,4,4] assert_array_almost_equal(9*rfftfreq(9),x) assert_array_almost_equal(9*pi*rfftfreq(9,pi),x) @@ -60,4 +58,4 @@ assert_array_almost_equal(10*pi*rfftfreq(10,pi),x) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/fftpack/tests/test_pseudo_diffs.py =================================================================== --- trunk/scipy/fftpack/tests/test_pseudo_diffs.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/fftpack/tests/test_pseudo_diffs.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -11,12 +11,10 @@ python tests/test_pseudo_diffs.py [] """ import sys -from numpy.testing import * -set_package_path() -from fftpack import diff,fft,ifft,tilbert,itilbert,hilbert,ihilbert,rfft -from fftpack import shift -from fftpack import fftfreq -restore_path() +from scipy.testing import * +from scipy.fftpack import diff,fft,ifft,tilbert,itilbert,hilbert,ihilbert,rfft +from scipy.fftpack import shift +from scipy.fftpack import fftfreq from numpy import arange, add, array, sin, cos, pi,exp,tanh,sum,sign @@ -77,9 +75,9 @@ return ifft(fft(x)*exp(k*a)).real -class TestDiff(NumpyTestCase): +class TestDiff(TestCase): - def check_definition(self): + def test_definition(self): for n in [16,17,64,127,32]: x = arange(n)*2*pi/n assert_array_almost_equal(diff(sin(x)),direct_diff(sin(x))) @@ -100,7 +98,7 @@ assert_array_almost_equal(diff(sin(4*x),k),direct_diff(sin(4*x),k)) assert_array_almost_equal(diff(cos(4*x),k),direct_diff(cos(4*x),k)) - def check_period(self): + def test_period(self): for n in [17,64]: x = arange(n)/float(n) assert_array_almost_equal(diff(sin(2*pi*x),period=1), @@ -108,7 +106,7 @@ assert_array_almost_equal(diff(sin(2*pi*x),3,period=1), -(2*pi)**3*cos(2*pi*x)) - def check_sin(self): + def test_sin(self): for n in [32,64,77]: x = arange(n)*2*pi/n assert_array_almost_equal(diff(sin(x)),cos(x)) @@ -118,7 +116,7 @@ assert_array_almost_equal(diff(sin(4*x)),4*cos(4*x)) assert_array_almost_equal(diff(sin(sin(x))),cos(x)*cos(sin(x))) - def check_expr(self): + def test_expr(self): for n in [64,77,100,128,256,512,1024,2048,4096,8192][:5]: x = arange(n)*2*pi/n f=sin(x)*cos(4*x)+exp(sin(3*x)) @@ -132,7 +130,7 @@ assert_array_almost_equal(diff(ddf,-1),df) #print max(abs(d1-df)) - def check_expr_large(self): + def test_expr_large(self): for n in [2048,4096]: x = arange(n)*2*pi/n f=sin(x)*cos(4*x)+exp(sin(3*x)) @@ -144,7 +142,7 @@ assert_array_almost_equal(diff(ddf,-1),df) assert_array_almost_equal(diff(f,2),ddf) - def check_int(self): + def test_int(self): n = 64 x = arange(n)*2*pi/n assert_array_almost_equal(diff(sin(x),-1),-cos(x)) @@ -152,7 +150,7 @@ assert_array_almost_equal(diff(sin(x),-4),sin(x)) assert_array_almost_equal(diff(2*cos(2*x),-1),sin(2*x)) - def check_random_even(self): + def test_random_even(self): for k in [0,2,4,6]: for n in [60,32,64,56,55]: f=random ((n,)) @@ -164,7 +162,7 @@ assert_array_almost_equal(diff(diff(f,k),-k),f) assert_array_almost_equal(diff(diff(f,-k),k),f) - def check_random_odd(self): + def test_random_odd(self): for k in [0,1,2,3,4,5,6]: for n in [33,65,55]: f=random ((n,)) @@ -174,7 +172,7 @@ assert_array_almost_equal(diff(diff(f,k),-k),f) assert_array_almost_equal(diff(diff(f,-k),k),f) - def check_zero_nyquist (self): + def test_zero_nyquist (self): for k in [0,1,2,3,4,5,6]: for n in [32,33,64,56,55]: f=random ((n,)) @@ -186,7 +184,8 @@ assert_array_almost_equal(diff(diff(f,k),-k),f) assert_array_almost_equal(diff(diff(f,-k),k),f) - def bench_random(self,level=5): + @dec.bench + def test_random(self): print print 'Differentiation of periodic functions' print '=====================================' @@ -209,16 +208,16 @@ f = sin(x)*cos(4*x) assert_array_almost_equal(diff(f,1),direct_diff(f,1)) assert_array_almost_equal(diff(f,2),direct_diff(f,2)) - print '| %9.2f' % self.measure('diff(f,3)',repeat), + print '| %9.2f' % measure('diff(f,3)',repeat), sys.stdout.flush() - print '| %9.2f' % self.measure('direct_diff(f,3)',repeat), + print '| %9.2f' % measure('direct_diff(f,3)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) -class TestTilbert(NumpyTestCase): +class TestTilbert(TestCase): - def check_definition(self): + def test_definition(self): for h in [0.1,0.5,1,5.5,10]: for n in [16,17,64,127]: x = arange(n)*2*pi/n @@ -230,7 +229,7 @@ assert_array_almost_equal(tilbert(sin(2*x),h), direct_tilbert(sin(2*x),h)) - def check_random_even(self): + def test_random_even(self): for h in [0.1,0.5,1,5.5,10]: for n in [32,64,56]: f=random ((n,)) @@ -239,7 +238,7 @@ assert_almost_equal(sum(f,axis=0),0.0) assert_array_almost_equal(direct_tilbert(direct_itilbert(f,h),h),f) - def check_random_odd(self): + def test_random_odd(self): for h in [0.1,0.5,1,5.5,10]: for n in [33,65,55]: f=random ((n,)) @@ -249,7 +248,8 @@ assert_array_almost_equal(itilbert(tilbert(f,h),h),f) assert_array_almost_equal(tilbert(itilbert(f,h),h),f) - def bench_random(self,level=5): + @dec.bench + def test_random(self): print print ' Tilbert transform of periodic functions' print '=========================================' @@ -271,15 +271,15 @@ else: f = sin(x)*cos(4*x) assert_array_almost_equal(tilbert(f,1),direct_tilbert(f,1)) - print '| %9.2f' % self.measure('tilbert(f,1)',repeat), + print '| %9.2f' % measure('tilbert(f,1)',repeat), sys.stdout.flush() - print '| %9.2f' % self.measure('direct_tilbert(f,1)',repeat), + print '| %9.2f' % measure('direct_tilbert(f,1)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) -class TestITilbert(NumpyTestCase): +class TestITilbert(TestCase): - def check_definition(self): + def test_definition(self): for h in [0.1,0.5,1,5.5,10]: for n in [16,17,64,127]: x = arange(n)*2*pi/n @@ -291,9 +291,9 @@ assert_array_almost_equal(itilbert(sin(2*x),h), direct_itilbert(sin(2*x),h)) -class TestHilbert(NumpyTestCase): +class TestHilbert(TestCase): - def check_definition(self): + def test_definition(self): for n in [16,17,64,127]: x = arange(n)*2*pi/n y = hilbert(sin(x)) @@ -302,7 +302,7 @@ assert_array_almost_equal(hilbert(sin(2*x)), direct_hilbert(sin(2*x))) - def check_tilbert_relation(self): + def test_tilbert_relation(self): for n in [16,17,64,127]: x = arange(n)*2*pi/n f = sin (x)+cos (2*x)*sin(x) @@ -312,7 +312,7 @@ y2 = tilbert(f,h=10) assert_array_almost_equal (y,y2) - def check_random_odd(self): + def test_random_odd(self): for n in [33,65,55]: f=random ((n,)) af=sum(f,axis=0)/n @@ -321,7 +321,7 @@ assert_array_almost_equal(ihilbert(hilbert(f)),f) assert_array_almost_equal(hilbert(ihilbert(f)),f) - def check_random_even(self): + def test_random_even(self): for n in [32,64,56]: f=random ((n,)) af=sum(f,axis=0)/n @@ -332,7 +332,8 @@ assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f) assert_array_almost_equal(hilbert(ihilbert(f)),f) - def bench_random(self,level=5): + @dec.bench + def test_random(self): print print ' Hilbert transform of periodic functions' print '=========================================' @@ -354,15 +355,15 @@ else: f = sin(x)*cos(4*x) assert_array_almost_equal(hilbert(f),direct_hilbert(f)) - print '| %9.2f' % self.measure('hilbert(f)',repeat), + print '| %9.2f' % measure('hilbert(f)',repeat), sys.stdout.flush() - print '| %9.2f' % self.measure('direct_hilbert(f)',repeat), + print '| %9.2f' % measure('direct_hilbert(f)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) -class TestIHilbert(NumpyTestCase): +class TestIHilbert(TestCase): - def check_definition(self): + def test_definition(self): for n in [16,17,64,127]: x = arange(n)*2*pi/n y = ihilbert(sin(x)) @@ -371,7 +372,7 @@ assert_array_almost_equal(ihilbert(sin(2*x)), direct_ihilbert(sin(2*x))) - def check_itilbert_relation(self): + def test_itilbert_relation(self): for n in [16,17,64,127]: x = arange(n)*2*pi/n f = sin (x)+cos (2*x)*sin(x) @@ -381,9 +382,9 @@ y2 = itilbert(f,h=10) assert_array_almost_equal (y,y2) -class TestShift(NumpyTestCase): +class TestShift(TestCase): - def check_definition(self): + def test_definition(self): for n in [18,17,64,127,32,2048,256]: x = arange(n)*2*pi/n for a in [0.1,3]: @@ -397,7 +398,8 @@ assert_array_almost_equal(shift(sin(x),pi),-sin(x)) assert_array_almost_equal(shift(sin(x),pi/2),cos(x)) - def bench_random(self,level=5): + @dec.bench + def test_random(self): print print ' Shifting periodic functions' print '==============================' @@ -423,11 +425,11 @@ sf = sin(x+a)*cos(4*(x+a)) assert_array_almost_equal(direct_shift(f,1),sf) assert_array_almost_equal(shift(f,1),sf) - print '| %9.2f' % self.measure('shift(f,a)',repeat), + print '| %9.2f' % measure('shift(f,a)',repeat), sys.stdout.flush() - print '| %9.2f' % self.measure('direct_shift(f,a)',repeat), + print '| %9.2f' % measure('direct_shift(f,a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) if __name__ == "__main__": - NumpyTest('fftpack.pseudo_diffs').run() + unittest.main() Modified: trunk/scipy/integrate/__init__.py =================================================================== --- trunk/scipy/integrate/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/integrate/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -12,5 +12,5 @@ from ode import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/integrate/tests/test_integrate.py =================================================================== --- trunk/scipy/integrate/tests/test_integrate.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/integrate/tests/test_integrate.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -9,12 +9,10 @@ import numpy from numpy import arange, zeros, array, dot, sqrt, cos, sin from scipy.linalg import norm -from numpy.testing import * -set_package_path() +from scipy.testing import * from scipy.integrate import odeint -restore_path() -class TestODEInt(NumpyTestCase): +class TestODEInt(TestCase): """ Test odeint: free vibration of a simple oscillator m \ddot{u} + k u = 0, u(0) = u_0 \dot{u}(0) \dot{u}_0 @@ -32,7 +30,7 @@ tmp[1,0] = -self.k / self.m return dot(tmp,z) - def check_odeint1(self): + def test_odeint1(self): omega = sqrt(self.k / self.m) z0 = zeros(2, float) z0[0] = 1.0 # initial displacement @@ -51,4 +49,4 @@ assert res < 1.0e-6 if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/integrate/tests/test_quadpack.py =================================================================== --- trunk/scipy/integrate/tests/test_quadpack.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/integrate/tests/test_quadpack.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,29 +1,27 @@ import numpy from numpy import sqrt, cos, sin, arctan, exp, log, pi, Inf -from numpy.testing import * -set_package_path() +from scipy.testing import * from scipy.integrate import quad, dblquad, tplquad -restore_path() def assert_quad((value, err), tabledValue, errTol=1.5e-8): assert abs(value-tabledValue) < err, (value, tabledValue, err) if errTol is not None: assert err < errTol, (err, errTol) -class TestQuad(NumpyTestCase): - def check_typical(self): +class TestQuad(TestCase): + def test_typical(self): # 1) Typical function with two extra arguments: def myfunc(x,n,z): # Bessel function integrand return cos(n*x-z*sin(x))/pi assert_quad(quad(myfunc,0,pi,(2,1.8)), 0.30614353532540296487) - def check_indefinite(self): + def test_indefinite(self): # 2) Infinite integration limits --- Euler's constant def myfunc(x): # Euler's constant integrand return -exp(-x)*log(x) assert_quad(quad(myfunc,0,Inf), 0.577215664901532860606512) - def check_singular(self): + def test_singular(self): # 3) Singular points in region of integration. def myfunc(x): if x > 0 and x < 2.5: @@ -36,7 +34,7 @@ assert_quad(quad(myfunc,0,10,points=[2.5,5.0]), 1 - cos(2.5) + exp(-2.5) - exp(-5.0)) - def check_sine_weighted_finite(self): + def test_sine_weighted_finite(self): # 4) Sine weighted integral (finite limits) def myfunc(x,a): return exp(a*(x-1)) @@ -45,7 +43,7 @@ assert_quad(quad(myfunc,0,1,args=20,weight='sin',wvar=ome), (20*sin(ome)-ome*cos(ome)+ome*exp(-20))/(20**2 + ome**2)) - def check_sine_weighted_infinite(self): + def test_sine_weighted_infinite(self): # 5) Sine weighted integral (infinite limits) def myfunc(x,a): return exp(-x*a) @@ -55,7 +53,7 @@ assert_quad(quad(myfunc,0,Inf,args=a,weight='sin',wvar=ome), ome/(a**2 + ome**2)) - def check_cosine_weighted_infinite(self): + def test_cosine_weighted_infinite(self): # 6) Cosine weighted integral (negative infinite limits) def myfunc(x,a): return exp(x*a) @@ -65,7 +63,7 @@ assert_quad(quad(myfunc,-Inf,0,args=a,weight='cos',wvar=ome), a/(a**2 + ome**2)) - def check_algebraic_log_weight(self): + def test_algebraic_log_weight(self): # 6) Algebraic-logarithmic weight. def myfunc(x,a): return 1/(1+x+2**(-a)) @@ -74,7 +72,7 @@ assert_quad(quad(myfunc,-1,1,args=a,weight='alg',wvar=(-0.5,-0.5)), pi/sqrt((1+2**(-a))**2 - 1)) - def check_cauchypv_weight(self): + def test_cauchypv_weight(self): # 7) Cauchy prinicpal value weighting w(x) = 1/(x-c) def myfunc(x,a): return 2.0**(-a)/((x-1)**2+4.0**(-a)) @@ -85,7 +83,7 @@ assert_quad(quad(myfunc,0,5,args=0.4,weight='cauchy',wvar=2.0), tabledValue, errTol=1.9e-8) - def check_double_integral(self): + def test_double_integral(self): # 8) Double Integral test def simpfunc(y,x): # Note order of arguments. return x+y @@ -94,7 +92,7 @@ assert_quad(dblquad(simpfunc,a,b,lambda x: x, lambda x: 2*x), 5/6.0 * (b**3.0-a**3.0)) - def check_triple_integral(self): + def test_triple_integral(self): # 9) Triple Integral test def simpfunc(z,y,x): # Note order of arguments. return x+y+z @@ -106,4 +104,4 @@ 8/3.0 * (b**4.0 - a**4.0)) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/integrate/tests/test_quadrature.py =================================================================== --- trunk/scipy/integrate/tests/test_quadrature.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/integrate/tests/test_quadrature.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,17 +1,15 @@ import numpy from numpy import cos, sin, pi -from numpy.testing import * +from scipy.testing import * -set_package_path() from scipy.integrate import quadrature, romberg, romb -restore_path() -class TestQuadrature(NumpyTestCase): +class TestQuadrature(TestCase): def quad(self, x, a, b, args): raise NotImplementedError - def check_quadrature(self): + def test_quadrature(self): # Typical function with two extra arguments: def myfunc(x,n,z): # Bessel function integrand return cos(n*x-z*sin(x))/pi @@ -19,7 +17,7 @@ table_val = 0.30614353532540296487 assert_almost_equal(val, table_val, decimal=7) - def check_romberg(self): + def test_romberg(self): # Typical function with two extra arguments: def myfunc(x, n, z): # Bessel function integrand return cos(n*x-z*sin(x))/pi @@ -27,8 +25,8 @@ table_val = 0.30614353532540296487 assert_almost_equal(val, table_val, decimal=7) - def check_romb(self): + def test_romb(self): assert_equal(romb(numpy.arange(17)),128) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/interpolate/__init__.py =================================================================== --- trunk/scipy/interpolate/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/interpolate/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -11,5 +11,5 @@ from fitpack2 import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/interpolate/tests/test_fitpack.py =================================================================== --- trunk/scipy/interpolate/tests/test_fitpack.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/interpolate/tests/test_fitpack.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -13,17 +13,15 @@ #import libwadpy import sys -from numpy.testing import * +from scipy.testing import * from numpy import array -set_package_path() -from interpolate.fitpack2 import UnivariateSpline,LSQUnivariateSpline,\ +from scipy.interpolate.fitpack2 import UnivariateSpline,LSQUnivariateSpline,\ InterpolatedUnivariateSpline -from interpolate.fitpack2 import LSQBivariateSpline, SmoothBivariateSpline,\ - RectBivariateSpline -restore_path() +from scipy.interpolate.fitpack2 import LSQBivariateSpline, \ + SmoothBivariateSpline, RectBivariateSpline -class TestUnivariateSpline(NumpyTestCase): - def check_linear_constant(self): +class TestUnivariateSpline(TestCase): + def test_linear_constant(self): x = [1,2,3] y = [3,3,3] lut = UnivariateSpline(x,y,k=1) @@ -32,7 +30,7 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2]),[3,3,3]) - def check_linear_1d(self): + def test_linear_1d(self): x = [1,2,3] y = [0,2,4] lut = UnivariateSpline(x,y,k=1) @@ -41,8 +39,8 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2]),[0,1,2]) -class TestLSQBivariateSpline(NumpyTestCase): - def check_linear_constant(self): +class TestLSQBivariateSpline(TestCase): + def test_linear_constant(self): x = [1,1,1,2,2,2,3,3,3] y = [1,2,3,1,2,3,1,2,3] z = [3,3,3,3,3,3,3,3,3] @@ -54,8 +52,8 @@ #print lut.get_coeffs() #print lut.get_residual() -class TestSmoothBivariateSpline(NumpyTestCase): - def check_linear_constant(self): +class TestSmoothBivariateSpline(TestCase): + def test_linear_constant(self): x = [1,1,1,2,2,2,3,3,3] y = [1,2,3,1,2,3,1,2,3] z = [3,3,3,3,3,3,3,3,3] @@ -65,7 +63,7 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[3,3],[3,3],[3,3]]) - def check_linear_1d(self): + def test_linear_1d(self): x = [1,1,1,2,2,2,3,3,3] y = [1,2,3,1,2,3,1,2,3] z = [0,0,0,2,2,2,4,4,4] @@ -75,8 +73,8 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[0,0],[1,1],[2,2]]) -class TestRectBivariateSpline(NumpyTestCase): - def check_defaults(self): +class TestRectBivariateSpline(TestCase): + def test_defaults(self): x = array([1,2,3,4,5]) y = array([1,2,3,4,5]) z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) @@ -84,4 +82,4 @@ assert_array_almost_equal(lut(x,y),z) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,13 +1,11 @@ -from numpy.testing import * +from scipy.testing import * from numpy import mgrid, pi, sin, ogrid import numpy as np -set_package_path() -from interpolate import interp1d, interp2d -restore_path() +from scipy.interpolate import interp1d, interp2d -class TestInterp2D(NumpyTestCase): +class TestInterp2D(TestCase): def test_interp2d(self): y, x = mgrid[0:pi:20j, 0:pi:21j] z = sin(x+y) @@ -18,7 +16,7 @@ assert_almost_equal(I(u.ravel(), v.ravel()), sin(v+u), decimal=2) -class TestInterp1D(NumpyTestCase): +class TestInterp1D(TestCase): def setUp(self): self.x10 = np.arange(10.) @@ -202,4 +200,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/io/__init__.py =================================================================== --- trunk/scipy/io/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/io/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -83,8 +83,6 @@ from data_store import save_as_module from mmio import mminfo, mmread, mmwrite - - __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,248 +1,242 @@ #!/usr/bin/env python - +''' Nose test generators ''' import os from glob import glob from cStringIO import StringIO from tempfile import mkstemp -from numpy.testing import set_package_path, restore_path, NumpyTestCase, NumpyTest -from numpy.testing import assert_equal, assert_array_almost_equal +from scipy.testing import * from numpy import arange, array, eye, pi, cos, exp, sin, sqrt, ndarray, \ zeros, reshape, transpose, empty import scipy.sparse as SP -set_package_path() -from matlab.mio import loadmat, savemat -from matlab.mio5 import mat_obj, mat_struct -restore_path() +from scipy.io.matlab.mio import loadmat, savemat +from scipy.io.matlab.mio5 import mat_obj, mat_struct try: # Python 2.3 support from sets import Set as set except: pass -test_data_path = os.path.join(os.path.dirname(__file__), './data') +test_data_path = os.path.join(os.path.dirname(__file__), 'data') -class TestMIOArray(NumpyTestCase): - def __init__(self, *args, **kwargs): - super(TestMIOArray, self).__init__(*args, **kwargs) +def _check_level(self, label, expected, actual): + """ Check one level of a potentially nested object / list """ + # object array is returned from cell array in mat file + typex = type(expected) + typac = type(actual) + if isinstance(expected, ndarray) and expected.dtype.hasobject: + assert typex is typac, "Different types at %s" % label + assert len(expected) == len(actual), "Different list lengths at %s" % label + for i, ev in enumerate(expected): + level_label = "%s, [%d], " % (label, i) + self._check_level(level_label, ev, actual[i]) + return + # object, as container for matlab structs and objects + elif isinstance(expected, mat_struct) or isinstance(expected, mat_obj): + assert isinstance(actual, typex), \ + "Different types %s and %s at %s" % (typex, typac, label) + ex_fields = dir(expected) + ac_fields = dir(actual) + for k in ex_fields: + if k.startswith('__') and k.endswith('__'): + continue + assert k in ac_fields, "Missing property at %s" % label + ev = expected.__dict__[k] + v = actual.__dict__[k] + level_label = "%s, property %s, " % (label, k) + self._check_level(level_label, ev, v) + return + # hoping this is a single value, which might be an array + if SP.issparse(expected): + assert SP.issparse(actual), "Expected sparse at %s" % label + assert_array_almost_equal(actual.todense(), + expected.todense(), + err_msg = label, + decimal = 5) + elif isinstance(expected, ndarray): + if expected.shape: # allow scalar and 0d array comparisons + assert isinstance(actual, ndarray), "Expected ndarray at %s" % label + assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) + else: + assert isinstance(expected, typac), \ + "Types %s and %s do not match at %s" % (typex, typac, label) + assert_equal(actual, expected, err_msg=label) - def _check_level(self, label, expected, actual): - """ Check one level of a potentially nested object / list """ - # object array is returned from cell array in mat file - typex = type(expected) - typac = type(actual) - if isinstance(expected, ndarray) and expected.dtype.hasobject: - assert typex is typac, "Different types at %s" % label - assert len(expected) == len(actual), "Different list lengths at %s" % label - for i, ev in enumerate(expected): - level_label = "%s, [%d], " % (label, i) - self._check_level(level_label, ev, actual[i]) - return - # object, as container for matlab structs and objects - elif isinstance(expected, mat_struct) or isinstance(expected, mat_obj): - assert isinstance(actual, typex), \ - "Different types %s and %s at %s" % (typex, typac, label) - ex_fields = dir(expected) - ac_fields = dir(actual) - for k in ex_fields: - if k.startswith('__') and k.endswith('__'): - continue - assert k in ac_fields, "Missing property at %s" % label - ev = expected.__dict__[k] - v = actual.__dict__[k] - level_label = "%s, property %s, " % (label, k) - self._check_level(level_label, ev, v) - return - # hoping this is a single value, which might be an array - if SP.issparse(expected): - assert SP.issparse(actual), "Expected sparse at %s" % label - assert_array_almost_equal(actual.todense(), - expected.todense(), - err_msg = label, - decimal = 5) - elif isinstance(expected, ndarray): - if expected.shape: # allow scalar and 0d array comparisons - assert isinstance(actual, ndarray), "Expected ndarray at %s" % label - assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) - else: - assert isinstance(expected, typac), \ - "Types %s and %s do not match at %s" % (typex, typac, label) - assert_equal(actual, expected, err_msg=label) +def _check_case(self, name, files, case): + for file_name in files: + matdict = loadmat(file_name) + label = "test %s; file %s" % (name, file_name) + for k, expected in case.items(): + k_label = "%s, variable %s" % (label, k) + assert k in matdict, "Missing key at %s" % k_label + self._check_level(k_label, expected, matdict[k]) - def _check_case(self, name, files, case): - for file_name in files: - matdict = loadmat(file_name) - label = "test %s; file %s" % (name, file_name) - for k, expected in case.items(): - k_label = "%s, variable %s" % (label, k) - assert k in matdict, "Missing key at %s" % k_label - self._check_level(k_label, expected, matdict[k]) +# Add the load tests dynamically, with given parameters +def _make_check_case(name, files, expected): + def cc(self): + self._check_case(name, files, expected) + cc.__doc__ = "check loadmat case %s" % name + return cc - # Add the load tests dynamically, with given parameters - def _make_check_case(name, files, expected): - def cc(self): - self._check_case(name, files, expected) - cc.__doc__ = "check loadmat case %s" % name - return cc +# Add the round trip tests dynamically, with given parameters +def _make_rt_check_case(name, expected, format): + def cc(self): + mat_stream = StringIO() + savemat(mat_stream, expected, format=format) + mat_stream.seek(0) + self._check_case(name, [mat_stream], expected) + cc.__doc__ = "check loadmat case %s" % name + return cc - # Add the round trip tests dynamically, with given parameters - def _make_rt_check_case(name, expected, format): - def cc(self): - mat_stream = StringIO() - savemat(mat_stream, expected, format=format) - mat_stream.seek(0) - self._check_case(name, [mat_stream], expected) - cc.__doc__ = "check loadmat case %s" % name - return cc +# Define cases to test +theta = pi/4*arange(9,dtype=float) +case_table4 = [ + {'name': 'double', + 'expected': {'testdouble': theta} + }] +case_table4.append( + {'name': 'string', + 'expected': {'teststring': u'"Do nine men interpret?" "Nine men," I nod.'}, + }) +case_table4.append( + {'name': 'complex', + 'expected': {'testcomplex': cos(theta) + 1j*sin(theta)} + }) +A = zeros((3,5)) +A[0] = range(1,6) +A[:,0] = range(1,4) +case_table4.append( + {'name': 'matrix', + 'expected': {'testmatrix': A}, + }) +case_table4.append( + {'name': 'sparse', + 'expected': {'testsparse': SP.csc_matrix(A)}, + }) +B = A.astype(complex) +B[0,0] += 1j +case_table4.append( + {'name': 'sparsecomplex', + 'expected': {'testsparsecomplex': SP.csc_matrix(B)}, + }) +case_table4.append( + {'name': 'multi', + 'expected': {'theta': theta, + 'a': A}, + }) +case_table4.append( + {'name': 'minus', + 'expected': {'testminus': array(-1)}, + }) +case_table4.append( + {'name': 'onechar', + 'expected': {'testonechar': u'r'}, + }) +case_table5 = [ + {'name': 'cell', + 'expected': {'testcell': + array([u'This cell contains this string and 3 arrays of '+\ + 'increasing length', + array(1), array([1,2]), array([1,2,3])], + dtype=object)} + }] +case_table5.append( + {'name': 'emptycell', + 'expected': {'testemptycell': + array([array(1), array(2), array([]), + array([]), array(3)], dtype=object)} + }) +case_table5.append( + {'name': 'stringarray', + 'expected': {'teststringarray': array( + [u'one ', u'two ', u'three'], dtype=object)}, + }) +case_table5.append( + {'name': '3dmatrix', + 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} + }) +case_table5_rt = [ + {'name': '3dmatrix', + 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} + }, + {'name': 'sparsefloat', + 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, + }, + {'name': 'sparsecomplex', + 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, + }, + ] +st = mat_struct() +st.stringfield = u'Rats live on no evil star.' +st.doublefield = array([sqrt(2),exp(1),pi]) +st.complexfield = (1+1j)*array([sqrt(2),exp(1),pi]) +case_table5.append( + {'name': 'struct', + 'expected': {'teststruct': st} + }) +a = array([array(1), + array([array(2), array(3), + array([array(4), array(5)], + dtype=object)], + dtype=object)], + dtype=object) +case_table5.append( + {'name': 'cellnest', + 'expected': {'testcellnest': a}, + }) +st = mat_struct() +st.one = array(1) +st.two = mat_struct() +st.two.three = u'number 3' +case_table5.append( + {'name': 'structnest', + 'expected': {'teststructnest': st} + }) +a = array([mat_struct(), mat_struct()]) +a[0].one = array(1) +a[0].two = array(2) +a[1].one = u'number 1' +a[1].two = u'number 2' +case_table5.append( + {'name': 'structarr', + 'expected': {'teststructarr': a} + }) +a = mat_obj() +a._classname = 'inline' +a.expr = u'x' +a.inputExpr = u' x = INLINE_INPUTS_{1};' +a.args = u'x' +a.isEmpty = array(0) +a.numArgs = array(1) +a.version = array(1) +case_table5.append( + {'name': 'object', + 'expected': {'testobject': a} + }) +u_str = file( + os.path.join(test_data_path, 'japanese_utf8.txt'), + 'rb').read().decode('utf-8') +case_table5.append( + {'name': 'unicode', + 'expected': {'testunicode': u_str} + }) - # Define cases to test - theta = pi/4*arange(9,dtype=float) - case_table4 = [ - {'name': 'double', - 'expected': {'testdouble': theta} - }] - case_table4.append( - {'name': 'string', - 'expected': {'teststring': u'"Do nine men interpret?" "Nine men," I nod.'}, - }) - case_table4.append( - {'name': 'complex', - 'expected': {'testcomplex': cos(theta) + 1j*sin(theta)} - }) - A = zeros((3,5)) - A[0] = range(1,6) - A[:,0] = range(1,4) - case_table4.append( - {'name': 'matrix', - 'expected': {'testmatrix': A}, - }) - case_table4.append( - {'name': 'sparse', - 'expected': {'testsparse': SP.csc_matrix(A)}, - }) - B = A.astype(complex) - B[0,0] += 1j - case_table4.append( - {'name': 'sparsecomplex', - 'expected': {'testsparsecomplex': SP.csc_matrix(B)}, - }) - case_table4.append( - {'name': 'multi', - 'expected': {'theta': theta, - 'a': A}, - }) - case_table4.append( - {'name': 'minus', - 'expected': {'testminus': array(-1)}, - }) - case_table4.append( - {'name': 'onechar', - 'expected': {'testonechar': u'r'}, - }) - case_table5 = [ - {'name': 'cell', - 'expected': {'testcell': - array([u'This cell contains this string and 3 arrays of '+\ - 'increasing length', - array(1), array([1,2]), array([1,2,3])], - dtype=object)} - }] - case_table5.append( - {'name': 'emptycell', - 'expected': {'testemptycell': - array([array(1), array(2), array([]), - array([]), array(3)], dtype=object)} - }) - case_table5.append( - {'name': 'stringarray', - 'expected': {'teststringarray': array( - [u'one ', u'two ', u'three'], dtype=object)}, - }) - case_table5.append( - {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }) - case_table5_rt = [ - {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} - }, - {'name': 'sparsefloat', - 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, - }, - {'name': 'sparsecomplex', - 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, - }, - ] - st = mat_struct() - st.stringfield = u'Rats live on no evil star.' - st.doublefield = array([sqrt(2),exp(1),pi]) - st.complexfield = (1+1j)*array([sqrt(2),exp(1),pi]) - case_table5.append( - {'name': 'struct', - 'expected': {'teststruct': st} - }) - a = array([array(1), - array([array(2), array(3), - array([array(4), array(5)], - dtype=object)], - dtype=object)], - dtype=object) - case_table5.append( - {'name': 'cellnest', - 'expected': {'testcellnest': a}, - }) - st = mat_struct() - st.one = array(1) - st.two = mat_struct() - st.two.three = u'number 3' - case_table5.append( - {'name': 'structnest', - 'expected': {'teststructnest': st} - }) - a = array([mat_struct(), mat_struct()]) - a[0].one = array(1) - a[0].two = array(2) - a[1].one = u'number 1' - a[1].two = u'number 2' - case_table5.append( - {'name': 'structarr', - 'expected': {'teststructarr': a} - }) - a = mat_obj() - a._classname = 'inline' - a.expr = u'x' - a.inputExpr = u' x = INLINE_INPUTS_{1};' - a.args = u'x' - a.isEmpty = array(0) - a.numArgs = array(1) - a.version = array(1) - case_table5.append( - {'name': 'object', - 'expected': {'testobject': a} - }) - u_str = file( - os.path.join(test_data_path, 'japanese_utf8.txt'), - 'rb').read().decode('utf-8') - case_table5.append( - {'name': 'unicode', - 'expected': {'testunicode': u_str} - }) - # add load tests +# generator for load tests +def test_load(): for case in case_table4 + case_table5: name = case['name'] expected = case['expected'] filt = os.path.join(test_data_path, 'test%s_*.mat' % name) files = glob(filt) assert files, "No files for test %s using filter %s" % (name, filt) - exec 'check_%s = _make_check_case(name, files, expected)' % name + yield _make_check_case, name, files, expected + # round trip tests +def test_round_trip(): for case in case_table4 + case_table5_rt: name = case['name'] + '_round_trip' expected = case['expected'] format = case in case_table4 and '4' or '5' - exec 'check_%s = _make_rt_check_case(name, expected, format)' \ - % name + yield _make_rt_check_case, name, expected, format -if __name__ == "__main__": - NumpyTest().run() Modified: trunk/scipy/lib/__init__.py =================================================================== --- trunk/scipy/lib/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/lib/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,5 +1,5 @@ from info import __doc__, __all__ -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/lib/blas/__init__.py =================================================================== --- trunk/scipy/lib/blas/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/lib/blas/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -58,5 +58,5 @@ funcs.append(func) return tuple(funcs) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/lib/blas/tests/test_blas.py =================================================================== --- trunk/scipy/lib/blas/tests/test_blas.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/lib/blas/tests/test_blas.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -12,21 +12,18 @@ python tests/test_blas.py [] """ +import sys +import math from numpy import arange, add, array -import math +from scipy.testing import * +from scipy.lib.blas import fblas +from scipy.lib.blas import cblas +from scipy.lib.blas import get_blas_funcs -import sys -from numpy.testing import * -set_package_path() -from blas import fblas -from blas import cblas -from blas import get_blas_funcs -restore_path() +class TestCBLAS1Simple(TestCase): -class TestCBLAS1Simple(NumpyTestCase): - - def check_axpy(self): + def test_axpy(self): for p in 'sd': f = getattr(cblas,p+'axpy',None) if f is None: continue @@ -36,9 +33,9 @@ if f is None: continue assert_array_almost_equal(f([1,2j,3],[2,-1,3],a=5),[7,10j-1,18]) -class TestFBLAS1Simple(NumpyTestCase): +class TestFBLAS1Simple(TestCase): - def check_axpy(self): + def test_axpy(self): for p in 'sd': f = getattr(fblas,p+'axpy',None) if f is None: continue @@ -47,7 +44,7 @@ f = getattr(fblas,p+'axpy',None) if f is None: continue assert_array_almost_equal(f([1,2j,3],[2,-1,3],a=5),[7,10j-1,18]) - def check_copy(self): + def test_copy(self): for p in 'sd': f = getattr(fblas,p+'copy',None) if f is None: continue @@ -56,7 +53,7 @@ f = getattr(fblas,p+'copy',None) if f is None: continue assert_array_almost_equal(f([3,4j,5+3j],[8]*3),[3,4j,5+3j]) - def check_asum(self): + def test_asum(self): for p in 'sd': f = getattr(fblas,p+'asum',None) if f is None: continue @@ -65,7 +62,7 @@ f = getattr(fblas,p+'asum',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j]),14) - def check_dot(self): + def test_dot(self): for p in 'sd': f = getattr(fblas,p+'dot',None) if f is None: continue @@ -76,7 +73,7 @@ assert_almost_equal(f([3j,-4,3-4j],[2,3,1]),-9+2j) f = getattr(fblas,p+'dotc') assert_almost_equal(f([3j,-4,3-4j],[2,3j,1]),3-14j) - def check_nrm2(self): + def test_nrm2(self): for p in 'sd': f = getattr(fblas,p+'nrm2',None) if f is None: continue @@ -85,7 +82,7 @@ f = getattr(fblas,p+'nrm2',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j]),math.sqrt(50)) - def check_scal(self): + def test_scal(self): for p in 'sd': f = getattr(fblas,p+'scal',None) if f is None: continue @@ -98,7 +95,7 @@ f = getattr(fblas,p+'scal',None) if f is None: continue assert_array_almost_equal(f(3,[3j,-4,3-4j]),[9j,-12,9-12j]) - def check_swap(self): + def test_swap(self): for p in 'sd': f = getattr(fblas,p+'swap',None) if f is None: continue @@ -113,7 +110,7 @@ x1,y1 = f(x,y) assert_array_almost_equal(x1,y) assert_array_almost_equal(y1,x) - def check_amax(self): + def test_amax(self): for p in 'sd': f = getattr(fblas,'i'+p+'amax') assert_equal(f([-2,4,3]),1) @@ -122,9 +119,9 @@ assert_equal(f([-5,4+3j,6]),1) #XXX: need tests for rot,rotm,rotg,rotmg -class TestFBLAS2Simple(NumpyTestCase): +class TestFBLAS2Simple(TestCase): - def check_gemv(self): + def test_gemv(self): for p in 'sd': f = getattr(fblas,p+'gemv',None) if f is None: continue @@ -136,7 +133,7 @@ assert_array_almost_equal(f(3j,[[3-4j]],[-4]),[-48-36j]) assert_array_almost_equal(f(3j,[[3-4j]],[-4],3,[5j]),[-48-21j]) - def check_ger(self): + def test_ger(self): for p in 'sd': f = getattr(fblas,p+'ger',None) @@ -170,9 +167,9 @@ 2j, 3j],[3j,4j]),[[6,8],[12,16],[18,24]]) -class TestFBLAS3Simple(NumpyTestCase): +class TestFBLAS3Simple(TestCase): - def check_gemm(self): + def test_gemm(self): for p in 'sd': f = getattr(fblas,p+'gemm',None) if f is None: continue @@ -188,22 +185,22 @@ assert_array_almost_equal(f(1,[[1,2],[1,2]],[[3],[4]]),[[11],[11]]) assert_array_almost_equal(f(1,[[1,2]],[[3,3],[4,4]]),[[11,11]]) - def check_gemm2(self): + def test_gemm2(self): for p in 'sdcz': f = getattr(fblas,p+'gemm',None) if f is None: continue assert_array_almost_equal(f(1,[[1,2]],[[3],[4]]),[[11]]) assert_array_almost_equal(f(1,[[1,2],[1,2]],[[3],[4]]),[[11],[11]]) -class TestBLAS(NumpyTestCase): +class TestBLAS(TestCase): - def check_blas(self): + def test_blas(self): a = array([[1,1,1]]) b = array([[1],[1],[1]]) gemm, = get_blas_funcs(('gemm',),(a,b)) assert_array_almost_equal(gemm(1,a,b),[[3]],15) - def check_fblas(self): + def test_fblas(self): if hasattr(fblas,'empty_module'): print """ **************************************************************** @@ -212,7 +209,7 @@ See scipy/INSTALL.txt for troubleshooting. **************************************************************** """ - def check_cblas(self): + def test_cblas(self): if hasattr(cblas,'empty_module'): print """ **************************************************************** @@ -226,4 +223,4 @@ """ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/lib/blas/tests/test_fblas.py =================================================================== --- trunk/scipy/lib/blas/tests/test_fblas.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/lib/blas/tests/test_fblas.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -6,13 +6,12 @@ # !! Complex calculations really aren't checked that carefully. # !! Only real valued complex numbers are used in tests. -from numpy import * - import sys -from numpy.testing import * -set_package_path() -from blas import fblas -restore_path() +from numpy import zeros, transpose, newaxis, shape, float32, \ + float64, complex64, complex128, arange, array, common_type, \ + conjugate +from scipy.testing import * +from scipy.lib.blas import fblas #decimal accuracy to require between Python and LAPACK/BLAS calculations accuracy = 5 @@ -40,39 +39,40 @@ ################################################## ### Test blas ?axpy -class BaseAxpy(NumpyTestCase): - def check_default_a(self): +class BaseAxpy(object): + # Mixin class to test dtypes + def test_default_a(self): x = arange(3.,dtype=self.dtype) y = arange(3.,dtype=x.dtype) real_y = x*1.+y self.blas_func(x,y) assert_array_almost_equal(real_y,y) - def check_simple(self): + def test_simple(self): x = arange(3.,dtype=self.dtype) y = arange(3.,dtype=x.dtype) real_y = x*3.+y self.blas_func(x,y,a=3.) assert_array_almost_equal(real_y,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) y = arange(3.,dtype=x.dtype) real_y = x[::2]*3.+y self.blas_func(x,y,a=3.,n=3,incx=2) assert_array_almost_equal(real_y,y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) real_y = x*3.+y[::2] self.blas_func(x,y,a=3.,n=3,incy=2) assert_array_almost_equal(real_y,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) real_y = x[::4]*3.+y[::2] self.blas_func(x,y,a=3.,n=3,incx=4,incy=2) assert_array_almost_equal(real_y,y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -81,7 +81,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -92,21 +92,21 @@ assert(0) try: - class TestSaxpy(BaseAxpy): + class TestSaxpy(TestCase, BaseAxpy): blas_func = fblas.saxpy dtype = float32 except AttributeError: class TestSaxpy: pass -class TestDaxpy(BaseAxpy): +class TestDaxpy(TestCase, BaseAxpy): blas_func = fblas.daxpy dtype = float64 try: - class TestCaxpy(BaseAxpy): + class TestCaxpy(TestCase, BaseAxpy): blas_func = fblas.caxpy dtype = complex64 except AttributeError: class TestCaxpy: pass -class TestZaxpy(BaseAxpy): +class TestZaxpy(TestCase, BaseAxpy): blas_func = fblas.zaxpy dtype = complex128 @@ -114,19 +114,20 @@ ################################################## ### Test blas ?scal -class BaseScal(NumpyTestCase): - def check_simple(self): +class BaseScal(object): + # Mixin class for testing particular dtypes + def test_simple(self): x = arange(3.,dtype=self.dtype) real_x = x*3. self.blas_func(3.,x) assert_array_almost_equal(real_x,x) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) real_x = x.copy() real_x[::2] = x[::2]*array(3.,self.dtype) self.blas_func(3.,x,n=3,incx=2) assert_array_almost_equal(real_x,x) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) try: self.blas_func(2.,x,n=4,incx=5) @@ -135,21 +136,21 @@ # should catch error and never get here assert(0) try: - class TestSscal(BaseScal): + class TestSscal(TestCase, BaseScal): blas_func = fblas.sscal dtype = float32 except AttributeError: class TestSscal: pass -class TestDscal(BaseScal): +class TestDscal(TestCase, BaseScal): blas_func = fblas.dscal dtype = float64 try: - class TestCscal(BaseScal): + class TestCscal(TestCase, BaseScal): blas_func = fblas.cscal dtype = complex64 except AttributeError: class TestCscal: pass -class TestZscal(BaseScal): +class TestZscal(TestCase, BaseScal): blas_func = fblas.zscal dtype = complex128 @@ -159,28 +160,29 @@ ################################################## ### Test blas ?copy -class BaseCopy(NumpyTestCase): - def check_simple(self): +class BaseCopy(object): + # Mixin class for testing dtypes + def test_simple(self): x = arange(3.,dtype=self.dtype) y = zeros(shape(x),x.dtype) self.blas_func(x,y) assert_array_almost_equal(x,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) self.blas_func(x,y,n=3,incx=2) assert_array_almost_equal(x[::2],y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) self.blas_func(x,y,n=3,incy=2) assert_array_almost_equal(x,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) self.blas_func(x,y,n=3,incx=4,incy=2) assert_array_almost_equal(x[::4],y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -189,7 +191,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -198,7 +200,7 @@ return # should catch error and never get here assert(0) - #def check_y_bad_type(self): + #def test_y_bad_type(self): ## Hmmm. Should this work? What should be the output. # x = arange(3.,dtype=self.dtype) # y = zeros(shape(x)) @@ -206,21 +208,21 @@ # assert_array_almost_equal(x,y) try: - class TestScopy(BaseCopy): + class TestScopy(TestCase, BaseCopy): blas_func = fblas.scopy dtype = float32 except AttributeError: class TestScopy: pass -class TestDcopy(BaseCopy): +class TestDcopy(TestCase, BaseCopy): blas_func = fblas.dcopy dtype = float64 try: - class TestCcopy(BaseCopy): + class TestCcopy(TestCase, BaseCopy): blas_func = fblas.ccopy dtype = complex64 except AttributeError: class TestCcopy: pass -class TestZcopy(BaseCopy): +class TestZcopy(TestCase, BaseCopy): blas_func = fblas.zcopy dtype = complex128 @@ -228,8 +230,9 @@ ################################################## ### Test blas ?swap -class BaseSwap(NumpyTestCase): - def check_simple(self): +class BaseSwap(object): + # Mixin class to implement test objects + def test_simple(self): x = arange(3.,dtype=self.dtype) y = zeros(shape(x),x.dtype) desired_x = y.copy() @@ -237,7 +240,7 @@ self.blas_func(x,y) assert_array_almost_equal(desired_x,x) assert_array_almost_equal(desired_y,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) desired_x = y.copy() @@ -245,7 +248,7 @@ self.blas_func(x,y,n=3,incx=2) assert_array_almost_equal(desired_x,x[::2]) assert_array_almost_equal(desired_y,y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) desired_x = y.copy()[::2] @@ -254,7 +257,7 @@ assert_array_almost_equal(desired_x,x) assert_array_almost_equal(desired_y,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) desired_x = y.copy()[::2] @@ -262,7 +265,7 @@ self.blas_func(x,y,n=3,incx=4,incy=2) assert_array_almost_equal(desired_x,x[::4]) assert_array_almost_equal(desired_y,y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -271,7 +274,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -282,21 +285,21 @@ assert(0) try: - class TestSswap(BaseSwap): + class TestSswap(TestCase, BaseSwap): blas_func = fblas.sswap dtype = float32 except AttributeError: class TestSswap: pass -class TestDswap(BaseSwap): +class TestDswap(TestCase, BaseSwap): blas_func = fblas.dswap dtype = float64 try: - class TestCswap(BaseSwap): + class TestCswap(TestCase, BaseSwap): blas_func = fblas.cswap dtype = complex64 except AttributeError: class TestCswap: pass -class TestZswap(BaseSwap): +class TestZswap(TestCase, BaseSwap): blas_func = fblas.zswap dtype = complex128 @@ -304,7 +307,8 @@ ### Test blas ?gemv ### This will be a mess to test all cases. -class BaseGemv(NumpyTestCase): +class BaseGemv(object): + # Mixin class to test dtypes def get_data(self,x_stride=1,y_stride=1): mult = array(1, dtype = self.dtype) if self.dtype in [complex64, complex128]: @@ -316,37 +320,37 @@ x = arange(shape(a)[0]*x_stride,dtype=self.dtype) * mult y = arange(shape(a)[1]*y_stride,dtype=self.dtype) * mult return alpha,beta,a,x,y - def check_simple(self): + def test_simple(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(a,x)+beta*y y = self.blas_func(alpha,a,x,beta,y) assert_array_almost_equal(desired_y,y) - def check_default_beta_y(self): + def test_default_beta_y(self): alpha,beta,a,x,y = self.get_data() desired_y = matrixmultiply(a,x) y = self.blas_func(1,a,x) assert_array_almost_equal(desired_y,y) - def check_simple_transpose(self): + def test_simple_transpose(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(transpose(a),x)+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=1) assert_array_almost_equal(desired_y,y) - def check_simple_transpose_conj(self): + def test_simple_transpose_conj(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(transpose(conjugate(a)),x)+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=2) assert_array_almost_equal(desired_y,y) - def check_x_stride(self): + def test_x_stride(self): alpha,beta,a,x,y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(a,x[::2])+beta*y y = self.blas_func(alpha,a,x,beta,y,incx=2) assert_array_almost_equal(desired_y,y) - def check_x_stride_transpose(self): + def test_x_stride_transpose(self): alpha,beta,a,x,y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(transpose(a),x[::2])+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=1,incx=2) assert_array_almost_equal(desired_y,y) - def check_x_stride_assert(self): + def test_x_stride_assert(self): # What is the use of this test? alpha,beta,a,x,y = self.get_data(x_stride=2) try: @@ -359,19 +363,19 @@ assert(0) except: pass - def check_y_stride(self): + def test_y_stride(self): alpha,beta,a,x,y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(a,x)+beta*y[::2] y = self.blas_func(alpha,a,x,beta,y,incy=2) assert_array_almost_equal(desired_y,y) - def check_y_stride_transpose(self): + def test_y_stride_transpose(self): alpha,beta,a,x,y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(transpose(a),x)+beta*y[::2] y = self.blas_func(alpha,a,x,beta,y,trans=1,incy=2) assert_array_almost_equal(desired_y,y) - def check_y_stride_assert(self): + def test_y_stride_assert(self): # What is the use of this test? alpha,beta,a,x,y = self.get_data(y_stride=2) try: @@ -386,21 +390,21 @@ pass try: - class TestSgemv(BaseGemv): + class TestSgemv(TestCase, BaseGemv): blas_func = fblas.sgemv dtype = float32 except AttributeError: class TestSgemv: pass -class TestDgemv(BaseGemv): +class TestDgemv(TestCase, BaseGemv): blas_func = fblas.dgemv dtype = float64 try: - class TestCgemv(BaseGemv): + class TestCgemv(TestCase, BaseGemv): blas_func = fblas.cgemv dtype = complex64 except AttributeError: class TestCgemv: pass -class TestZgemv(BaseGemv): +class TestZgemv(TestCase, BaseGemv): blas_func = fblas.zgemv dtype = complex128 @@ -409,7 +413,7 @@ ### Test blas ?ger ### This will be a mess to test all cases. -class BaseGer(NumpyTestCase): +class BaseGer(TestCase): def get_data(self,x_stride=1,y_stride=1): from numpy.random import normal alpha = array(1., dtype = self.dtype) @@ -417,31 +421,31 @@ x = arange(shape(a)[0]*x_stride,dtype=self.dtype) y = arange(shape(a)[1]*y_stride,dtype=self.dtype) return alpha,a,x,y - def check_simple(self): + def test_simple(self): alpha,a,x,y = self.get_data() # tranpose takes care of Fortran vs. C(and Python) memory layout desired_a = alpha*transpose(x[:,newaxis]*y) + a self.blas_func(x,y,a) assert_array_almost_equal(desired_a,a) - def check_x_stride(self): + def test_x_stride(self): alpha,a,x,y = self.get_data(x_stride=2) desired_a = alpha*transpose(x[::2,newaxis]*y) + a self.blas_func(x,y,a,incx=2) assert_array_almost_equal(desired_a,a) - def check_x_stride_assert(self): + def test_x_stride_assert(self): alpha,a,x,y = self.get_data(x_stride=2) try: self.blas_func(x,y,a,incx=3) assert(0) except: pass - def check_y_stride(self): + def test_y_stride(self): alpha,a,x,y = self.get_data(y_stride=2) desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a self.blas_func(x,y,a,incy=2) assert_array_almost_equal(desired_a,a) - def check_y_stride_assert(self): + def test_y_stride_assert(self): alpha,a,x,y = self.get_data(y_stride=2) try: self.blas_func(a,x,y,incy=3) @@ -472,7 +476,7 @@ y = normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype) y = y + y * array(1j, dtype = self.dtype) return alpha,a,x,y - def check_simple(self): + def test_simple(self): alpha,a,x,y = self.get_data() # tranpose takes care of Fortran vs. C(and Python) memory layout a = a * array(0.,dtype = self.dtype) @@ -482,12 +486,12 @@ fblas.cgeru(x,y,a,alpha = alpha) assert_array_almost_equal(desired_a,a) - #def check_x_stride(self): + #def test_x_stride(self): # alpha,a,x,y = self.get_data(x_stride=2) # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a # self.blas_func(x,y,a,incx=2) # assert_array_almost_equal(desired_a,a) - #def check_y_stride(self): + #def test_y_stride(self): # alpha,a,x,y = self.get_data(y_stride=2) # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a # self.blas_func(x,y,a,incy=2) @@ -518,4 +522,4 @@ """ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/lib/lapack/__init__.py =================================================================== --- trunk/scipy/lib/lapack/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/lib/lapack/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -90,5 +90,5 @@ func_code = %(func_name)s.func_code ''' -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/lib/lapack/tests/esv_tests.py =================================================================== --- trunk/scipy/lib/lapack/tests/esv_tests.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/lib/lapack/tests/esv_tests.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,10 +1,10 @@ -from numpy.testing import * -from numpy import * +from scipy.testing import * +from numpy import dot -class _test_ev: +class _test_ev(object): - def check_syev(self,level=1,sym='sy',suffix=''): + def check_syev(self,sym='sy',suffix=''): a = [[1,2,3],[2,2,3],[3,3,6]] exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] f = getattr(self.lapack,sym+'ev'+suffix) @@ -20,7 +20,7 @@ #def check_heevd(self): self.check_syev(sym='he',suffix='d') -## def check_heev_complex(self,level=1,suffix=''): +## def check_heev_complex(self,suffix=''): ## a= [[1,2-2j,3+7j],[2+2j,2,3],[3-7j,3,5]] ## exact_w=[-6.305141710654834,2.797880950890922,11.50726075976392] ## f = getattr(self.lapack,'heev'+suffix) @@ -32,7 +32,7 @@ #def check_heevd_complex(self): self.check_heev_complex(suffix='d') - def check_syevr(self,level=1,sym='sy'): + def check_syevr(self,sym='sy'): a = [[1,2,3],[2,2,3],[3,3,6]] exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] f = getattr(self.lapack,sym+'evr') @@ -42,7 +42,7 @@ for i in range(3): assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i]) -## def check_heevr_complex(self,level=1): +## def check_heevr_complex(self): ## a= [[1,2-2j,3+7j],[2+2j,2,3],[3-7j,3,5]] ## exact_w=[-6.305141710654834,2.797880950890922,11.50726075976392] ## f = self.lapack.heevr @@ -54,7 +54,7 @@ ## def check_heevr(self): self.check_syevr(sym='he') - def check_syevr_irange(self,level=1,sym='sy',irange=[0,2]): + def check_syevr_irange(self,sym='sy',irange=[0,2]): a = [[1,2,3],[2,2,3],[3,3,6]] exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] f = getattr(self.lapack,sym+'evr') @@ -79,7 +79,7 @@ ## def check_heevr_irange_high(self): self.check_syevr_irange(sym='he',irange=[1,2]) - def check_syevr_vrange(self,level=1,sym='sy',vrange=None): + def check_syevr_vrange(self,sym='sy',vrange=None): a = [[1,2,3],[2,2,3],[3,3,6]] exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] if vrange is None: Modified: trunk/scipy/lib/lapack/tests/gesv_tests.py =================================================================== --- trunk/scipy/lib/lapack/tests/gesv_tests.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/lib/lapack/tests/gesv_tests.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,10 +1,10 @@ -from numpy.testing import * -from numpy import * +from scipy.testing import * +from numpy import dot -class _test_gev: +class _test_gev(object): - def check_sygv(self,level=1,sym='sy',suffix='',itype=1): + def check_sygv(self,sym='sy',suffix='',itype=1): a = [[1,2,3],[2,2,3],[3,3,6]] b = [[10,-1,1],[-1,8,-2],[1,-2,6]] f = getattr(self.lapack,sym+'gv'+suffix) Modified: trunk/scipy/lib/lapack/tests/test_lapack.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_lapack.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/lib/lapack/tests/test_lapack.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -2,33 +2,33 @@ # # Created by: Pearu Peterson, September 2002 # +''' +This file adapted for nose tests 1/1/08 -__usage__ = """ -Build lapack: - python setup_lapack.py build -Run tests if scipy is installed: - python -c 'import scipy;scipy.lib.lapack.test()' -Run tests if lapack is not installed: - python tests/test_lapack.py [] -""" +Note that the conversion is not very complete. +This and the included files deliberately use "check_" as the test +method names. There are no subclasses of TestCase. Thus nose will +pick up nothing but the final test_all_lapack generator function. +This does the work of collecting the test methods and checking if they +can be run (see the isrunnable method). +''' + +import os import sys -from numpy.testing import * -from numpy import * +from scipy.testing import * +from numpy import dot, ones, zeros -set_package_path() -from lapack import flapack,clapack -restore_path() +from scipy.lib.lapack import flapack, clapack -set_local_path() +sys.path.insert(0, os.path.split(__file__)) from gesv_tests import _test_gev from esv_tests import _test_ev -restore_path() +del sys.path[0] #class _test_ev: pass -class _TestLapack(NumpyTestCase, - _test_ev, +class _TestLapack( _test_ev, _test_gev): def check_gebal(self): @@ -57,12 +57,13 @@ assert not info,`info` def isrunnable(self,mthname): + ''' Return True if required routines for check method present in module ''' l = mthname.split('_') if len(l)>1 and l[0]=='check': return hasattr(self.lapack,l[1]) return 2 -class PrefixWrapper: +class PrefixWrapper(object): def __init__(self,module,prefix): self.module = module self.prefix = prefix @@ -122,5 +123,18 @@ lapack = PrefixWrapper(clapack,'z') decimal = 12 -if __name__ == "__main__": - NumpyTest().run() +# Collect test classes and methods with generator +# This is a moderate hack replicating some obscure numpy testing +# functionality for use with nose + +def test_all_lapack(): + methods = [] + for name, value in globals().items(): + if not (name.startswith('Test') + and issubclass(value, _TestLapack)): + continue + o = value() + methods += [getattr(o, n) for n in dir(o) if o.isrunnable(n) is True] + for method in methods: + yield (method, ) + Modified: trunk/scipy/linalg/__init__.py =================================================================== --- trunk/scipy/linalg/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -28,5 +28,5 @@ del k, register_func -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/linalg/tests/test_atlas_version.py =================================================================== --- trunk/scipy/linalg/tests/test_atlas_version.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/tests/test_atlas_version.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,10 +4,10 @@ # import sys -from numpy.testing import * -set_package_path() -import linalg.atlas_version -restore_path() +from scipy.testing import * +import scipy.linalg.atlas_version + + # No futher tests possible. # Importing atlas_version will print out atlas version. Modified: trunk/scipy/linalg/tests/test_basic.py =================================================================== --- trunk/scipy/linalg/tests/test_basic.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/tests/test_basic.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -14,21 +14,21 @@ Build linalg: python setup_linalg.py build Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' + python -c 'import scipy;scipy.linalg.test()' Run tests if linalg is not installed: - python tests/test_basic.py [] + python tests/test_basic.py """ import numpy from numpy import arange, add, array, dot, zeros, identity, conjugate, transpose import sys -from numpy.testing import * -set_package_path() -from linalg import solve,inv,det,lstsq, toeplitz, hankel, tri, triu, tril -from linalg import pinv, pinv2, solve_banded -restore_path() +from scipy.testing import * +from scipy.linalg import solve,inv,det,lstsq, toeplitz, hankel, tri, triu, \ + tril, pinv, pinv2, solve_banded + + def random(size): return rand(*size) @@ -37,9 +37,9 @@ data = add.outer(data,data) return data -class TestSolveBanded(NumpyTestCase): +class TestSolveBanded(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,20,0,0],[-30,4,6,0],[2,1,20,2],[0,-1,7,14]] ab = [[0,20,6,2], @@ -52,9 +52,9 @@ x = solve_banded((l,u),ab,b) assert_array_almost_equal(numpy.dot(a,x),b) -class TestSolve(NumpyTestCase): +class TestSolve(TestCase): - def check_20Feb04_bug(self): + def test_20Feb04_bug(self): a = [[1,1],[1.0,0]] # ok x0 = solve(a,[1,0j]) assert_array_almost_equal(numpy.dot(a,x0),[1,0]) @@ -64,21 +64,21 @@ x0 = solve(a,b) assert_array_almost_equal(numpy.dot(a,x0),[1,0]) - def check_simple(self): + def test_simple(self): a = [[1,20],[-30,4]] for b in ([[1,0],[0,1]],[1,0], [[2,1],[-30,4]]): x = solve(a,b) assert_array_almost_equal(numpy.dot(a,x),b) - def check_simple_sym(self): + def test_simple_sym(self): a = [[2,3],[3,5]] for lower in [0,1]: for b in ([[1,0],[0,1]],[1,0]): x = solve(a,b,sym_pos=1,lower=lower) assert_array_almost_equal(numpy.dot(a,x),b) - def check_simple_sym_complex(self): + def test_simple_sym_complex(self): a = [[5,2],[2,4]] for b in [[1j,0], [[1j,1j], @@ -87,7 +87,7 @@ x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.dot(a,x),b) - def check_simple_complex(self): + def test_simple_complex(self): a = array([[5,2],[2j,4]],'D') for b in [[1j,0], [[1j,1j], @@ -98,7 +98,7 @@ x = solve(a,b) assert_array_almost_equal(numpy.dot(a,x),b) - def check_nils_20Feb04(self): + def test_nils_20Feb04(self): n = 2 A = random([n,n])+random([n,n])*1j X = zeros((n,n),'D') @@ -109,7 +109,7 @@ X[:,i] = solve(A,r) assert_array_almost_equal(X,Ainv) - def check_random(self): + def test_random(self): n = 20 a = random([n,n]) @@ -119,7 +119,7 @@ x = solve(a,b) assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_complex(self): + def test_random_complex(self): n = 20 a = random([n,n]) + 1j * random([n,n]) for i in range(n): a[i,i] = 20*(.1+a[i,i]) @@ -128,7 +128,7 @@ x = solve(a,b) assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_sym(self): + def test_random_sym(self): n = 20 a = random([n,n]) for i in range(n): @@ -140,7 +140,7 @@ x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_sym_complex(self): + def test_random_sym_complex(self): n = 20 a = random([n,n]) #a = a + 1j*random([n,n]) # XXX: with this the accuracy will be very low @@ -153,7 +153,8 @@ x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.dot(a,x),b) - def bench_random(self,level=5): + @dec.bench + def test_bench_random(self): import numpy.linalg as linalg basic_solve = linalg.solve print @@ -174,26 +175,26 @@ for i in range(size): a[i,i] = 10*(.1+a[i,i]) b = random([size]) - print '| %6.2f ' % self.measure('solve(a,b)',repeat), + print '| %6.2f ' % measure('solve(a,b)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_solve(a,b)',repeat), + print '| %6.2f ' % measure('basic_solve(a,b)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] - print '| %6.2f ' % self.measure('solve(a,b)',repeat), + print '| %6.2f ' % measure('solve(a,b)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_solve(a,b)',repeat), + print '| %6.2f ' % measure('basic_solve(a,b)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) -class TestInv(NumpyTestCase): +class TestInv(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2],[3,4]] a_inv = inv(a) assert_array_almost_equal(numpy.dot(a,a_inv), @@ -203,7 +204,7 @@ assert_array_almost_equal(numpy.dot(a,a_inv), [[1,0,0],[0,1,0],[0,0,1]]) - def check_random(self): + def test_random(self): n = 20 for i in range(4): a = random([n,n]) @@ -211,13 +212,13 @@ a_inv = inv(a) assert_array_almost_equal(numpy.dot(a,a_inv), numpy.identity(n)) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2],[3,4j]] a_inv = inv(a) assert_array_almost_equal(numpy.dot(a,a_inv), [[1,0],[0,1]]) - def check_random_complex(self): + def test_random_complex(self): n = 20 for i in range(4): a = random([n,n])+2j*random([n,n]) @@ -226,7 +227,8 @@ assert_array_almost_equal(numpy.dot(a,a_inv), numpy.identity(n)) - def bench_random(self,level=5): + @dec.bench + def test_bench_random(self): import numpy.linalg as linalg basic_inv = linalg.inv print @@ -245,37 +247,37 @@ # large diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i]) - print '| %6.2f ' % self.measure('inv(a)',repeat), + print '| %6.2f ' % measure('inv(a)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_inv(a)',repeat), + print '| %6.2f ' % measure('basic_inv(a)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] - print '| %6.2f ' % self.measure('inv(a)',repeat), + print '| %6.2f ' % measure('inv(a)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_inv(a)',repeat), + print '| %6.2f ' % measure('basic_inv(a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) -class TestDet(NumpyTestCase): +class TestDet(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2],[3,4]] a_det = det(a) assert_almost_equal(a_det,-2.0) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2],[3,4j]] a_det = det(a) assert_almost_equal(a_det,-6+4j) - def check_random(self): + def test_random(self): import numpy.linalg as linalg basic_det = linalg.det n = 20 @@ -285,7 +287,7 @@ d2 = basic_det(a) assert_almost_equal(d1,d2) - def check_random_complex(self): + def test_random_complex(self): import numpy.linalg as linalg basic_det = linalg.det n = 20 @@ -295,7 +297,8 @@ d2 = basic_det(a) assert_almost_equal(d1,d2) - def bench_random(self,level=5): + @dec.bench + def test_bench_random(self): import numpy.linalg as linalg basic_det = linalg.det print @@ -312,19 +315,19 @@ a = random([size,size]) - print '| %6.2f ' % self.measure('det(a)',repeat), + print '| %6.2f ' % measure('det(a)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_det(a)',repeat), + print '| %6.2f ' % measure('basic_det(a)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] - print '| %6.2f ' % self.measure('det(a)',repeat), + print '| %6.2f ' % measure('det(a)',repeat), sys.stdout.flush() - print '| %6.2f ' % self.measure('basic_det(a)',repeat), + print '| %6.2f ' % measure('basic_det(a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) @@ -338,8 +341,8 @@ b1 = dot(at, b) return solve(a1, b1) -class TestLstsq(NumpyTestCase): - def check_random_overdet_large(self): +class TestLstsq(TestCase): + def test_random_overdet_large(self): #bug report: Nils Wagner n = 200 a = random([n,2]) @@ -348,21 +351,21 @@ x = lstsq(a,b)[0] assert_array_almost_equal(x,direct_lstsq(a,b)) - def check_simple_exact(self): + def test_simple_exact(self): a = [[1,20],[-30,4]] for b in ([[1,0],[0,1]],[1,0], [[2,1],[-30,4]]): x = lstsq(a,b)[0] assert_array_almost_equal(numpy.dot(a,x),b) - def check_simple_overdet(self): + def test_simple_overdet(self): a = [[1,2],[4,5],[3,4]] b = [1,2,3] x,res,r,s = lstsq(a,b) #XXX: check defintion of res assert_array_almost_equal(x,direct_lstsq(a,b)) - def check_simple_underdet(self): + def test_simple_underdet(self): a = [[1,2,3],[4,5,6]] b = [1,2] x,res,r,s = lstsq(a,b) @@ -370,7 +373,7 @@ assert_array_almost_equal(x,[[-0.05555556], [0.11111111],[0.27777778]]) - def check_random_exact(self): + def test_random_exact(self): n = 20 a = random([n,n]) @@ -380,7 +383,7 @@ x = lstsq(a,b)[0] assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_complex_exact(self): + def test_random_complex_exact(self): n = 20 a = random([n,n]) + 1j * random([n,n]) for i in range(n): a[i,i] = 20*(.1+a[i,i]) @@ -389,7 +392,7 @@ x = lstsq(a,b)[0] assert_array_almost_equal(numpy.dot(a,x),b) - def check_random_overdet(self): + def test_random_overdet(self): n = 20 m = 15 a = random([n,m]) @@ -401,7 +404,7 @@ #XXX: check definition of res assert_array_almost_equal(x,direct_lstsq(a,b)) - def check_random_complex_overdet(self): + def test_random_complex_overdet(self): n = 20 m = 15 a = random([n,m]) + 1j * random([n,m]) @@ -414,8 +417,8 @@ #XXX: check definition of res assert_array_almost_equal(x,direct_lstsq(a,b,1)) -class TestTri(NumpyTestCase): - def check_basic(self): +class TestTri(TestCase): + def test_basic(self): assert_equal(tri(4),array([[1,0,0,0], [1,1,0,0], [1,1,1,0], @@ -424,7 +427,7 @@ [1,1,0,0], [1,1,1,0], [1,1,1,1]],'f')) - def check_diag(self): + def test_diag(self): assert_equal(tri(4,k=1),array([[1,1,0,0], [1,1,1,0], [1,1,1,1], @@ -433,7 +436,7 @@ [1,0,0,0], [1,1,0,0], [1,1,1,0]])) - def check_2d(self): + def test_2d(self): assert_equal(tri(4,3),array([[1,0,0], [1,1,0], [1,1,1], @@ -441,7 +444,7 @@ assert_equal(tri(3,4),array([[1,0,0,0], [1,1,0,0], [1,1,1,0]])) - def check_diag2d(self): + def test_diag2d(self): assert_equal(tri(3,4,k=2),array([[1,1,1,0], [1,1,1,1], [1,1,1,1]])) @@ -450,8 +453,8 @@ [1,0,0], [1,1,0]])) -class TestTril(NumpyTestCase): - def check_basic(self): +class TestTril(TestCase): + def test_basic(self): a = (100*get_mat(5)).astype('l') b = a.copy() for k in range(5): @@ -459,7 +462,7 @@ b[k,l] = 0 assert_equal(tril(a),b) - def check_diag(self): + def test_diag(self): a = (100*get_mat(5)).astype('f') b = a.copy() for k in range(5): @@ -472,8 +475,8 @@ b[k,l] = 0 assert_equal(tril(a,k=-2),b) -class TestTriu(NumpyTestCase): - def check_basic(self): +class TestTriu(TestCase): + def test_basic(self): a = (100*get_mat(5)).astype('l') b = a.copy() for k in range(5): @@ -481,7 +484,7 @@ b[l,k] = 0 assert_equal(triu(a),b) - def check_diag(self): + def test_diag(self): a = (100*get_mat(5)).astype('f') b = a.copy() for k in range(5): @@ -494,46 +497,46 @@ b[l,k] = 0 assert_equal(triu(a,k=-2),b) -class TestToeplitz(NumpyTestCase): - def check_basic(self): +class TestToeplitz(TestCase): + def test_basic(self): y = toeplitz([1,2,3]) assert_array_equal(y,[[1,2,3],[2,1,2],[3,2,1]]) y = toeplitz([1,2,3],[1,4,5]) assert_array_equal(y,[[1,4,5],[2,1,4],[3,2,1]]) -class TestHankel(NumpyTestCase): - def check_basic(self): +class TestHankel(TestCase): + def test_basic(self): y = hankel([1,2,3]) assert_array_equal(y,[[1,2,3],[2,3,0],[3,0,0]]) y = hankel([1,2,3],[3,4,5]) assert_array_equal(y,[[1,2,3],[2,3,4],[3,4,5]]) -class TestPinv(NumpyTestCase): +class TestPinv(TestCase): - def check_simple(self): + def test_simple(self): a=array([[1,2,3],[4,5,6.],[7,8,10]]) a_pinv = pinv(a) assert_array_almost_equal(dot(a,a_pinv),[[1,0,0],[0,1,0],[0,0,1]]) a_pinv = pinv2(a) assert_array_almost_equal(dot(a,a_pinv),[[1,0,0],[0,1,0],[0,0,1]]) - def check_simple_0det(self): + def test_simple_0det(self): a=array([[1,2,3],[4,5,6.],[7,8,9]]) a_pinv = pinv(a) a_pinv2 = pinv2(a) assert_array_almost_equal(a_pinv,a_pinv2) - def check_simple_cols(self): + def test_simple_cols(self): a=array([[1,2,3],[4,5,6.]]) a_pinv = pinv(a) a_pinv2 = pinv2(a) assert_array_almost_equal(a_pinv,a_pinv2) - def check_simple_rows(self): + def test_simple_rows(self): a=array([[1,2],[3,4],[5,6]]) a_pinv = pinv(a) a_pinv2 = pinv2(a) assert_array_almost_equal(a_pinv,a_pinv2) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/linalg/tests/test_blas.py =================================================================== --- trunk/scipy/linalg/tests/test_blas.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/tests/test_blas.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -12,21 +12,19 @@ python tests/test_blas.py [] """ +import sys +import math from numpy import arange, add, array -import math -import sys -from numpy.testing import * -set_package_path() -from linalg import fblas -print fblas -from linalg import cblas -restore_path() +from scipy.testing import * -class TestCBLAS1Simple(NumpyTestCase): +from scipy.linalg import fblas, cblas - def check_axpy(self): + +class TestCBLAS1Simple(TestCase): + + def test_axpy(self): for p in 'sd': f = getattr(cblas,p+'axpy',None) if f is None: continue @@ -36,9 +34,9 @@ if f is None: continue assert_array_almost_equal(f(5,[1,2j,3],[2,-1,3]),[7,10j-1,18]) -class TestFBLAS1Simple(NumpyTestCase): +class TestFBLAS1Simple(TestCase): - def check_axpy(self): + def test_axpy(self): for p in 'sd': f = getattr(fblas,p+'axpy',None) if f is None: continue @@ -47,7 +45,7 @@ f = getattr(fblas,p+'axpy',None) if f is None: continue assert_array_almost_equal(f([1,2j,3],[2,-1,3],a=5),[7,10j-1,18]) - def check_copy(self): + def test_copy(self): for p in 'sd': f = getattr(fblas,p+'copy',None) if f is None: continue @@ -56,7 +54,7 @@ f = getattr(fblas,p+'copy',None) if f is None: continue assert_array_almost_equal(f([3,4j,5+3j],[8]*3),[3,4j,5+3j]) - def check_asum(self): + def test_asum(self): for p in 'sd': f = getattr(fblas,p+'asum',None) if f is None: continue @@ -65,24 +63,24 @@ f = getattr(fblas,p+'asum',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j]),14) - def check_dot(self): + def test_dot(self): for p in 'sd': f = getattr(fblas,p+'dot',None) if f is None: continue assert_almost_equal(f([3,-4,5],[2,5,1]),-9) - def check_complex_dotu(self): + def test_complex_dotu(self): for p in 'cz': f = getattr(fblas,p+'dotu',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j],[2,3,1]),-9+2j) - def check_complex_dotc(self): + def test_complex_dotc(self): for p in 'cz': f = getattr(fblas,p+'dotc',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j],[2,3j,1]),3-14j) - def check_nrm2(self): + def test_nrm2(self): for p in 'sd': f = getattr(fblas,p+'nrm2',None) if f is None: continue @@ -91,7 +89,7 @@ f = getattr(fblas,p+'nrm2',None) if f is None: continue assert_almost_equal(f([3j,-4,3-4j]),math.sqrt(50)) - def check_scal(self): + def test_scal(self): for p in 'sd': f = getattr(fblas,p+'scal',None) if f is None: continue @@ -104,7 +102,7 @@ f = getattr(fblas,p+'scal',None) if f is None: continue assert_array_almost_equal(f(3,[3j,-4,3-4j]),[9j,-12,9-12j]) - def check_swap(self): + def test_swap(self): for p in 'sd': f = getattr(fblas,p+'swap',None) if f is None: continue @@ -119,7 +117,7 @@ x1,y1 = f(x,y) assert_array_almost_equal(x1,y) assert_array_almost_equal(y1,x) - def check_amax(self): + def test_amax(self): for p in 'sd': f = getattr(fblas,'i'+p+'amax') assert_equal(f([-2,4,3]),1) @@ -128,9 +126,9 @@ assert_equal(f([-5,4+3j,6]),1) #XXX: need tests for rot,rotm,rotg,rotmg -class TestFBLAS2Simple(NumpyTestCase): +class TestFBLAS2Simple(TestCase): - def check_gemv(self): + def test_gemv(self): for p in 'sd': f = getattr(fblas,p+'gemv',None) if f is None: continue @@ -142,7 +140,7 @@ assert_array_almost_equal(f(3j,[[3-4j]],[-4]),[-48-36j]) assert_array_almost_equal(f(3j,[[3-4j]],[-4],3,[5j]),[-48-21j]) - def check_ger(self): + def test_ger(self): for p in 'sd': f = getattr(fblas,p+'ger',None) @@ -176,9 +174,9 @@ 2j, 3j],[3j,4j]),[[6,8],[12,16],[18,24]]) -class TestFBLAS3Simple(NumpyTestCase): +class TestFBLAS3Simple(TestCase): - def check_gemm(self): + def test_gemm(self): for p in 'sd': f = getattr(fblas,p+'gemm',None) if f is None: continue @@ -190,9 +188,9 @@ assert_array_almost_equal(f(3j,[3-4j],[-4]),[[-48-36j]]) assert_array_almost_equal(f(3j,[3-4j],[-4],3,[5j]),[-48-21j]) -class TestBLAS(NumpyTestCase): +class TestBLAS(TestCase): - def check_fblas(self): + def test_fblas(self): if hasattr(fblas,'empty_module'): print """ **************************************************************** @@ -201,7 +199,7 @@ See scipy/INSTALL.txt for troubleshooting. **************************************************************** """ - def check_cblas(self): + def test_cblas(self): if hasattr(cblas,'empty_module'): print """ **************************************************************** @@ -215,4 +213,4 @@ """ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/linalg/tests/test_decomp.py =================================================================== --- trunk/scipy/linalg/tests/test_decomp.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/tests/test_decomp.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -9,37 +9,41 @@ Build linalg: python setup_linalg.py build Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' + python -c 'import scipy;scipy.linalg.test()' Run tests if linalg is not installed: - python tests/test_decomp.py [] + python tests/test_decomp.py """ import sys -from numpy.testing import * +from scipy.testing import * -set_package_path() -from linalg import eig,eigvals,lu,svd,svdvals,cholesky,qr,schur,rsf2csf -from linalg import lu_solve,lu_factor,solve,diagsvd,hessenberg,rq -from linalg import eig_banded,eigvals_banded -from linalg.flapack import dgbtrf, dgbtrs, zgbtrf, zgbtrs -from linalg.flapack import dsbev, dsbevd, dsbevx, zhbevd, zhbevx -restore_path() -from numpy import * +from scipy.linalg import eig,eigvals,lu,svd,svdvals,cholesky,qr, \ + schur,rsf2csf, lu_solve,lu_factor,solve,diagsvd,hessenberg,rq, \ + eig_banded, eigvals_banded +from scipy.linalg.flapack import dgbtrf, dgbtrs, zgbtrf, zgbtrs, \ + dsbev, dsbevd, dsbevx, zhbevd, zhbevx + +from numpy import array, transpose, sometrue, diag, ones, linalg, \ + argsort, zeros, arange, float32, complex64, dot, conj, identity, \ + ravel, sqrt, iscomplex, shape, sort, sign, conjugate, sign, bmat, \ + asarray, matrix, isfinite + + from numpy.random import rand def random(size): return rand(*size) -class TestEigVals(NumpyTestCase): +class TestEigVals(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2,3],[1,2,3],[2,5,6]] w = eigvals(a) exact_w = [(9+sqrt(93))/2,0,(9-sqrt(93))/2] assert_array_almost_equal(w,exact_w) - def check_simple_tr(self): + def test_simple_tr(self): a = array([[1,2,3],[1,2,3],[2,5,6]],'d') a = transpose(a).copy() a = transpose(a) @@ -47,7 +51,7 @@ exact_w = [(9+sqrt(93))/2,0,(9-sqrt(93))/2] assert_array_almost_equal(w,exact_w) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2,3],[1,2,3],[2,5,6+1j]] w = eigvals(a) exact_w = [(9+1j+sqrt(92+6j))/2, @@ -55,7 +59,8 @@ (9+1j-sqrt(92+6j))/2] assert_array_almost_equal(w,exact_w) - def bench_random(self,level=5): + @dec.bench + def test_bench_random(self): import numpy.linalg as linalg Numeric_eigvals = linalg.eigvals print @@ -72,14 +77,14 @@ a = random([size,size]) - print '| %6.2f ' % self.measure('eigvals(a)',repeat), + print '| %6.2f ' % measure('eigvals(a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) -class TestEig(NumpyTestCase): +class TestEig(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2,3],[1,2,3],[2,5,6]] w,v = eig(a) exact_w = [(9+sqrt(93))/2,0,(9-sqrt(93))/2] @@ -99,7 +104,7 @@ for i in range(3): assert_array_almost_equal(dot(transpose(a),v[:,i]),w[i]*v[:,i]) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2,3],[1,2,3],[2,5,6+1j]] w,vl,vr = eig(a,left=1,right=1) for i in range(3): @@ -151,10 +156,10 @@ if all(isfinite(res[:, i])): assert_array_almost_equal(res[:, i], 0) -class TestEigBanded(NumpyTestCase): +class TestEigBanded(TestCase): def __init__(self, *args): - NumpyTestCase.__init__(self, *args) + TestCase.__init__(self, *args) self.create_bandmat() @@ -238,7 +243,7 @@ ##################################################################### - def check_dsbev(self): + def test_dsbev(self): """Compare dsbev eigenvalues and eigenvectors with the result of linalg.eig.""" w, evec, info = dsbev(self.bandmat_sym, compute_v=1) @@ -248,7 +253,7 @@ - def check_dsbevd(self): + def test_dsbevd(self): """Compare dsbevd eigenvalues and eigenvectors with the result of linalg.eig.""" w, evec, info = dsbevd(self.bandmat_sym, compute_v=1) @@ -258,7 +263,7 @@ - def check_dsbevx(self): + def test_dsbevx(self): """Compare dsbevx eigenvalues and eigenvectors with the result of linalg.eig.""" N,N = shape(self.sym_mat) @@ -270,7 +275,7 @@ assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin)) - def check_zhbevd(self): + def test_zhbevd(self): """Compare zhbevd eigenvalues and eigenvectors with the result of linalg.eig.""" w, evec, info = zhbevd(self.bandmat_herm, compute_v=1) @@ -280,7 +285,7 @@ - def check_zhbevx(self): + def test_zhbevx(self): """Compare zhbevx eigenvalues and eigenvectors with the result of linalg.eig.""" N,N = shape(self.herm_mat) @@ -293,7 +298,7 @@ - def check_eigvals_banded(self): + def test_eigvals_banded(self): """Compare eigenvalues of eigvals_banded with those of linalg.eig.""" w_sym = eigvals_banded(self.bandmat_sym) w_sym = w_sym.real @@ -332,7 +337,7 @@ - def check_eig_banded(self): + def test_eig_banded(self): """Compare eigenvalues and eigenvectors of eig_banded with those of linalg.eig. """ w_sym, evec_sym = eig_banded(self.bandmat_sym) @@ -382,7 +387,7 @@ abs(self.evec_herm_lin[:,ind1:ind2+1]) ) - def check_dgbtrf(self): + def test_dgbtrf(self): """Compare dgbtrf LU factorisation with the LU factorisation result of linalg.lu.""" M,N = shape(self.real_mat) @@ -397,7 +402,7 @@ assert_array_almost_equal(u, u_lin) - def check_zgbtrf(self): + def test_zgbtrf(self): """Compare zgbtrf LU factorisation with the LU factorisation result of linalg.lu.""" M,N = shape(self.comp_mat) @@ -413,7 +418,7 @@ - def check_dgbtrs(self): + def test_dgbtrs(self): """Compare dgbtrs solutions for linear equation system A*x = b with solutions of linalg.solve.""" @@ -423,7 +428,7 @@ y_lin = linalg.solve(self.real_mat, self.b) assert_array_almost_equal(y, y_lin) - def check_zgbtrs(self): + def test_zgbtrs(self): """Compare zgbtrs solutions for linear equation system A*x = b with solutions of linalg.solve.""" @@ -436,10 +441,10 @@ -class TestLU(NumpyTestCase): +class TestLU(TestCase): def __init__(self, *args, **kw): - NumpyTestCase.__init__(self, *args, **kw) + TestCase.__init__(self, *args, **kw) self.a = array([[1,2,3],[1,2,3],[2,5,6]]) self.ca = array([[1,2,3],[1,2,3],[2,5j,6]]) @@ -466,37 +471,37 @@ assert_array_almost_equal(dot(pl,u),data) # Simple tests - def check_simple(self): + def test_simple(self): self._test_common(self.a) - def check_simple_complex(self): + def test_simple_complex(self): self._test_common(self.ca) - def check_simple2(self): + def test_simple2(self): self._test_common(self.b) - def check_simple2_complex(self): + def test_simple2_complex(self): self._test_common(self.cb) # rectangular matrices tests - def check_hrectangular(self): + def test_hrectangular(self): self._test_common(self.hrect) - def check_vrectangular(self): + def test_vrectangular(self): self._test_common(self.vrect) - def check_hrectangular_complex(self): + def test_hrectangular_complex(self): self._test_common(self.chrect) - def check_vrectangular_complex(self): + def test_vrectangular_complex(self): self._test_common(self.cvrect) # Bigger matrices - def check_medium1(self, level = 2): + def test_medium1(self): """Check lu decomposition on medium size, rectangular matrix.""" self._test_common(self.med) - def check_medium1_complex(self, level = 2): + def test_medium1_complex(self): """Check lu decomposition on medium size, rectangular matrix.""" self._test_common(self.cmed) @@ -519,8 +524,8 @@ self.med = self.vrect.astype(float32) self.cmed = self.vrect.astype(complex64) -class TestLUSolve(NumpyTestCase): - def check_lu(self): +class TestLUSolve(TestCase): + def test_lu(self): a = random((10,10)) b = random((10,)) @@ -531,9 +536,9 @@ assert_array_equal(x1,x2) -class TestSVD(NumpyTestCase): +class TestSVD(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2,3],[1,20,3],[2,5,6]] u,s,vh = svd(a) assert_array_almost_equal(dot(transpose(u),u),identity(3)) @@ -542,7 +547,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_simple_singular(self): + def test_simple_singular(self): a = [[1,2,3],[1,2,3],[2,5,6]] u,s,vh = svd(a) assert_array_almost_equal(dot(transpose(u),u),identity(3)) @@ -551,7 +556,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_simple_underdet(self): + def test_simple_underdet(self): a = [[1,2,3],[4,5,6]] u,s,vh = svd(a) assert_array_almost_equal(dot(transpose(u),u),identity(2)) @@ -560,7 +565,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_simple_overdet(self): + def test_simple_overdet(self): a = [[1,2],[4,5],[3,4]] u,s,vh = svd(a) assert_array_almost_equal(dot(transpose(u),u),identity(3)) @@ -569,7 +574,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_random(self): + def test_random(self): n = 20 m = 15 for i in range(3): @@ -581,7 +586,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2,3],[1,2j,3],[2,5,6]] u,s,vh = svd(a) assert_array_almost_equal(dot(conj(transpose(u)),u),identity(3)) @@ -590,7 +595,7 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) - def check_random_complex(self): + def test_random_complex(self): n = 20 m = 15 for i in range(3): @@ -604,52 +609,52 @@ for i in range(len(s)): sigma[i,i] = s[i] assert_array_almost_equal(dot(dot(u,sigma),vh),a) -class TestSVDVals(NumpyTestCase): +class TestSVDVals(TestCase): - def check_simple(self): + def test_simple(self): a = [[1,2,3],[1,2,3],[2,5,6]] s = svdvals(a) assert len(s)==3 assert s[0]>=s[1]>=s[2] - def check_simple_underdet(self): + def test_simple_underdet(self): a = [[1,2,3],[4,5,6]] s = svdvals(a) assert len(s)==2 assert s[0]>=s[1] - def check_simple_overdet(self): + def test_simple_overdet(self): a = [[1,2],[4,5],[3,4]] s = svdvals(a) assert len(s)==2 assert s[0]>=s[1] - def check_simple_complex(self): + def test_simple_complex(self): a = [[1,2,3],[1,20,3j],[2,5,6]] s = svdvals(a) assert len(s)==3 assert s[0]>=s[1]>=s[2] - def check_simple_underdet_complex(self): + def test_simple_underdet_complex(self): a = [[1,2,3],[4,5j,6]] s = svdvals(a) assert len(s)==2 assert s[0]>=s[1] - def check_simple_overdet_complex(self): + def test_simple_overdet_complex(self): a = [[1,2],[4,5],[3j,4]] s = svdvals(a) assert len(s)==2 assert s[0]>=s[1] -class TestDiagSVD(NumpyTestCase): +class TestDiagSVD(TestCase): - def check_simple(self): + def test_simple(self): assert_array_almost_equal(diagsvd([1,0,0],3,3),[[1,0,0],[0,0,0],[0,0,0]]) -class TestCholesky(NumpyTestCase): +class TestCholesky(TestCase): - def check_simple(self): + def test_simple(self): a = [[8,2,3],[2,9,3],[3,3,6]] c = cholesky(a) assert_array_almost_equal(dot(transpose(c),c),a) @@ -657,7 +662,7 @@ a = dot(c,transpose(c)) assert_array_almost_equal(cholesky(a,lower=1),c) - def check_simple_complex(self): + def test_simple_complex(self): m = array([[3+1j,3+4j,5],[0,2+2j,2+7j],[0,0,7+4j]]) a = dot(transpose(conjugate(m)),m) c = cholesky(a) @@ -667,7 +672,7 @@ a = dot(c,transpose(conjugate(c))) assert_array_almost_equal(cholesky(a,lower=1),c) - def check_random(self): + def test_random(self): n = 20 for k in range(2): m = random([n,n]) @@ -681,7 +686,7 @@ a = dot(c,transpose(c)) assert_array_almost_equal(cholesky(a,lower=1),c) - def check_random_complex(self): + def test_random_complex(self): n = 20 for k in range(2): m = random([n,n])+1j*random([n,n]) @@ -696,28 +701,28 @@ assert_array_almost_equal(cholesky(a,lower=1),c) -class TestQR(NumpyTestCase): +class TestQR(TestCase): - def check_simple(self): + def test_simple(self): a = [[8,2,3],[2,9,3],[5,3,6]] q,r = qr(a) assert_array_almost_equal(dot(transpose(q),q),identity(3)) assert_array_almost_equal(dot(q,r),a) - def check_simple_trap(self): + def test_simple_trap(self): a = [[8,2,3],[2,9,3]] q,r = qr(a) assert_array_almost_equal(dot(transpose(q),q),identity(2)) assert_array_almost_equal(dot(q,r),a) - def check_simple_tall(self): + def test_simple_tall(self): # full version a = [[8,2],[2,9],[5,3]] q,r = qr(a) assert_array_almost_equal(dot(transpose(q),q),identity(3)) assert_array_almost_equal(dot(q,r),a) - def check_simple_tall_e(self): + def test_simple_tall_e(self): # economy version a = [[8,2],[2,9],[5,3]] q,r = qr(a,econ=True) @@ -726,13 +731,13 @@ assert_equal(q.shape, (3,2)) assert_equal(r.shape, (2,2)) - def check_simple_complex(self): + def test_simple_complex(self): a = [[3,3+4j,5],[5,2,2+7j],[3,2,7]] q,r = qr(a) assert_array_almost_equal(dot(conj(transpose(q)),q),identity(3)) assert_array_almost_equal(dot(q,r),a) - def check_random(self): + def test_random(self): n = 20 for k in range(2): a = random([n,n]) @@ -740,7 +745,7 @@ assert_array_almost_equal(dot(transpose(q),q),identity(n)) assert_array_almost_equal(dot(q,r),a) - def check_random_tall(self): + def test_random_tall(self): # full version m = 200 n = 100 @@ -750,7 +755,7 @@ assert_array_almost_equal(dot(transpose(q),q),identity(m)) assert_array_almost_equal(dot(q,r),a) - def check_random_tall_e(self): + def test_random_tall_e(self): # economy version m = 200 n = 100 @@ -762,7 +767,7 @@ assert_equal(q.shape, (m,n)) assert_equal(r.shape, (n,n)) - def check_random_trap(self): + def test_random_trap(self): m = 100 n = 200 for k in range(2): @@ -771,7 +776,7 @@ assert_array_almost_equal(dot(transpose(q),q),identity(m)) assert_array_almost_equal(dot(q,r),a) - def check_random_complex(self): + def test_random_complex(self): n = 20 for k in range(2): a = random([n,n])+1j*random([n,n]) @@ -779,15 +784,15 @@ assert_array_almost_equal(dot(conj(transpose(q)),q),identity(n)) assert_array_almost_equal(dot(q,r),a) -class TestRQ(NumpyTestCase): +class TestRQ(TestCase): - def check_simple(self): + def test_simple(self): a = [[8,2,3],[2,9,3],[5,3,6]] r,q = rq(a) assert_array_almost_equal(dot(transpose(q),q),identity(3)) assert_array_almost_equal(dot(r,q),a) - def check_random(self): + def test_random(self): n = 20 for k in range(2): a = random([n,n]) @@ -797,25 +802,25 @@ # TODO: implement support for non-square and complex arrays -## def check_simple_trap(self): +## def test_simple_trap(self): ## a = [[8,2,3],[2,9,3]] ## r,q = rq(a) ## assert_array_almost_equal(dot(transpose(q),q),identity(2)) ## assert_array_almost_equal(dot(r,q),a) -## def check_simple_tall(self): +## def test_simple_tall(self): ## a = [[8,2],[2,9],[5,3]] ## r,q = rq(a) ## assert_array_almost_equal(dot(transpose(q),q),identity(3)) ## assert_array_almost_equal(dot(r,q),a) -## def check_simple_complex(self): +## def test_simple_complex(self): ## a = [[3,3+4j,5],[5,2,2+7j],[3,2,7]] ## r,q = rq(a) ## assert_array_almost_equal(dot(conj(transpose(q)),q),identity(3)) ## assert_array_almost_equal(dot(r,q),a) -## def check_random_tall(self): +## def test_random_tall(self): ## m = 200 ## n = 100 ## for k in range(2): @@ -824,7 +829,7 @@ ## assert_array_almost_equal(dot(transpose(q),q),identity(m)) ## assert_array_almost_equal(dot(r,q),a) -## def check_random_trap(self): +## def test_random_trap(self): ## m = 100 ## n = 200 ## for k in range(2): @@ -833,7 +838,7 @@ ## assert_array_almost_equal(dot(transpose(q),q),identity(m)) ## assert_array_almost_equal(dot(r,q),a) -## def check_random_complex(self): +## def test_random_complex(self): ## n = 20 ## for k in range(2): ## a = random([n,n])+1j*random([n,n]) @@ -844,9 +849,9 @@ transp = transpose any = sometrue -class TestSchur(NumpyTestCase): +class TestSchur(TestCase): - def check_simple(self): + def test_simple(self): a = [[8,12,3],[2,9,3],[10,3,6]] t,z = schur(a) assert_array_almost_equal(dot(dot(z,t),transp(conj(z))),a) @@ -856,9 +861,9 @@ tc2,zc2 = rsf2csf(tc,zc) assert_array_almost_equal(dot(dot(zc2,tc2),transp(conj(zc2))),a) -class TestHessenberg(NumpyTestCase): +class TestHessenberg(TestCase): - def check_simple(self): + def test_simple(self): a = [[-149, -50,-154], [ 537, 180, 546], [ -27, -9, -25]] @@ -869,7 +874,7 @@ assert_array_almost_equal(dot(transp(q),dot(a,q)),h) assert_array_almost_equal(h,h1,decimal=4) - def check_simple_complex(self): + def test_simple_complex(self): a = [[-149, -50,-154], [ 537, 180j, 546], [ -27j, -9, -25]] @@ -877,7 +882,7 @@ h1 = dot(transp(conj(q)),dot(a,q)) assert_array_almost_equal(h1,h) - def check_simple2(self): + def test_simple2(self): a = [[1,2,3,4,5,6,7], [0,2,3,4,6,7,2], [0,2,2,3,0,3,2], @@ -888,14 +893,14 @@ h,q = hessenberg(a,calc_q=1) assert_array_almost_equal(dot(transp(q),dot(a,q)),h) - def check_random(self): + def test_random(self): n = 20 for k in range(2): a = random([n,n]) h,q = hessenberg(a,calc_q=1) assert_array_almost_equal(dot(transp(q),dot(a,q)),h) - def check_random_complex(self): + def test_random_complex(self): n = 20 for k in range(2): a = random([n,n])+1j*random([n,n]) @@ -905,9 +910,9 @@ -class TestDataNotShared(NumpyTestCase): +class TestDataNotShared(TestCase): - def check_datanotshared(self): + def test_datanotshared(self): from scipy.linalg.decomp import _datanotshared M = matrix([[0,1],[2,3]]) @@ -924,4 +929,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/linalg/tests/test_fblas.py =================================================================== --- trunk/scipy/linalg/tests/test_fblas.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/tests/test_fblas.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -6,14 +6,16 @@ # !! Complex calculations really aren't checked that carefully. # !! Only real valued complex numbers are used in tests. -from numpy import * - import sys -from numpy.testing import * -set_package_path() -from linalg import fblas -restore_path() +from numpy import dot, float32, float64, complex64, complex128, \ + arange, array, zeros, shape, transpose, newaxis, \ + common_type, conjugate +from scipy.linalg import fblas + +from scipy.testing import * + + #decimal accuracy to require between Python and LAPACK/BLAS calculations accuracy = 5 @@ -40,39 +42,40 @@ ################################################## ### Test blas ?axpy -class BaseAxpy(NumpyTestCase): - def check_default_a(self): +class BaseAxpy(object): + ''' Mixin class for axpy tests ''' + def test_default_a(self): x = arange(3.,dtype=self.dtype) y = arange(3.,dtype=x.dtype) real_y = x*1.+y self.blas_func(x,y) assert_array_equal(real_y,y) - def check_simple(self): + def test_simple(self): x = arange(3.,dtype=self.dtype) y = arange(3.,dtype=x.dtype) real_y = x*3.+y self.blas_func(x,y,a=3.) assert_array_equal(real_y,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) y = arange(3.,dtype=x.dtype) real_y = x[::2]*3.+y self.blas_func(x,y,a=3.,n=3,incx=2) assert_array_equal(real_y,y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) real_y = x*3.+y[::2] self.blas_func(x,y,a=3.,n=3,incy=2) assert_array_equal(real_y,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) real_y = x[::4]*3.+y[::2] self.blas_func(x,y,a=3.,n=3,incx=4,incy=2) assert_array_equal(real_y,y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -81,7 +84,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -92,21 +95,21 @@ assert(0) try: - class TestSaxpy(BaseAxpy): + class TestSaxpy(TestCase, BaseAxpy): blas_func = fblas.saxpy dtype = float32 except AttributeError: class TestSaxpy: pass -class TestDaxpy(BaseAxpy): +class TestDaxpy(TestCase, BaseAxpy): blas_func = fblas.daxpy dtype = float64 try: - class TestCaxpy(BaseAxpy): + class TestCaxpy(TestCase, BaseAxpy): blas_func = fblas.caxpy dtype = complex64 except AttributeError: class TestCaxpy: pass -class TestZaxpy(BaseAxpy): +class TestZaxpy(TestCase, BaseAxpy): blas_func = fblas.zaxpy dtype = complex128 @@ -114,19 +117,20 @@ ################################################## ### Test blas ?scal -class BaseScal(NumpyTestCase): - def check_simple(self): +class BaseScal(object): + ''' Mixin class for scal testing ''' + def test_simple(self): x = arange(3.,dtype=self.dtype) real_x = x*3. self.blas_func(3.,x) assert_array_equal(real_x,x) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) real_x = x.copy() real_x[::2] = x[::2]*array(3.,self.dtype) self.blas_func(3.,x,n=3,incx=2) assert_array_equal(real_x,x) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) try: self.blas_func(2.,x,n=4,incx=5) @@ -135,21 +139,21 @@ # should catch error and never get here assert(0) try: - class TestSscal(BaseScal): + class TestSscal(TestCase, BaseScal): blas_func = fblas.sscal dtype = float32 except AttributeError: class TestSscal: pass -class TestDscal(BaseScal): +class TestDscal(TestCase, BaseScal): blas_func = fblas.dscal dtype = float64 try: - class TestCscal(BaseScal): + class TestCscal(TestCase, BaseScal): blas_func = fblas.cscal dtype = complex64 except AttributeError: class TestCscal: pass -class TestZscal(BaseScal): +class TestZscal(TestCase, BaseScal): blas_func = fblas.zscal dtype = complex128 @@ -159,28 +163,29 @@ ################################################## ### Test blas ?copy -class BaseCopy(NumpyTestCase): - def check_simple(self): +class BaseCopy(object): + ''' Mixin class for copy testing ''' + def test_simple(self): x = arange(3.,dtype=self.dtype) y = zeros(shape(x),x.dtype) self.blas_func(x,y) assert_array_equal(x,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) self.blas_func(x,y,n=3,incx=2) assert_array_equal(x[::2],y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) self.blas_func(x,y,n=3,incy=2) assert_array_equal(x,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) self.blas_func(x,y,n=3,incx=4,incy=2) assert_array_equal(x[::4],y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -189,7 +194,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -198,7 +203,7 @@ return # should catch error and never get here assert(0) - #def check_y_bad_type(self): + #def test_y_bad_type(self): ## Hmmm. Should this work? What should be the output. # x = arange(3.,dtype=self.dtype) # y = zeros(shape(x)) @@ -206,21 +211,21 @@ # assert_array_equal(x,y) try: - class TestScopy(BaseCopy): + class TestScopy(TestCase, BaseCopy): blas_func = fblas.scopy dtype = float32 except AttributeError: class TestScopy: pass -class TestDcopy(BaseCopy): +class TestDcopy(TestCase, BaseCopy): blas_func = fblas.dcopy dtype = float64 try: - class TestCcopy(BaseCopy): + class TestCcopy(TestCase, BaseCopy): blas_func = fblas.ccopy dtype = complex64 except AttributeError: class TestCcopy: pass -class TestZcopy(BaseCopy): +class TestZcopy(TestCase, BaseCopy): blas_func = fblas.zcopy dtype = complex128 @@ -228,8 +233,9 @@ ################################################## ### Test blas ?swap -class BaseSwap(NumpyTestCase): - def check_simple(self): +class BaseSwap(object): + ''' Mixin class for swap tests ''' + def test_simple(self): x = arange(3.,dtype=self.dtype) y = zeros(shape(x),x.dtype) desired_x = y.copy() @@ -237,7 +243,7 @@ self.blas_func(x,y) assert_array_equal(desired_x,x) assert_array_equal(desired_y,y) - def check_x_stride(self): + def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) desired_x = y.copy() @@ -245,7 +251,7 @@ self.blas_func(x,y,n=3,incx=2) assert_array_equal(desired_x,x[::2]) assert_array_equal(desired_y,y) - def check_y_stride(self): + def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) desired_x = y.copy()[::2] @@ -254,7 +260,7 @@ assert_array_equal(desired_x,x) assert_array_equal(desired_y,y[::2]) - def check_x_and_y_stride(self): + def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) desired_x = y.copy()[::2] @@ -262,7 +268,7 @@ self.blas_func(x,y,n=3,incx=4,incy=2) assert_array_equal(desired_x,x[::4]) assert_array_equal(desired_y,y[::2]) - def check_x_bad_size(self): + def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: @@ -271,7 +277,7 @@ return # should catch error and never get here assert(0) - def check_y_bad_size(self): + def test_y_bad_size(self): x = arange(12.,dtype=complex64) y = zeros(6,x.dtype) try: @@ -282,21 +288,21 @@ assert(0) try: - class TestSswap(BaseSwap): + class TestSswap(TestCase, BaseSwap): blas_func = fblas.sswap dtype = float32 except AttributeError: class TestSswap: pass -class TestDswap(BaseSwap): +class TestDswap(TestCase, BaseSwap): blas_func = fblas.dswap dtype = float64 try: - class TestCswap(BaseSwap): + class TestCswap(TestCase, BaseSwap): blas_func = fblas.cswap dtype = complex64 except AttributeError: class TestCswap: pass -class TestZswap(BaseSwap): +class TestZswap(TestCase, BaseSwap): blas_func = fblas.zswap dtype = complex128 @@ -304,7 +310,8 @@ ### Test blas ?gemv ### This will be a mess to test all cases. -class BaseGemv(NumpyTestCase): +class BaseGemv(object): + ''' Mixin class for gemv tests ''' def get_data(self,x_stride=1,y_stride=1): mult = array(1, dtype = self.dtype) if self.dtype in [complex64, complex128]: @@ -316,37 +323,37 @@ x = arange(shape(a)[0]*x_stride,dtype=self.dtype) * mult y = arange(shape(a)[1]*y_stride,dtype=self.dtype) * mult return alpha,beta,a,x,y - def check_simple(self): + def test_simple(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(a,x)+beta*y y = self.blas_func(alpha,a,x,beta,y) assert_array_almost_equal(desired_y,y) - def check_default_beta_y(self): + def test_default_beta_y(self): alpha,beta,a,x,y = self.get_data() desired_y = matrixmultiply(a,x) y = self.blas_func(1,a,x) assert_array_almost_equal(desired_y,y) - def check_simple_transpose(self): + def test_simple_transpose(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(transpose(a),x)+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=1) assert_array_almost_equal(desired_y,y) - def check_simple_transpose_conj(self): + def test_simple_transpose_conj(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(transpose(conjugate(a)),x)+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=2) assert_array_almost_equal(desired_y,y) - def check_x_stride(self): + def test_x_stride(self): alpha,beta,a,x,y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(a,x[::2])+beta*y y = self.blas_func(alpha,a,x,beta,y,incx=2) assert_array_almost_equal(desired_y,y) - def check_x_stride_transpose(self): + def test_x_stride_transpose(self): alpha,beta,a,x,y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(transpose(a),x[::2])+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=1,incx=2) assert_array_almost_equal(desired_y,y) - def check_x_stride_assert(self): + def test_x_stride_assert(self): # What is the use of this test? alpha,beta,a,x,y = self.get_data(x_stride=2) try: @@ -359,19 +366,19 @@ assert(0) except: pass - def check_y_stride(self): + def test_y_stride(self): alpha,beta,a,x,y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(a,x)+beta*y[::2] y = self.blas_func(alpha,a,x,beta,y,incy=2) assert_array_almost_equal(desired_y,y) - def check_y_stride_transpose(self): + def test_y_stride_transpose(self): alpha,beta,a,x,y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(transpose(a),x)+beta*y[::2] y = self.blas_func(alpha,a,x,beta,y,trans=1,incy=2) assert_array_almost_equal(desired_y,y) - def check_y_stride_assert(self): + def test_y_stride_assert(self): # What is the use of this test? alpha,beta,a,x,y = self.get_data(y_stride=2) try: @@ -386,21 +393,21 @@ pass try: - class TestSgemv(BaseGemv): + class TestSgemv(TestCase, BaseGemv): blas_func = fblas.sgemv dtype = float32 except AttributeError: class TestSgemv: pass -class TestDgemv(BaseGemv): +class TestDgemv(TestCase, BaseGemv): blas_func = fblas.dgemv dtype = float64 try: - class TestCgemv(BaseGemv): + class TestCgemv(TestCase, BaseGemv): blas_func = fblas.cgemv dtype = complex64 except AttributeError: class TestCgemv: pass -class TestZgemv(BaseGemv): +class TestZgemv(TestCase, BaseGemv): blas_func = fblas.zgemv dtype = complex128 @@ -409,7 +416,7 @@ ### Test blas ?ger ### This will be a mess to test all cases. -class BaseGer(NumpyTestCase): +class BaseGer(TestCase): def get_data(self,x_stride=1,y_stride=1): from numpy.random import normal alpha = array(1., dtype = self.dtype) @@ -417,31 +424,31 @@ x = arange(shape(a)[0]*x_stride,dtype=self.dtype) y = arange(shape(a)[1]*y_stride,dtype=self.dtype) return alpha,a,x,y - def check_simple(self): + def test_simple(self): alpha,a,x,y = self.get_data() # tranpose takes care of Fortran vs. C(and Python) memory layout desired_a = alpha*transpose(x[:,newaxis]*y) + a self.blas_func(x,y,a) assert_array_almost_equal(desired_a,a) - def check_x_stride(self): + def test_x_stride(self): alpha,a,x,y = self.get_data(x_stride=2) desired_a = alpha*transpose(x[::2,newaxis]*y) + a self.blas_func(x,y,a,incx=2) assert_array_almost_equal(desired_a,a) - def check_x_stride_assert(self): + def test_x_stride_assert(self): alpha,a,x,y = self.get_data(x_stride=2) try: self.blas_func(x,y,a,incx=3) assert(0) except: pass - def check_y_stride(self): + def test_y_stride(self): alpha,a,x,y = self.get_data(y_stride=2) desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a self.blas_func(x,y,a,incy=2) assert_array_almost_equal(desired_a,a) - def check_y_stride_assert(self): + def test_y_stride_assert(self): alpha,a,x,y = self.get_data(y_stride=2) try: self.blas_func(a,x,y,incy=3) @@ -472,7 +479,7 @@ y = normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype) y = y + y * array(1j, dtype = self.dtype) return alpha,a,x,y - def check_simple(self): + def test_simple(self): alpha,a,x,y = self.get_data() # tranpose takes care of Fortran vs. C(and Python) memory layout a = a * array(0.,dtype = self.dtype) @@ -482,12 +489,12 @@ fblas.cgeru(x,y,a,alpha = alpha) assert_array_almost_equal(desired_a,a) - #def check_x_stride(self): + #def test_x_stride(self): # alpha,a,x,y = self.get_data(x_stride=2) # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a # self.blas_func(x,y,a,incx=2) # assert_array_almost_equal(desired_a,a) - #def check_y_stride(self): + #def test_y_stride(self): # alpha,a,x,y = self.get_data(y_stride=2) # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a # self.blas_func(x,y,a,incy=2) @@ -518,4 +525,4 @@ """ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/linalg/tests/test_iterative.py =================================================================== --- trunk/scipy/linalg/tests/test_iterative.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/tests/test_iterative.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -13,15 +13,14 @@ python tests/test_iterative.py [] """ +import sys + from numpy import zeros, dot, diag, ones -from numpy.testing import * +from scipy.testing import * from numpy.random import rand #from numpy import arange, add, array, dot, zeros, identity, conjugate, transpose -import sys -set_package_path() -from linalg import iterative, norm, cg, cgs, bicg, bicgstab, gmres, qmr -restore_path() +from scipy.linalg import iterative, norm, cg, cgs, bicg, bicgstab, gmres, qmr def callback(x): @@ -29,9 +28,9 @@ res = b-dot(A,x) #print "||A.x - b|| = " + str(norm(dot(A,x)-b)) -class TestIterativeSolvers(NumpyTestCase): +class TestIterativeSolvers(TestCase): def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.setUp() def setUp (self): global A, b @@ -44,41 +43,41 @@ self.b = rand(n) b = self.b - def check_cg(self): + def test_cg(self): bx0 = self.x0.copy() x, info = cg(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_bicg(self): + def test_bicg(self): bx0 = self.x0.copy() x, info = bicg(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_cgs(self): + def test_cgs(self): bx0 = self.x0.copy() x, info = cgs(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_bicgstab(self): + def test_bicgstab(self): bx0 = self.x0.copy() x, info = bicgstab(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_gmres(self): + def test_gmres(self): bx0 = self.x0.copy() x, info = gmres(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol - def check_qmr(self): + def test_qmr(self): bx0 = self.x0.copy() x, info = qmr(self.A, self.b, self.x0, callback=callback) assert_array_equal(bx0, self.x0) assert norm(dot(self.A, x) - self.b) < 5*self.tol if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/linalg/tests/test_lapack.py =================================================================== --- trunk/scipy/linalg/tests/test_lapack.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/tests/test_lapack.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,26 +3,17 @@ # Created by: Pearu Peterson, September 2002 # -__usage__ = """ -Build linalg: - python setup_linalg.py build -Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' -Run tests if linalg is not installed: - python tests/test_lapack.py [] -""" import sys -from numpy.testing import * +from scipy.testing import * from numpy import ones -set_package_path() -from linalg import flapack -from linalg import clapack -restore_path() -class TestFlapackSimple(NumpyTestCase): +from scipy.linalg import flapack, clapack - def check_gebal(self): + +class TestFlapackSimple(TestCase): + + def test_gebal(self): a = [[1,2,3],[4,5,6],[7,8,9]] a1 = [[1,0,0,3e-4], [4,0,0,2e-3], @@ -42,7 +33,7 @@ #print a1 #print ba,lo,hi,pivscale - def check_gehrd(self): + def test_gehrd(self): a = [[-149, -50,-154], [ 537, 180, 546], [ -27, -9, -25]] @@ -52,9 +43,9 @@ ht,tau,info = f(a) assert not info,`info` -class TestLapack(NumpyTestCase): +class TestLapack(TestCase): - def check_flapack(self): + def test_flapack(self): if hasattr(flapack,'empty_module'): print """ **************************************************************** @@ -63,7 +54,7 @@ See scipy/INSTALL.txt for troubleshooting. **************************************************************** """ - def check_clapack(self): + def test_clapack(self): if hasattr(clapack,'empty_module'): print """ **************************************************************** @@ -77,4 +68,4 @@ """ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/linalg/tests/test_matfuncs.py =================================================================== --- trunk/scipy/linalg/tests/test_matfuncs.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linalg/tests/test_matfuncs.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -5,29 +5,21 @@ """ Test functions for linalg.matfuncs module """ -__usage__ = """ -Build linalg: - python setup_linalg.py build -Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' -Run tests if linalg is not installed: - python tests/test_matfuncs.py [] -""" -from numpy import array, identity - import sys -from numpy.testing import * -set_package_path() + import numpy -from numpy import dot,sqrt -import linalg -from linalg import signm,logm,funm, sqrtm, expm, expm2, expm3 -restore_path() +from numpy import array, identity, dot, sqrt -class TestSignM(NumpyTestCase): +from scipy.testing import * - def check_nils(self): +import scipy.linalg +from scipy.linalg import signm,logm,funm, sqrtm, expm, expm2, expm3 + + +class TestSignM(TestCase): + + def test_nils(self): a = array([[ 29.2, -24.2, 69.5, 49.8, 7. ], [ -9.2, 5.2, -18. , -16.8, -2. ], [-10. , 6. , -20. , -18. , -2. ], @@ -41,12 +33,12 @@ r = signm(a) assert_array_almost_equal(r,cr) - def check_defective1(self): + def test_defective1(self): a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]]) r = signm(a) #XXX: what would be the correct result? - def check_defective2(self): + def test_defective2(self): a = array(( [29.2,-24.2,69.5,49.8,7.0], [-9.2,5.2,-18.0,-16.8,-2.0], @@ -56,7 +48,7 @@ r = signm(a) #XXX: what would be the correct result? - def check_defective3(self): + def test_defective3(self): a = array([[ -2., 25., 0., 0., 0., 0., 0.], [ 0., -3., 10., 3., 3., 3., 0.], [ 0., 0., 2., 15., 3., 3., 0.], @@ -67,9 +59,9 @@ r = signm(a) #XXX: what would be the correct result? -class TestLogM(NumpyTestCase): +class TestLogM(TestCase): - def check_nils(self): + def test_nils(self): a = array([[ -2., 25., 0., 0., 0., 0., 0.], [ 0., -3., 10., 3., 3., 3., 0.], [ 0., 0., 2., 15., 3., 3., 0.], @@ -81,8 +73,8 @@ logm(m) -class TestSqrtM(NumpyTestCase): - def check_bad(self): +class TestSqrtM(TestCase): + def test_bad(self): # See http://www.maths.man.ac.uk/~nareports/narep336.ps.gz e = 2**-5 se = sqrt(e) @@ -98,12 +90,12 @@ esa = sqrtm(a) assert_array_almost_equal(dot(esa,esa),a) -class TestExpM(NumpyTestCase): - def check_zero(self): +class TestExpM(TestCase): + def test_zero(self): a = array([[0.,0],[0,0]]) assert_array_almost_equal(expm(a),[[1,0],[0,1]]) assert_array_almost_equal(expm2(a),[[1,0],[0,1]]) assert_array_almost_equal(expm3(a),[[1,0],[0,1]]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/linsolve/__init__.py =================================================================== --- trunk/scipy/linsolve/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linsolve/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -9,5 +9,5 @@ from linsolve import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/linsolve/umfpack/__init__.py =================================================================== --- trunk/scipy/linsolve/umfpack/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linsolve/umfpack/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,5 +3,5 @@ from umfpack import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/linsolve/umfpack/tests/test_umfpack.py =================================================================== --- trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -8,20 +8,23 @@ from numpy import transpose, array, arange import random -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy import linsolve, rand, matrix, diag, eye from scipy.sparse import csc_matrix, dok_matrix, spdiags import numpy as nm import scipy.linsolve.umfpack as um -restore_path() +# Allow disabling of nose tests if umfpack not present +have_umfpack = um.umfpack._um is not None -class TestSolvers(NumpyTestCase): +class TestSolvers(TestCase): """Tests inverting a sparse linear system""" - def check_solve_complex_without_umfpack(self): + __test__ = have_umfpack + + def test_solve_complex_without_umfpack(self): """Solve: single precision complex""" linsolve.use_solver( useUmfpack = False ) a = self.a.astype('F') @@ -32,7 +35,7 @@ assert_array_almost_equal(a*x, b) - def check_solve_without_umfpack(self): + def test_solve_without_umfpack(self): """Solve: single precision""" linsolve.use_solver( useUmfpack = False ) a = self.a.astype('f') @@ -43,7 +46,7 @@ assert_array_almost_equal(a*x, b) - def check_solve_complex_umfpack(self): + def test_solve_complex_umfpack(self): """Solve with UMFPACK: double precision complex""" linsolve.use_solver( useUmfpack = True ) a = self.a.astype('D') @@ -53,7 +56,7 @@ #print "Error: ", a*x-b assert_array_almost_equal(a*x, b) - def check_solve_umfpack(self): + def test_solve_umfpack(self): """Solve with UMFPACK: double precision""" linsolve.use_solver( useUmfpack = True ) a = self.a.astype('d') @@ -63,7 +66,7 @@ #print "Error: ", a*x-b assert_array_almost_equal(a*x, b) - def check_solve_sparse_rhs(self): + def test_solve_sparse_rhs(self): """Solve with UMFPACK: double precision, sparse rhs""" linsolve.use_solver( useUmfpack = True ) a = self.a.astype('d') @@ -73,7 +76,7 @@ #print "Error: ", a*x-b assert_array_almost_equal(a*x, self.b) - def check_factorized_umfpack(self): + def test_factorized_umfpack(self): """Prefactorize (with UMFPACK) matrix for solving with multiple rhs""" linsolve.use_solver( useUmfpack = True ) a = self.a.astype('d') @@ -84,7 +87,7 @@ x2 = solve( self.b2 ) assert_array_almost_equal(a*x2, self.b2) - def check_factorized_without_umfpack(self): + def test_factorized_without_umfpack(self): """Prefactorize matrix for solving with multiple rhs""" linsolve.use_solver( useUmfpack = False ) a = self.a.astype('d') @@ -104,10 +107,12 @@ -class TestFactorization(NumpyTestCase): +class TestFactorization(TestCase): """Tests factorizing a sparse linear system""" - def check_complex_lu(self): + __test__ = have_umfpack + + def test_complex_lu(self): """Getting factors of complex matrix""" umfpack = um.UmfpackContext("zi") @@ -126,7 +131,7 @@ assert_array_almost_equal(P*R*A*Q,L*U) - def check_real_lu(self): + def test_real_lu(self): """Getting factors of real matrix""" umfpack = um.UmfpackContext("di") @@ -166,4 +171,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/maxentropy/__init__.py =================================================================== --- trunk/scipy/maxentropy/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/maxentropy/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -8,5 +8,5 @@ from info import __doc__ from maxentropy import * -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/maxentropy/tests/test_maxentropy.py =================================================================== --- trunk/scipy/maxentropy/tests/test_maxentropy.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/maxentropy/tests/test_maxentropy.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -7,20 +7,15 @@ """ import sys -from numpy.testing import * +from scipy.testing import * from numpy import arange, add, array, dot, zeros, identity, log, exp, ones -set_package_path() from scipy.maxentropy.maxentropy import * -restore_path() -import unittest - - -class TestMaxentropy(NumpyTestCase): +class TestMaxentropy(TestCase): """Test whether logsumexp() function correctly handles large inputs. """ - def check_logsumexp(self, level=1): + def test_logsumexp(self): a = arange(200) desired = log(sum(exp(a))) assert_almost_equal(logsumexp(a), desired) @@ -35,10 +30,10 @@ desired = 10000.0 + log(n) assert_almost_equal(logsumexp(b), desired) - def check_simple(self, level=1): + def test_simple(self): # Write me! pass if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/misc/__init__.py =================================================================== --- trunk/scipy/misc/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/misc/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -20,5 +20,5 @@ __all__ += common.__all__ -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/misc/ppimport.py =================================================================== --- trunk/scipy/misc/ppimport.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/misc/ppimport.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -242,8 +242,8 @@ self.__dict__['_ppimport_p_frame'] = p_frame if location != 'sys.path': - from numpy.test.testing import NumpyTest - self.__dict__['test'] = NumpyTest(self).test + from scipy.testing.pkgtester import Tester + self.__dict__['test'] = Tester(os,path.dirname(location)).test # install loader sys.modules[name] = self @@ -283,9 +283,8 @@ self.__dict__['_ppimport_module'] = module # XXX: Should we check the existence of module.test? Warn? - from numpy.test.testing import NumpyTest - module.test = NumpyTest(module).test - + from scipy.testing.pkgtester import Tester + test = Tester(os.path.dirname(module).test return module def __setattr__(self, name, value): Modified: trunk/scipy/misc/tests/test_pilutil.py =================================================================== --- trunk/scipy/misc/tests/test_pilutil.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/misc/tests/test_pilutil.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,16 +1,15 @@ -from numpy.testing import * -set_package_path() +import os.path +import glob +import numpy as N + +from scipy.testing import * + import PIL.Image import scipy.misc.pilutil as pilutil -restore_path() -import glob -import os.path -import numpy as N - datapath = os.path.dirname(__file__) -class TestPILUtil(ParametricTestCase): +class TestPILUtil(TestCase): def test_imresize(self): im = N.random.random((10,20)) for T in N.sctypes['float'] + [float]: @@ -23,19 +22,20 @@ assert_equal(pilutil.bytescale(x),x) assert_equal(pilutil.bytescale(y),[0,127,255]) - def tst_fromimage(self,filename,irange): - img = pilutil.fromimage(PIL.Image.open(filename)) - imin,imax = irange - assert img.min() >= imin - assert img.max() <= imax - def testip_fromimage(self): - data = {'icon.png':(0,255), - 'icon_mono.png':(0,2), - 'icon_mono_flat.png':(0,1)} +def tst_fromimage(filename, irange): + img = pilutil.fromimage(PIL.Image.open(filename)) + imin,imax = irange + assert img.min() >= imin + assert img.max() <= imax - return ((self.tst_fromimage,os.path.join(datapath,'data',fn),irange) - for fn,irange in data.iteritems()) +def test_fromimage(): + ''' Test generator for parametric tests ''' + data = {'icon.png':(0,255), + 'icon_mono.png':(0,2), + 'icon_mono_flat.png':(0,1)} + for fn, irange in data.iteritems(): + yield tst_fromimage, os.path.join(datapath,'data',fn), irange if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/ndimage/__init__.py =================================================================== --- trunk/scipy/ndimage/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/ndimage/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -36,6 +36,7 @@ from morphology import * from info import __doc__ -from numpy.testing import NumpyTest -test = NumpyTest().test __version__ = '2.0' + +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/ndimage/segment/tests/test_segment.py =================================================================== --- trunk/scipy/ndimage/segment/tests/test_segment.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/ndimage/segment/tests/test_segment.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,6 +1,6 @@ import numpy as N -from numpy.testing import * +from scipy.testing import * import scipy.ndimage.segment as S inputname = 'slice112.raw' @@ -291,7 +291,7 @@ slice.tofile(filename) -class TestSegment(NumpyTestCase): +class TestSegment(TestCase): def test1(self): image = get_slice(filename) sourceImage = image.copy() @@ -310,4 +310,4 @@ if __name__ == "__main__": - NumpyTest().run() + inittest.main() Modified: trunk/scipy/ndimage/tests/test_ndimage.py =================================================================== --- trunk/scipy/ndimage/tests/test_ndimage.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/ndimage/tests/test_ndimage.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -28,21 +28,12 @@ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -import sys -import unittest import math import numpy from numpy import fft -from numpy.testing import * -set_package_path() -try: - import scipy.ndimage as ndimage -except: - import ndimage +from scipy.testing import * +import scipy.ndimage as ndimage -restore_path() -#import numarray.numinclude as numinclude - eps = 1e-12 def diff(a, b): @@ -66,7 +57,7 @@ return math.sqrt(t) -class TestNdimage(NumpyTestCase): +class TestNdimage(TestCase): def setUp(self): # list of numarray data types @@ -5522,5 +5513,4 @@ # return len(result.failures), result.testsRun if __name__ == "__main__": - #unittest.main() - NumpyTest().run() + unittest.main() Modified: trunk/scipy/odr/__init__.py =================================================================== --- trunk/scipy/odr/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/odr/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -21,6 +21,6 @@ __all__ = ['odr', 'odr_error', 'odr_stop', 'Data', 'RealData', 'Model', 'Output', 'ODR', 'odrpack'] -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test #### EOF ####################################################################### Modified: trunk/scipy/odr/tests/test_odr.py =================================================================== --- trunk/scipy/odr/tests/test_odr.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/odr/tests/test_odr.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,11 +4,11 @@ # Scipy imports. import numpy as np from numpy import pi -from numpy.testing import NumpyTest, NumpyTestCase, assert_array_almost_equal +from scipy.testing import * from scipy.odr import Data, Model, ODR, RealData, odr_stop -class TestODR(NumpyTestCase): +class TestODR(TestCase): # Explicit Example @@ -311,6 +311,5 @@ if __name__ == "__main__": - NumpyTest().run() - + unittest.main() #### EOF ####################################################################### Modified: trunk/scipy/optimize/__init__.py =================================================================== --- trunk/scipy/optimize/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/optimize/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -16,5 +16,5 @@ from slsqp import fmin_slsqp __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/optimize/tests/test_cobyla.py =================================================================== --- trunk/scipy/optimize/tests/test_cobyla.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/optimize/tests/test_cobyla.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,13 +1,11 @@ +import math -from numpy.testing import * +from scipy.testing import * -set_package_path() -from optimize import cobyla as co -restore_path() -import math +from scipy.optimize import cobyla as co -class TestCobyla(NumpyTestCase): - def check_simple(self, level=1): +class TestCobyla(TestCase): + def test_simple(self): function = lambda x: x[0]**2 + abs(x[1])**3 con1 = lambda x: x[0]**2 + x[1]**2 - 25 @@ -20,4 +18,4 @@ assert_almost_equal(x, [x0, x1], decimal=5) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/optimize/tests/test_nonlin.py =================================================================== --- trunk/scipy/optimize/tests/test_nonlin.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/optimize/tests/test_nonlin.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,13 +3,12 @@ May 2007 """ -from numpy.testing import * +from scipy.testing import * -set_package_path() from scipy.optimize import nonlin from numpy import matrix, diag -restore_path() + def F(x): def p3(y): return float(y.T*y)*y @@ -25,7 +24,7 @@ return tuple(f.flat) -class TestNonlin(NumpyTestCase): +class TestNonlin(TestCase): """ Test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) @@ -92,4 +91,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/optimize/tests/test_optimize.py =================================================================== --- trunk/scipy/optimize/tests/test_optimize.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/optimize/tests/test_optimize.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,17 +3,16 @@ Nov 2005 """ -from numpy.testing import * +from scipy.testing import * -set_package_path() from scipy import optimize from numpy import array, zeros, float64, dot, log, exp, inf from scipy.optimize.tnc import RCSTRINGS, MSG_NONE -restore_path() + from math import sin, cos, pow -class TestOptimize(NumpyTestCase): +class TestOptimize(TestCase): """ Test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) @@ -44,7 +43,7 @@ return dot(self.F.transpose(), p) - self.K - def check_cg(self): + def test_cg(self): """ conjugate gradient optimization routine """ retval = optimize.fmin_cg(self.func, self.startparams, self.grad, (), \ @@ -58,7 +57,7 @@ assert err < 1e-6 - def check_bfgs(self): + def test_bfgs(self): """ Broyden-Fletcher-Goldfarb-Shanno optimization routine """ retval = optimize.fmin_bfgs(self.func, self.startparams, self.grad, \ @@ -72,7 +71,7 @@ assert err < 1e-6 - def check_powell(self): + def test_powell(self): """ Powell (direction set) optimization routine """ retval = optimize.fmin_powell(self.func, self.startparams, \ @@ -85,7 +84,7 @@ #print "Powell: Difference is: " + str(err) assert err < 1e-6 - def check_neldermead(self): + def test_neldermead(self): """ Nelder-Mead simplex algorithm """ retval = optimize.fmin(self.func, self.startparams, \ @@ -98,7 +97,7 @@ #print "Nelder-Mead: Difference is: " + str(err) assert err < 1e-6 - def check_ncg(self): + def test_ncg(self): """ line-search Newton conjugate gradient optimization routine """ retval = optimize.fmin_ncg(self.func, self.startparams, self.grad, @@ -113,7 +112,7 @@ assert err < 1e-6 - def check_l_bfgs_b(self): + def test_l_bfgs_b(self): """ limited-memory bound-constrained BFGS algorithm """ retval = optimize.fmin_l_bfgs_b(self.func, self.startparams, @@ -143,7 +142,7 @@ -class TestTnc(NumpyTestCase): +class TestTnc(TestCase): """TNC non-linear optimization. These tests are taken from Prof. K. Schittkowski's test examples @@ -244,4 +243,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/optimize/tests/test_slsqp.py =================================================================== --- trunk/scipy/optimize/tests/test_slsqp.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/optimize/tests/test_slsqp.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,12 +1,11 @@ -from numpy.testing import * +from scipy.testing import * import numpy as np -set_package_path() from scipy.optimize import fmin_slsqp from numpy import matrix, diag -restore_path() -class TestSLSQP(NumpyTestCase): + +class TestSLSQP(TestCase): """Test fmin_slsqp using Example 14.4 from Numerical Methods for Engineers by Steven Chapra and Raymond Canale. This example maximizes the function f(x) = 2*x*y + 2*x - x**2 - 2*y**2, which @@ -87,4 +86,4 @@ assert_array_almost_equal(x,[2,1],decimal=3) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/optimize/tests/test_zeros.py =================================================================== --- trunk/scipy/optimize/tests/test_zeros.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/optimize/tests/test_zeros.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,11 +1,10 @@ #!/usr/bin/env python -from numpy.testing import * -set_package_path() -from optimize import zeros as cc -restore_path() +from scipy.testing import * +from scipy.optimize import zeros as cc + from math import sin,sqrt,log from random import random @@ -51,8 +50,8 @@ functions = [f2,f3,f4,f5,f6] fstrings = ['f2','f3','f4','f5','f6'] -class TestBasic(NumpyTestCase) : - def run_test(self, method, name): +class TestBasic(TestCase) : + def run_check(self, method, name): a = .5 b = sqrt(3) for function, fname in zip(functions, fstrings): @@ -61,16 +60,17 @@ assert_almost_equal(zero, 1.0, decimal=12, err_msg='method %s, function %s' % (name, fname)) - def check_bisect(self): - self.run_test(cc.bisect, 'bisect') - def check_ridder(self): - self.run_test(cc.ridder, 'ridder') - def check_brentq(self): - self.run_test(cc.brentq, 'brentq') - def check_brenth(self): - self.run_test(cc.brenth, 'brenth') + def test_bisect(self): + self.run_check(cc.bisect, 'bisect') + def test_ridder(self): + self.run_check(cc.ridder, 'ridder') + def test_brentq(self): + self.run_check(cc.brentq, 'brentq') + def test_brenth(self): + self.run_check(cc.brenth, 'brenth') - def bench_run(self,level=5): + @dec.bench + def test_run(self): a = .5 b = sqrt(3) repeat = 2000 @@ -85,7 +85,7 @@ for j in range(len(methods)) : meth = methods[j] try: - t = self.measure("meth(func,a,b)",repeat) + t = measure("meth(func,a,b)",repeat) except: print '%s : failed'%mstrings[j] else: @@ -93,4 +93,4 @@ print '\n\n' if __name__ == '__main__' : - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/arpack/tests/test_arpack.py =================================================================== --- trunk/scipy/sandbox/arpack/tests/test_arpack.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/arpack/tests/test_arpack.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -9,17 +9,14 @@ """ -import sys -from numpy.testing import * +from scipy.testing import * -set_package_path() -from arpack import * -del sys.path[0] +from scipy.sandbox.arpack import * import numpy from scipy.linalg import eig,eigh,norm -class TestEigenNonsymmetric(NumpyTestCase): +class TestEigenNonsymmetric(TestCase): def get_a1(self,typ): mat=numpy.array([[-2., -8., 1., 2., -5.], @@ -106,7 +103,7 @@ assert_array_almost_equal(num[:k],exact[:k],decimal=5) - def check_type(self): + def test_type(self): k=2 for typ in 'fd': self.large_magnitude(typ,k) @@ -121,7 +118,7 @@ -class TestEigenComplexNonsymmetric(NumpyTestCase): +class TestEigenComplexNonsymmetric(TestCase): def get_a1(self,typ): mat=numpy.array([[-2., -8., 1., 2., -5.], @@ -205,7 +202,7 @@ assert_array_almost_equal(num,exact[:k],decimal=5) - def check_type(self): + def test_type(self): k=2 for typ in 'FD': self.large_magnitude(typ,k) @@ -218,7 +215,7 @@ -class TestEigenSymmetric(NumpyTestCase): +class TestEigenSymmetric(TestCase): def get_a1(self,typ): mat_a1=numpy.array([[ 2., 0., 0., -1., 0., -1.], @@ -275,14 +272,14 @@ for i in range(k): assert_array_almost_equal(sb.dot(a,v[:,i]),w[i]*v[:,i]) - def check_eigenvectors(self): + def test_eigenvectors(self): k=2 for typ in 'fd': self.large_eigenvectors(typ,k) self.small_eigenvectors(typ,k) self.end_eigenvectors(typ,k) - def check_type(self): + def test_type(self): k=2 for typ in 'fd': self.large_eigenvalues(typ,k) @@ -290,7 +287,7 @@ self.end_eigenvalues(typ,k) -class TestEigenComplexSymmetric(NumpyTestCase): +class TestEigenComplexSymmetric(TestCase): def get_a1(self,typ): mat_a1=numpy.array([[ 2., 0., 0., -1., 0., -1.], @@ -341,7 +338,7 @@ w.real.sort() assert_array_almost_equal(w,aw[:k]) - def check_complex_symmetric(self): + def test_complex_symmetric(self): k=2 for typ in 'FD': self.large_magnitude(typ,k) @@ -352,4 +349,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/arpack/tests/test_speigs.py =================================================================== --- trunk/scipy/sandbox/arpack/tests/test_speigs.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/arpack/tests/test_speigs.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,14 +1,12 @@ #!/usr/bin/env python -import sys -from numpy.testing import * -set_package_path() -from arpack.speigs import * -restore_path() +from scipy.testing import * +from scipy.sandbox.arpack.speigs import * + import numpy as N -class TestEigs(NumpyTestCase): +class TestEigs(TestCase): def test(self): maxn=15 # Dimension of square matrix to be solved # Use a PDP^-1 factorisation to construct matrix with known @@ -30,13 +28,13 @@ nev=4 eigvs = ARPACK_eigs(matvec, A.shape[0], nev=nev) calc_vals = eigvs[0] - # Ensure the calculate eigenvectors have the same sign as the refence values + # Ensure the calculated eigenvectors have the same sign as the reference values calc_vecs = eigvs[1] / [N.sign(x[0]) for x in eigvs[1].T] assert_array_almost_equal(calc_vals, vals[0:nev], decimal=7) assert_array_almost_equal(calc_vecs, N.array(vecs)[:,0:nev], decimal=7) -# class TestGeneigs(NumpyTestCase): +# class TestGeneigs(TestCase): # def test(self): # import pickle # import scipy.linsolve @@ -50,4 +48,4 @@ # 94.646308846854879, 95.30841709116271], decimal=11) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/buildgrid/test_build_grid.py =================================================================== --- trunk/scipy/sandbox/buildgrid/test_build_grid.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/buildgrid/test_build_grid.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -5,6 +5,8 @@ """ import sys,math,random,time +from scipy.sandbox import buildgrid + random.seed(7) global ncol,nrow,step,xmin,ymin,simple @@ -84,11 +86,10 @@ xp,yp,zp = makeInputXYZ(xyzfile, datapoints) -import BuildGrid # get file statistics nvals,xmin,xmax,ymin,ymax,zmin,zmax,zavrg,zstnd = \ - BuildGrid.filestatistics(xyzfile) + buildgrid.filestatistics(xyzfile) print xyzfile,'statistics. Number of values',nvals print 'X min %9.1f max %9.1f' % (xmin,xmax) print 'Y min %9.1f max %9.1f' % (ymin,ymax) @@ -97,7 +98,7 @@ # build grid 'fromfile' t0 = time.clock() -grid = BuildGrid.fromfile(xyzfile=xyzfile, +grid = buildgrid.fromfile(xyzfile=xyzfile, nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, method='Good', # or 'Best' - not implemented trimming=trimdist, # if no trimming - full grid @@ -112,14 +113,14 @@ if not build_only: outfile = "outdata1.xyz" t0 = time.clock() - rv = BuildGrid.tofile(filename=outfile, griddata=grid, gridtype='xyz', + rv = buildgrid.tofile(filename=outfile, griddata=grid, gridtype='xyz', nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, unvalue=1234.4321) print 'tofile():',outfile,rv,"(%.2f sec)" % (time.clock()-t0) # build grid from xyz lists t0 = time.clock() -grid2 = BuildGrid.fromxyz(xdata=xp,ydata=yp,zdata=zp, +grid2 = buildgrid.fromxyz(xdata=xp,ydata=yp,zdata=zp, nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, method='Good', # or 'Best' (not implemented) trimming=trimdist, # if no trimming - full grid @@ -133,7 +134,7 @@ if not build_only: outfile = "outdata2.xyz" t0 = time.clock() - rv = BuildGrid.tofile(filename=outfile, griddata=grid2, gridtype='xyz', + rv = buildgrid.tofile(filename=outfile, griddata=grid2, gridtype='xyz', nx=ncol, ny=nrow, step=step, xmin=xmin, ymin=ymin, unvalue=1234.4321) print 'tofile():',outfile,rv,"(%.2f sec)" % (time.clock()-t0) Modified: trunk/scipy/sandbox/cdavid/__init__.py =================================================================== --- trunk/scipy/sandbox/cdavid/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/cdavid/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -5,5 +5,5 @@ from autocorr import autocorr_oneside_nofft, autocorr_fft from segmentaxis import segment_axis -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/sandbox/cdavid/segmentaxis.py =================================================================== --- trunk/scipy/sandbox/cdavid/segmentaxis.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/cdavid/segmentaxis.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,6 +1,6 @@ import numpy as N -import unittest -from numpy.testing import NumpyTestCase, assert_array_almost_equal, assert_almost_equal, assert_equal +from numpy.testing import assert_array_almost_equal, \ + assert_almost_equal, assert_equal import warnings def segment_axis(a, length, overlap=0, axis=None, end='cut', endvalue=0): Modified: trunk/scipy/sandbox/constants/constants.py =================================================================== --- trunk/scipy/sandbox/constants/constants.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/constants/constants.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -12,7 +12,7 @@ physical constants: imported from CODATA unit conversion: see e.g. NIST special publication 811 Use at own risk: double-check values before calculating your Mars orbit-insertion burn. -Some constants exist in a few variants, which are marked with sufixes. +Some constants exist in a few variants, which are marked with suffixes. The ones without any suffix should be the most common one. """ Modified: trunk/scipy/sandbox/delaunay/tests/test_triangulate.py =================================================================== --- trunk/scipy/sandbox/delaunay/tests/test_triangulate.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/delaunay/tests/test_triangulate.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,6 +1,7 @@ from scipy.sandbox import delaunay as dlny from numpy import random import scipy as sp +from scipy.testing import * def onright(x0, y0, x1, y1, x, y): """Return True if (x,y) is to the right of the vector from (x0,y0) to @@ -16,12 +17,11 @@ assert r2 < r -class TestSanity(object): - def setup_method(self, method): +class TestSanity(TestCase): + def setUp(self): self.rs = random.RandomState(1234567890) def test_counts(self): - assert False for n in (10, 30, 100, 300, 1000, 3000): x, y = self.rs.uniform(0, 100, size=(2, n)) tri = dlny.Triangulation(x, y) @@ -35,7 +35,6 @@ assert sp.sum((tri.triangle_neighbors == -1).astype(sp.int32).flat) == k def test_ccw_triangles(self): - assert False for n in (10, 30, 100, 300, 1000, 3000): x, y = self.rs.uniform(0, 100, size=(2, n)) tri = dlny.Triangulation(x, y) @@ -44,7 +43,6 @@ assert not onright(x[i], y[i], x[j], y[j], x[k], y[k]) def test_ccw_hull(self): - assert False for n in (10, 30, 100, 300, 1000, 3000): x, y = self.rs.uniform(0, 100, size=(2, n)) tri = dlny.Triangulation(x, y) @@ -57,7 +55,6 @@ assert not onright(x[i], y[i], x[j], y[j], x[k], y[k]) def test_circle_condition(self): - assert False for n in (10, 30, 100, 300, 1000, 3000): x, y = self.rs.uniform(0, 100, size=(2, n)) tri = dlny.Triangulation(x, y) @@ -68,3 +65,8 @@ alldist2 = (sp.subtract.outer(x, tri.circumcenters[:,0])**2 + sp.subtract.outer(y, tri.circumcenters[:,1])**2) assert sp.alltrue(r2 <= alldist2) + + +if __name__ == '__main__': + unittest.main() + Deleted: trunk/scipy/sandbox/dhuard/test_histogram.py =================================================================== --- trunk/scipy/sandbox/dhuard/test_histogram.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/dhuard/test_histogram.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,99 +0,0 @@ -from numpy.testing import * -from histogram import _histogram_fixed_binsize, _histogram_digitize,\ - _histogram_searchsort, histogram,_optimize_binning -import numpy as np -from numpy.random import rand - -class TestHistogram1DFunctions(NumpyTestCase): - def check_consistency(self): - n = 100 - r = rand(n)*12-1 - bins = range(11) - a = _histogram_fixed_binsize(r, bins[0], bins[1]-bins[0], len(bins)-1) - b = _histogram_digitize(r, None, np.array(bins), False) - c = _histogram_searchsort(r,bins) - assert_array_equal(a,b) - assert_array_equal(c,b) - -class TestHistogram(NumpyTestCase): - def check_simple(self): - n=100 - v=rand(n) - (a,b)=histogram(v) - #check if the sum of the bins equals the number of samples - assert_equal(np.sum(a,axis=0),n) - #check that the bin counts are evenly spaced when the data is from a linear function - (a,b)=histogram(np.linspace(0,10,100)) - assert_array_equal(a,10) - #Check the construction of the bin array - a, b = histogram(v, bins=4, range=[.2,.8]) - assert_array_almost_equal(b['edges'],np.linspace(.2, .8, 5),8) - #Check the number of outliers - assert_equal((v<.2).sum(), b['lower']) - assert_equal((v>.8).sum(),b['upper']) - #Check the normalization - bins = [0,.5,.75,1] - a,b = histogram(v, bins, normed=True) - assert_almost_equal((a*np.diff(bins)).sum(), 1) - - def check_axis(self): - n,m = 100,20 - v = rand(n,m) - a,b = histogram(v, bins=5) - # Check dimension is reduced (axis=None). - assert_equal(a.ndim, 1) - #Check total number of count is equal to the number of samples. - assert_equal(a.sum(), n*m) - a,b = histogram(v, bins = 7, axis=0) - # Check shape of new array is ok. - assert(a.ndim == 2) - assert_array_equal(a.shape,[7, m]) - # Check normalization is consistent - a,b = histogram(v, bins = 7, axis=0, normed=True) - assert_array_almost_equal((a.T*np.diff(b['edges'])).sum(1), np.ones((m)),5) - a,b = histogram(v, bins = 7, axis=1, normed=True) - assert_array_equal(a.shape, [n,7]) - assert_array_almost_equal((a*np.diff(b['edges'])).sum(1), np.ones((n))) - # Check results are consistent with 1d estimate - a1, b1 = histogram(v[0,:], bins=b['edges'], normed=True) - assert_array_almost_equal(a1, a[0,:],7) - - def check_weights(self): - # Check weights = constant gives the same answer as no weights. - v = rand(100) - w = np.ones(100)*5 - a,b = histogram(v) - na,nb = histogram(v, normed=True) - wa,wb = histogram(v, weights=w) - nwa,nwb = histogram(v, weights=w, normed=True) - assert_array_equal(a*5, wa) - assert_array_almost_equal(na, nwa,8) - # Check weights are properly applied. - v = np.linspace(0,10,10) - w = np.concatenate((np.zeros(5), np.ones(5))) - wa,wb = histogram(v, bins=np.linspace(0,10.01, 11),weights=w) - assert_array_almost_equal(wa, w) - - def check_strategies(self): - v = rand(100) - ae,be = histogram(v, strategy='binsize') - ab,bb = histogram(v, strategy='digitize') - as,bs = histogram(v, strategy='searchsort') - assert_array_equal(ae, ab) - assert_array_equal(ae, as) - - w = rand(100) - ae,be = histogram(v, weights=w, strategy='binsize') - ab,bb = histogram(v, weights=w, strategy='digitize') - as,bs = histogram(v, weights=w, strategy='searchsort') - assert_array_almost_equal(ae, ab,8) - assert_array_almost_equal(ae, as,8) - - def check_automatic_binning(self): - v = rand(100) - h,b = histogram(v, 'Scott') - h,b = histogram(v, 'Freedman') - - -if __name__ == "__main__": - NumpyTest().run() Deleted: trunk/scipy/sandbox/dhuard/test_stats.py =================================================================== --- trunk/scipy/sandbox/dhuard/test_stats.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/dhuard/test_stats.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,45 +0,0 @@ -""" -Test statistical functions. -""" - - -from numpy.testing import * -import stats -import numpy as np - -N = 100 -np.random.seed(2) -r = np.random.randn(N) - -class TestEmpiricalCDF(NumpyTestCase): - def check_hazen(self): - - f = stats.empiricalcdf(r) - assert_equal(len(f), len(r)) - assert_array_equal(np.argsort(r), np.argsort(f)) - assert_array_equal(np.sort(f), (np.arange(N)+.5)/N) - - def check_weibull(self): - f = stats.empiricalcdf(r, 'weibull') - assert_array_equal(np.sort(f), (np.arange(N)+1.)/(N+1.)) - - def check_california(self): - f = stats.empiricalcdf(r, 'california') - assert_array_equal(np.sort(f), (np.arange(N))/float(N)) - -class TestScoreAtPercentile(NumpyTestCase): - def check_simple(self): - r = np.random.randn(1000) - s = stats.scoreatpercentile(r, [15.9,50,84.1]) - assert_array_almost_equal(s, [-1,0,1], 1) - -class TestPercentileOfScore(NumpyTestCase): - def check_simple(self): - r = np.random.randn(3000) - p = stats.percentileofscore(r, [-1,0,1]) - assert_array_almost_equal(p, [15.9, 50, 84.1], 0) - - - -if __name__ == '__main__': - NumpyTest().run() Added: trunk/scipy/sandbox/dhuard/tests/test_histogram.py =================================================================== --- trunk/scipy/sandbox/dhuard/tests/test_histogram.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/dhuard/tests/test_histogram.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -0,0 +1,99 @@ +from scipy.testing import * +from scipy.sandbox.dhuard.histogram import _histogram_fixed_binsize, _histogram_digitize,\ + _histogram_searchsort, histogram,_optimize_binning +import numpy as np +from numpy.random import rand + +class TestHistogram1DFunctions(TestCase): + def test_consistency(self): + n = 100 + r = rand(n)*12-1 + bins = range(11) + a = _histogram_fixed_binsize(r, bins[0], bins[1]-bins[0], len(bins)-1) + b = _histogram_digitize(r, None, np.array(bins), False) + c = _histogram_searchsort(r,bins) + assert_array_equal(a,b) + assert_array_equal(c,b) + +class TestHistogram(TestCase): + def test_simple(self): + n=100 + v=rand(n) + (a,b)=histogram(v) + #check if the sum of the bins equals the number of samples + assert_equal(np.sum(a,axis=0),n) + #check that the bin counts are evenly spaced when the data is from a linear function + (a,b)=histogram(np.linspace(0,10,100)) + assert_array_equal(a,10) + #Check the construction of the bin array + a, b = histogram(v, bins=4, range=[.2,.8]) + assert_array_almost_equal(b['edges'],np.linspace(.2, .8, 5),8) + #Check the number of outliers + assert_equal((v<.2).sum(), b['lower']) + assert_equal((v>.8).sum(),b['upper']) + #Check the normalization + bins = [0,.5,.75,1] + a,b = histogram(v, bins, normed=True) + assert_almost_equal((a*np.diff(bins)).sum(), 1) + + def test_axis(self): + n,m = 100,20 + v = rand(n,m) + a,b = histogram(v, bins=5) + # Check dimension is reduced (axis=None). + assert_equal(a.ndim, 1) + #Check total number of count is equal to the number of samples. + assert_equal(a.sum(), n*m) + a,b = histogram(v, bins = 7, axis=0) + # Check shape of new array is ok. + assert(a.ndim == 2) + assert_array_equal(a.shape,[7, m]) + # Check normalization is consistent + a,b = histogram(v, bins = 7, axis=0, normed=True) + assert_array_almost_equal((a.T*np.diff(b['edges'])).sum(1), np.ones((m)),5) + a,b = histogram(v, bins = 7, axis=1, normed=True) + assert_array_equal(a.shape, [n,7]) + assert_array_almost_equal((a*np.diff(b['edges'])).sum(1), np.ones((n))) + # Check results are consistent with 1d estimate + a1, b1 = histogram(v[0,:], bins=b['edges'], normed=True) + assert_array_almost_equal(a1, a[0,:],7) + + def test_weights(self): + # Check weights = constant gives the same answer as no weights. + v = rand(100) + w = np.ones(100)*5 + a,b = histogram(v) + na,nb = histogram(v, normed=True) + wa,wb = histogram(v, weights=w) + nwa,nwb = histogram(v, weights=w, normed=True) + assert_array_equal(a*5, wa) + assert_array_almost_equal(na, nwa,8) + # Check weights are properly applied. + v = np.linspace(0,10,10) + w = np.concatenate((np.zeros(5), np.ones(5))) + wa,wb = histogram(v, bins=np.linspace(0,10.01, 11),weights=w) + assert_array_almost_equal(wa, w) + + def test_strategies(self): + v = rand(100) + ae,be = histogram(v, strategy='binsize') + ab,bb = histogram(v, strategy='digitize') + as,bs = histogram(v, strategy='searchsort') + assert_array_equal(ae, ab) + assert_array_equal(ae, as) + + w = rand(100) + ae,be = histogram(v, weights=w, strategy='binsize') + ab,bb = histogram(v, weights=w, strategy='digitize') + as,bs = histogram(v, weights=w, strategy='searchsort') + assert_array_almost_equal(ae, ab,8) + assert_array_almost_equal(ae, as,8) + + def test_automatic_binning(self): + v = rand(100) + h,b = histogram(v, 'Scott') + h,b = histogram(v, 'Freedman') + + +if __name__ == "__main__": + unittest.main() Added: trunk/scipy/sandbox/dhuard/tests/test_stats.py =================================================================== --- trunk/scipy/sandbox/dhuard/tests/test_stats.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/dhuard/tests/test_stats.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -0,0 +1,44 @@ +""" +Test statistical functions. +""" + +from scipy.testing import * +from scipy.sandbox.dhuard import stats +import numpy as np + +N = 100 +np.random.seed(2) +r = np.random.randn(N) + +class TestEmpiricalCDF(TestCase): + def test_hazen(self): + + f = stats.empiricalcdf(r) + assert_equal(len(f), len(r)) + assert_array_equal(np.argsort(r), np.argsort(f)) + assert_array_equal(np.sort(f), (np.arange(N)+.5)/N) + + def test_weibull(self): + f = stats.empiricalcdf(r, 'weibull') + assert_array_equal(np.sort(f), (np.arange(N)+1.)/(N+1.)) + + def test_california(self): + f = stats.empiricalcdf(r, 'california') + assert_array_equal(np.sort(f), (np.arange(N))/float(N)) + +class TestScoreAtPercentile(TestCase): + def test_simple(self): + r = np.random.randn(1000) + s = stats.scoreatpercentile(r, [15.9,50,84.1]) + assert_array_almost_equal(s, [-1,0,1], 1) + +class TestPercentileOfScore(TestCase): + def test_simple(self): + r = np.random.randn(3000) + p = stats.percentileofscore(r, [-1,0,1]) + assert_array_almost_equal(p, [15.9, 50, 84.1], 0) + + + +if __name__ == '__main__': + unittest.main() Modified: trunk/scipy/sandbox/fdfpack/tests/test_fdf.py =================================================================== --- trunk/scipy/sandbox/fdfpack/tests/test_fdf.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/fdfpack/tests/test_fdf.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,33 +1,32 @@ +from scipy.testing import * -from numpy.testing import * -set_package_path() -from fdfpack import periodic_finite_difference as diff -restore_path() +from scipy.sandbox.fdfpack import periodic_finite_difference as diff + from numpy import arange, add, array,sin,cos,pi -class TestDiff(NumpyTestCase): - def check_1(self): +class TestDiff(TestCase): + def test_1(self): for n in [64,100,125,4000]: x = arange(n)*2*pi/n for m in range(5,15): assert_array_almost_equal(diff(sin(x),m=m),cos(x)) - def check_2(self): + def test_2(self): for n in [64,100,125,4000]: x = arange(n)*2*pi/n for m in range(8,15)+[6]: assert_array_almost_equal(diff(sin(x),k=2,m=m),-sin(x)) - def check_3(self): + def test_3(self): for n in [64,100,125,4000]: x = arange(n)*2*pi/n for m in range(7,15): assert_array_almost_equal(diff(sin(x),k=3,m=m)/n,-cos(x)/n) - def check_4(self): + def test_4(self): for n in [64,100,125,200,2000]: x = arange(n)*2*pi/n for m in range(10,15): assert_array_almost_equal(diff(sin(x),k=4,m=m)/n,sin(x)/n) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/lobpcg/__init__.py =================================================================== --- trunk/scipy/sandbox/lobpcg/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/lobpcg/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -7,5 +7,5 @@ from lobpcg import * -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/sandbox/lobpcg/tests/large_scale.py =================================================================== --- trunk/scipy/sandbox/lobpcg/tests/large_scale.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/lobpcg/tests/large_scale.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,4 +1,5 @@ -from scipy import * +from scipy import array, arange, ones, sort, cos, pi, rand, \ + set_printoptions, r_ from scipy.sandbox import lobpcg from scipy.sparse import spdiags, speye from pylab import loglog, show, xlabel, ylabel, title Modified: trunk/scipy/sandbox/lobpcg/tests/test_lobpcg.py =================================================================== --- trunk/scipy/sandbox/lobpcg/tests/test_lobpcg.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/lobpcg/tests/test_lobpcg.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,10 +1,11 @@ -from scipy import * +from scipy import array, arange, ones, sort, cos, pi, rand, \ + set_printoptions, r_, diag, linalg from scipy.sandbox import lobpcg from symeig import symeig from pylab import plot, show, legend, xlabel, ylabel set_printoptions(precision=3,linewidth=90) -def test1(n): +def check1(n): L = 1.0 le=L/n rho = 7.85e3 @@ -16,7 +17,7 @@ B = mass*(diag(r_[4.*ones(n-1),2])+diag(ones(n-1),1)+diag(ones(n-1),-1)) return A,B -def test2(n): +def check2(n): x = arange(1,n+1) B = diag(1./x) y = arange(n-1,0,-1) @@ -26,22 +27,22 @@ n = 100 # Dimension -A,B = test1(n) # Fixed-free elastic rod -A,B = test2(n) # Mikota pair acts as a nice test since the eigenvalues are the squares of the integers n, n=1,2,... +def test_1and2(): + A,B = check1(n) # Fixed-free elastic rod + A,B = check2(n) # Mikota pair acts as a nice test since the eigenvalues are the squares of the integers n, n=1,2,... + + m = 20 + V = rand(n,m) + X = linalg.orth(V) + + eigs,vecs = lobpcg.lobpcg(X,A,B) + eigs = sort(eigs) + + w,v=symeig(A,B) -m = 20 -V = rand(n,m) -X = linalg.orth(V) - -eigs,vecs = lobpcg.lobpcg(X,A,B) -eigs = sort(eigs) - -w,v=symeig(A,B) - - -plot(arange(0,len(w[:m])),w[:m],'bx',label='Results by symeig') -plot(arange(0,len(eigs)),eigs,'r+',label='Results by lobpcg') -legend() -xlabel(r'Eigenvalue $i$') -ylabel(r'$\lambda_i$') -show() + plot(arange(0,len(w[:m])),w[:m],'bx',label='Results by symeig') + plot(arange(0,len(eigs)),eigs,'r+',label='Results by lobpcg') + legend() + xlabel(r'Eigenvalue $i$') + ylabel(r'$\lambda_i$') + show() Modified: trunk/scipy/sandbox/maskedarray/alternative_versions/test_mrecarray.py =================================================================== --- trunk/scipy/sandbox/maskedarray/alternative_versions/test_mrecarray.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/maskedarray/alternative_versions/test_mrecarray.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -14,22 +14,18 @@ import numpy as N import numpy.core.fromnumeric as fromnumeric -from numpy.testing import NumpyTest, NumpyTestCase -from numpy.testing.utils import build_err_msg +from scipy.testing import * +from scipy.sandbox.maskedarray.testutils import * -import maskedarray.testutils -from maskedarray.testutils import * +import scipy.sandbox.maskedarray.core as MA +from scipy.sandbox.maskedarray.mrecords import mrecarray, fromarrays, fromtextfile, fromrecords -import maskedarray.core as MA -import maskedarray.mrecords -from maskedarray.mrecords import mrecarray, fromarrays, fromtextfile, fromrecords - #.............................................................................. -class TestMrecarray(NumpyTestCase): +class TestMrecarray(TestCase): "Base test class for MaskedArrays." def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.setup() def setup(self): @@ -125,4 +121,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/maskedarray/testutils.py =================================================================== --- trunk/scipy/sandbox/maskedarray/testutils.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/maskedarray/testutils.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -14,7 +14,6 @@ from numpy.core import ndarray from numpy.core.numerictypes import float_ import numpy.core.umath as umath -from numpy.testing import NumpyTest, NumpyTestCase from numpy.testing.utils import build_err_msg, rand import core Modified: trunk/scipy/sandbox/montecarlo/tests/test_dictsampler.py =================================================================== --- trunk/scipy/sandbox/montecarlo/tests/test_dictsampler.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/montecarlo/tests/test_dictsampler.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -10,19 +10,16 @@ from numpy import arange, add, array, dot, zeros, identity import sys -from numpy.testing import * -set_package_path() -from numpy import * +from scipy.testing import * + +from numpy import sum, array, average, sqrt #from scipy.montecarlo import * from scipy.sandbox.montecarlo import * from scipy import stats -restore_path() -import unittest - -class test_dict_sampler(NumpyTestCase): - def check_simple(self): +class test_dict_sampler(TestCase): + def test_simple(self): """ # Sample from this discrete distribution: # x 'a' 'b' 'c' @@ -51,7 +48,7 @@ #z = 2.5758 # = norminv(0.995), for a 1% confidence interval #assert abs(m - lam) < z * lam/sqrt(numsamples) - def check_sanity(self): + def test_sanity(self): # Sample from this pmf: # x 0 1 2 3 4 # p(x) 0.5 0.1 0.15 0 0.25 @@ -76,4 +73,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/montecarlo/tests/test_intsampler.py =================================================================== --- trunk/scipy/sandbox/montecarlo/tests/test_intsampler.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/montecarlo/tests/test_intsampler.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -18,16 +18,14 @@ from numpy import arange, add, array, dot, zeros, identity import sys -from numpy.testing import * -set_package_path() -from numpy import * +from scipy.testing import * + from scipy.sandbox.montecarlo import * from scipy import stats -restore_path() -class test_int_sampler(NumpyTestCase): - def check_simple(self): +class test_int_sampler(TestCase): + def test_simple(self): # Sample from a Poisson distribution, P(lambda = 10.0) lam = 10.0 n = 35 @@ -41,7 +39,7 @@ z = 2.5758 # = norminv(0.995), for a 1% confidence interval assert abs(m - lam) < z * lam/sqrt(numsamples) - def check_sanity(self): + def test_sanity(self): # Sample from this pmf: # x 0 1 2 3 4 # p(x) 0.5 0.1 0.15 0 0.25 @@ -67,4 +65,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/multigrid/__init__.py =================================================================== --- trunk/scipy/sandbox/multigrid/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/multigrid/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -5,5 +5,5 @@ from multilevel import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/sandbox/multigrid/simple_test.py =================================================================== --- trunk/scipy/sandbox/multigrid/simple_test.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/multigrid/simple_test.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,4 +1,4 @@ -from scipy import * +from scipy import rand from scipy.sandbox.multigrid.sa import * from scipy.sandbox.multigrid import * from scipy.sandbox.multigrid.utils import * Modified: trunk/scipy/sandbox/multigrid/tests/test_adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,20 +1,20 @@ -from numpy.testing import * +from scipy.testing import * from scipy.sparse import csr_matrix from numpy import arange,ones,zeros,array,eye,vstack,diff -set_package_path() + from scipy.sandbox.multigrid.sa import sa_fit_candidates from scipy.sandbox.multigrid.adaptive import augment_candidates -restore_path() + #import pdb; pdb.set_trace() -class TestAdaptiveSA(NumpyTestCase): +class TestAdaptiveSA(TestCase): def setUp(self): pass -class TestAugmentCandidates(NumpyTestCase): +class TestAugmentCandidates(TestCase): def setUp(self): self.cases = [] @@ -25,7 +25,7 @@ - def check_first_level(self): + def test_first_level(self): cases = [] ## tests where AggOp includes all DOFs @@ -66,4 +66,4 @@ if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/multigrid/tests/test_relaxation.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,4 +1,4 @@ -from numpy.testing import * +from scipy.testing import * import numpy import scipy @@ -6,14 +6,14 @@ from scipy.sparse import spdiags -set_package_path() + import scipy.sandbox.multigrid from scipy.sandbox.multigrid.relaxation import polynomial_smoother,gauss_seidel,jacobi -restore_path() -class TestRelaxation(NumpyTestCase): - def check_polynomial(self): + +class TestRelaxation(TestCase): + def test_polynomial(self): N = 3 A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x0 = arange(N).astype(numpy.float64) @@ -37,7 +37,7 @@ polynomial_smoother(A,x,b,[-0.14285714, 1., -2.]) assert_almost_equal(x,x0 - 0.14285714*A*A*r + A*r - 2*r) - def check_jacobi(self): + def test_jacobi(self): N = 1 A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) @@ -81,7 +81,7 @@ jacobi(A,x,b,omega=1.0/3.0) assert_almost_equal(x,2.0/3.0*x_copy + 1.0/3.0*array([5.5,11.0,15.5])) - def check_gauss_seidel_bsr(self): + def test_gauss_seidel_bsr(self): cases = [] for N in [1,2,3,4,5,6,10]: @@ -100,7 +100,7 @@ assert_almost_equal(x_bsr,x_csr) - def check_gauss_seidel_csr(self): + def test_gauss_seidel_csr(self): N = 1 A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') x = arange(N).astype(numpy.float64) @@ -158,4 +158,4 @@ self.assert_(allclose(resid1,resid2)) if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,7 +4,7 @@ except: pass -from numpy.testing import * +from scipy.testing import * from numpy import sqrt,empty,ones,arange,array_split,eye,array, \ zeros,diag,zeros_like,diff,matrix,hstack,vstack from numpy.linalg import norm @@ -14,7 +14,7 @@ isspmatrix_lil import numpy -set_package_path() + import scipy.sandbox.multigrid from scipy.sandbox.multigrid.sa import sa_strong_connections, sa_constant_interpolation, \ sa_interpolation, sa_fit_candidates, \ @@ -22,9 +22,9 @@ from scipy.sandbox.multigrid.multilevel import poisson_problem1D,poisson_problem2D, \ smoothed_aggregation_solver from scipy.sandbox.multigrid.utils import diag_sparse -restore_path() + #def sparsity(A): # A = A.copy() # @@ -38,7 +38,7 @@ # # return A -class TestSA(NumpyTestCase): +class TestSA(TestCase): def setUp(self): self.cases = [] @@ -54,7 +54,7 @@ self.cases.append( poisson_problem2D(N) ) - def check_sa_strong_connections(self): + def test_sa_strong_connections(self): for A in self.cases: for epsilon in [0.0,0.1,0.5,1.0,10.0]: S_expected = reference_sa_strong_connections(A,epsilon) @@ -62,7 +62,7 @@ assert_almost_equal(S_result.todense(),S_expected.todense()) #assert_array_equal(sparsity(S_result).todense(),sparsity(S_expected).todense()) - def check_sa_constant_interpolation(self): + def test_sa_constant_interpolation(self): for A in self.cases: for epsilon in [0.0,0.1,0.5,1.0]: S_expected = reference_sa_constant_interpolation(A,epsilon) @@ -101,7 +101,7 @@ assert_array_equal(S_result.todense(),S_expected) - def check_user_aggregation(self): + def test_user_aggregation(self): """check that the sa_interpolation accepts user-defined aggregates""" user_cases = [] @@ -128,7 +128,7 @@ -class TestFitCandidates(NumpyTestCase): +class TestFitCandidates(TestCase): def setUp(self): self.cases = [] @@ -163,7 +163,7 @@ self.cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9),arange(9)**2)).T )) self.cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9))).T )) - def check_all_cases(self): + def test_all_cases(self): """Test case where aggregation includes all fine nodes""" def mask_candidate(AggOp,candidates): @@ -194,7 +194,7 @@ ## assert_almost_equal(Q*(Q.T*fine_candidates),fine_candidates) -class TestSASolverPerformance(NumpyTestCase): +class TestSASolverPerformance(TestCase): def setUp(self): self.cases = [] @@ -203,7 +203,7 @@ # TODO add unstructured tests - def check_basic(self): + def test_basic(self): """check that method converges at a reasonable rate""" for A,candidates in self.cases: @@ -220,7 +220,7 @@ assert(avg_convergence_ratio < 0.5) - def check_DAD(self): + def test_DAD(self): for A,candidates in self.cases: x = rand(A.shape[0]) @@ -326,4 +326,4 @@ if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/multigrid/tests/test_utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,4 +1,4 @@ -from numpy.testing import * +from scipy.testing import * import numpy import scipy @@ -7,16 +7,16 @@ from scipy.sparse import csr_matrix from scipy.linalg import norm -set_package_path() + from scipy.sandbox.multigrid.utils import approximate_spectral_radius, \ infinity_norm, diag_sparse, \ symmetric_rescaling, \ expand_into_blocks -restore_path() -class TestUtils(NumpyTestCase): - def check_approximate_spectral_radius(self): + +class TestUtils(TestCase): + def test_approximate_spectral_radius(self): cases = [] cases.append( matrix([[-4]]) ) @@ -38,7 +38,7 @@ #TODO test larger matrices - def check_infinity_norm(self): + def test_infinity_norm(self): A = matrix([[-4]]) assert_equal(infinity_norm(csr_matrix(A)),4) @@ -51,7 +51,7 @@ A = matrix([[1.3,-4.7,0],[-2.23,5.5,0],[9,0,-2]]) assert_equal(infinity_norm(csr_matrix(A)),11) - def check_diag_sparse(self): + def test_diag_sparse(self): #check sparse -> array A = matrix([[-4]]) assert_equal(diag_sparse(csr_matrix(A)),[-4]) @@ -79,7 +79,7 @@ assert_equal(diag_sparse(array([1.3,5.5,-2])).todense(),csr_matrix(A).todense()) - def check_symmetric_rescaling(self): + def test_symmetric_rescaling(self): cases = [] cases.append( diag_sparse(array([1,2,3,4])) ) cases.append( diag_sparse(array([1,0,3,4])) ) @@ -105,7 +105,7 @@ D_sqrt,D_sqrt_inv = diag_sparse(D_sqrt),diag_sparse(D_sqrt_inv) assert_almost_equal((D_sqrt_inv*A*D_sqrt_inv).todense(), DAD.todense()) - def check_expand_into_blocks(self): + def test_expand_into_blocks(self): cases = [] cases.append( ( matrix([[1]]), (1,2) ) ) cases.append( ( matrix([[1]]), (2,1) ) ) @@ -129,4 +129,4 @@ if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/numexpr/__init__.py =================================================================== --- trunk/scipy/sandbox/numexpr/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/numexpr/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,7 +1,4 @@ -from numexpr.info import __doc__ -from numexpr.expressions import E -from numexpr.compiler import numexpr, disassemble, evaluate +from scipy.sandbox.numexpr.info import __doc__ +from scipy.sandbox.numexpr.expressions import E +from scipy.sandbox.numexpr.compiler import numexpr, disassemble, evaluate -def test(level=1, verbosity=1): - from numpy.testing import NumpyTest - NumpyTest().test(level, verbosity) Modified: trunk/scipy/sandbox/numexpr/compiler.py =================================================================== --- trunk/scipy/sandbox/numexpr/compiler.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/numexpr/compiler.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,7 +1,7 @@ import sys import numpy -from numexpr import interpreter, expressions +from scipy.sandbox.numexpr import interpreter, expressions typecode_to_kind = {'b': 'bool', 'i': 'int', 'l': 'long', 'f': 'float', 'c': 'complex', 's': 'str', 'n' : 'none'} Modified: trunk/scipy/sandbox/numexpr/expressions.py =================================================================== --- trunk/scipy/sandbox/numexpr/expressions.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/numexpr/expressions.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -6,7 +6,7 @@ import numpy -from numexpr import interpreter +from scipy.sandbox.numexpr import interpreter class Expression(object): def __init__(self): Modified: trunk/scipy/sandbox/numexpr/tests/test_numexpr.py =================================================================== --- trunk/scipy/sandbox/numexpr/tests/test_numexpr.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/numexpr/tests/test_numexpr.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,31 +1,32 @@ import new -from numpy import * -from numpy.testing import * +from numpy import array, arange, sin, zeros, sum, int32, empty, \ + prod, uint16, complex_, float64, rec +from scipy.testing import * -set_package_path() -from numexpr import E, numexpr, evaluate, disassemble -restore_path() -class test_numexpr(NumpyTestCase): - def check_simple(self): +from scipy.sandbox.numexpr import E, numexpr, evaluate, disassemble + + +class test_numexpr(TestCase): + def test_simple(self): ex = 2.0 * E.a + 3.0 * E.b * E.c func = numexpr(ex, signature=[('a', float), ('b', float), ('c', float)]) x = func(array([1., 2, 3]), array([4., 5, 6]), array([7., 8, 9])) assert_array_equal(x, array([ 86., 124., 168.])) - def check_simple_expr_small_array(self): + def test_simple_expr_small_array(self): func = numexpr(E.a) x = arange(100.0) y = func(x) assert_array_equal(x, y) - def check_simple_expr(self): + def test_simple_expr(self): func = numexpr(E.a) x = arange(1e5) y = func(x) assert_array_equal(x, y) - def check_rational_expr(self): + def test_rational_expr(self): func = numexpr((E.a + 2.0*E.b) / (1 + E.a + 4*E.b*E.b)) a = arange(1e5) b = arange(1e5) * 0.1 @@ -33,7 +34,7 @@ y = func(a, b) assert_array_equal(x, y) - def check_reductions(self): + def test_reductions(self): # Check that they compile OK. assert_equal(disassemble(numexpr("sum(x**2+2, axis=None)", [('x', float)])), [('mul_fff', 't3', 'r1[x]', 'r1[x]'), @@ -72,7 +73,7 @@ assert_equal(evaluate("sum(x**2+2,axis=0)"), sum(x**2+2,axis=0)) assert_equal(evaluate("prod(x**2+2,axis=0)"), prod(x**2+2,axis=0)) - def check_axis(self): + def test_axis(self): y = arange(9.0).reshape(3,3) try: evaluate("sum(y, axis=2)") @@ -90,37 +91,37 @@ - def check_r0_reuse(self): + def test_r0_reuse(self): assert_equal(disassemble(numexpr("x**2+2", [('x', float)])), [('mul_fff', 'r0', 'r1[x]', 'r1[x]'), ('add_fff', 'r0', 'r0', 'c2[2.0]')]) -class test_evaluate(NumpyTestCase): - def check_simple(self): +class test_evaluate(TestCase): + def test_simple(self): a = array([1., 2., 3.]) b = array([4., 5., 6.]) c = array([7., 8., 9.]) x = evaluate("2*a + 3*b*c") assert_array_equal(x, array([ 86., 124., 168.])) - def check_simple_expr_small_array(self): + def test_simple_expr_small_array(self): x = arange(100.0) y = evaluate("x") assert_array_equal(x, y) - def check_simple_expr(self): + def test_simple_expr(self): x = arange(1e5) y = evaluate("x") assert_array_equal(x, y) - def check_rational_expr(self): + def test_rational_expr(self): a = arange(1e5) b = arange(1e5) * 0.1 x = (a + 2*b) / (1 + a + 4*b*b) y = evaluate("(a + 2*b) / (1 + a + 4*b*b)") assert_array_equal(x, y) - def check_complex_expr(self): + def test_complex_expr(self): def complex(a, b): c = zeros(a.shape, dtype=complex_) c.real = a @@ -135,7 +136,7 @@ assert_array_almost_equal(x, y) - def check_complex_strides(self): + def test_complex_strides(self): a = arange(100).reshape(10,10)[::2] b = arange(50).reshape(5,10) assert_array_equal(evaluate("a+b"), a+b) @@ -148,7 +149,7 @@ assert_array_equal(evaluate("a0+c1"), a0+c1) - def check_broadcasting(self): + def test_broadcasting(self): a = arange(100).reshape(10,10)[::2] c = arange(10) d = arange(5).reshape(5,1) @@ -157,20 +158,20 @@ expr = numexpr("2.0*a+3.0*c",[('a',float),('c', float)]) assert_array_equal(expr(a,c), 2.0*a+3.0*c) - def check_all_scalar(self): + def test_all_scalar(self): a = 3. b = 4. assert_equal(evaluate("a+b"), a+b) expr = numexpr("2*a+3*b",[('a',float),('b', float)]) assert_equal(expr(a,b), 2*a+3*b) - def check_run(self): + def test_run(self): a = arange(100).reshape(10,10)[::2] b = arange(10) expr = numexpr("2*a+3*b",[('a',float),('b', float)]) assert_array_equal(expr(a,b), expr.run(a,b)) - def check_illegal_value(self): + def test_illegal_value(self): a = arange(3) try: evaluate("a < [0, 0, 0]") @@ -239,7 +240,7 @@ class Skip(Exception): pass -class test_expressions(NumpyTestCase): +class test_expressions(TestCase): pass def generate_check_expressions(): @@ -306,21 +307,21 @@ generate_check_expressions() -class test_int32_int64(NumpyTestCase): - def check_small_long(self): +class test_int32_int64(TestCase): + def test_small_long(self): # Small longs should not be downgraded to ints. res = evaluate('42L') assert_array_equal(res, 42) self.assertEqual(res.dtype.name, 'int64') - def check_big_int(self): + def test_big_int(self): # Big ints should be promoted to longs. # This test may only fail under 64-bit platforms. res = evaluate('2**40') assert_array_equal(res, 2**40) self.assertEqual(res.dtype.name, 'int64') - def check_long_constant_promotion(self): + def test_long_constant_promotion(self): int32array = arange(100, dtype='int32') res = int32array * 2 res32 = evaluate('int32array * 2') @@ -330,7 +331,7 @@ self.assertEqual(res32.dtype.name, 'int32') self.assertEqual(res64.dtype.name, 'int64') - def check_int64_array_promotion(self): + def test_int64_array_promotion(self): int32array = arange(100, dtype='int32') int64array = arange(100, dtype='int64') respy = int32array * int64array @@ -338,7 +339,7 @@ assert_array_equal(respy, resnx) self.assertEqual(resnx.dtype.name, 'int64') -class test_strings(NumpyTestCase): +class test_strings(TestCase): BLOCK_SIZE1 = 128 BLOCK_SIZE2 = 8 str_list1 = ['foo', 'bar', '', ' '] @@ -348,7 +349,7 @@ str_array2 = array(str_list2 * str_nloops) str_constant = 'doodoo' - def check_null_chars(self): + def test_null_chars(self): str_list = [ '\0\0\0', '\0\0foo\0', '\0\0foo\0b', '\0\0foo\0b\0', 'foo\0', 'foo\0b', 'foo\0b\0', 'foo\0bar\0baz\0\0' ] @@ -356,14 +357,14 @@ r = evaluate('s') self.assertEqual(s, r.tostring()) # check *all* stored data - def check_compare_copy(self): + def test_compare_copy(self): sarr = self.str_array1 expr = 'sarr' res1 = eval(expr) res2 = evaluate(expr) assert_array_equal(res1, res2) - def check_compare_array(self): + def test_compare_array(self): sarr1 = self.str_array1 sarr2 = self.str_array2 expr = 'sarr1 >= sarr2' @@ -371,7 +372,7 @@ res2 = evaluate(expr) assert_array_equal(res1, res2) - def check_compare_variable(self): + def test_compare_variable(self): sarr = self.str_array1 svar = self.str_constant expr = 'sarr >= svar' @@ -379,20 +380,20 @@ res2 = evaluate(expr) assert_array_equal(res1, res2) - def check_compare_constant(self): + def test_compare_constant(self): sarr = self.str_array1 expr = 'sarr >= %r' % self.str_constant res1 = eval(expr) res2 = evaluate(expr) assert_array_equal(res1, res2) - def check_add_string_array(self): + def test_add_string_array(self): sarr1 = self.str_array1 sarr2 = self.str_array2 expr = 'sarr1 + sarr2' self.assert_missing_op('add_sss', expr, locals()) - def check_add_numeric_array(self): + def test_add_numeric_array(self): sarr = self.str_array1 narr = arange(len(sarr), dtype='int32') expr = 'sarr >= narr' @@ -408,7 +409,7 @@ else: self.fail(msg) - def check_compare_prefix(self): + def test_compare_prefix(self): # Check comparing two strings where one is a prefix of the # other. for s1, s2 in [ ('foo', 'foobar'), ('foo', 'foo\0bar'), @@ -429,8 +430,8 @@ # because in 64-bit machines 'c2' is unaligned. However, this should # check most platforms where, while not unaligned, 'len(datatype) > # boundary_alignment' is fullfilled. -class test_irregular_stride(NumpyTestCase): - def check_select(self): +class test_irregular_stride(TestCase): + def test_select(self): f0 = arange(10, dtype=int32) f1 = arange(10, dtype=float64) @@ -447,4 +448,4 @@ if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/pyloess/mpyloess.py =================================================================== --- trunk/scipy/sandbox/pyloess/mpyloess.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/pyloess/mpyloess.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -42,9 +42,8 @@ nempty = numeric.empty nlogical_not = numpy.logical_not -import maskedarray.core -from maskedarray.core import masked, nomask, mask_or -from maskedarray.core import masked_array as marray +from scipy.sandbox.maskedarray.core import masked, nomask, mask_or, \ + masked_array as marray import _lowess, _stl, _mloess Modified: trunk/scipy/sandbox/pyloess/tests/test_mpyloess.py =================================================================== --- trunk/scipy/sandbox/pyloess/tests/test_mpyloess.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/pyloess/tests/test_mpyloess.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -18,27 +18,24 @@ import numpy.core.numeric as numeric fromiter = numpy.fromiter -import maskedarray +from scipy.sandbox import maskedarray marray = maskedarray.masked_array masked_values = maskedarray.masked_values -from numpy.testing import NumpyTest, NumpyTestCase -from maskedarray.testutils import build_err_msg, \ +from scipy.testing import * +from scipy.sandbox.maskedarray.testutils import build_err_msg, \ assert_equal, assert_almost_equal +from scipy.sandbox.pyloess.mpyloess import lowess, stl, loess, loess_anova -import mpyloess -reload(mpyloess) -from mpyloess import lowess, stl, loess, loess_anova - #####--------------------------------------------------------------------------- #---- --- LOWESS --- #####--------------------------------------------------------------------------- -class TestLowess(NumpyTestCase): +class TestLowess(TestCase): "Test class for lowess." # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) X = marray([ 1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8,10,12,14,50]) Y = marray([18, 2,15, 6,10, 4,16,11, 7, 3,14,17,20,12, 9,13, 1, 8, 5,19]) idx = X.argsort() @@ -95,11 +92,11 @@ #####--------------------------------------------------------------------------- #---- --- STL --- #####--------------------------------------------------------------------------- -class TestStl(NumpyTestCase): +class TestStl(TestCase): "Tests STL." # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) # Get CO2 data ................ filename = os.path.join('tests','co2_data') F = open(filename, 'r') @@ -141,11 +138,11 @@ #---- --- LOESS --- #####--------------------------------------------------------------------------- -class TestLoess2D(NumpyTestCase): +class TestLoess2D(TestCase): "Test class for lowess." # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) dfile = open(os.path.join('tests','madeup_data'), 'r') dfile.readline() x = fromiter((float(v) for v in dfile.readline().rstrip().split()), @@ -292,11 +289,11 @@ #####--------------------------------------------------------------------------- #---- --- test 1D --- #####--------------------------------------------------------------------------- -class TestLoessGas(NumpyTestCase): +class TestLoessGas(TestCase): "Test class for lowess." # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) NOx = marray([4.818, 2.849, 3.275, 4.691, 4.255, 5.064, 2.118, 4.602, 2.286, 0.970, 3.965, 5.344, 3.834, 1.990, 5.199, 5.283, 3.752, 0.537, 1.640, 5.055, 4.937, 1.561]) @@ -433,4 +430,4 @@ ######################################################################## if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/pyloess/tests/test_pyloess.py =================================================================== --- trunk/scipy/sandbox/pyloess/tests/test_pyloess.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/pyloess/tests/test_pyloess.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -21,22 +21,18 @@ narray = numpy.array -from numpy.testing import NumpyTest, NumpyTestCase -from numpy.testing.utils import build_err_msg, \ - assert_equal, assert_almost_equal +from scipy.testing import * -import pyloess -reload(pyloess) -from pyloess import lowess, stl, loess, loess_anova +from scipy.sandbox.pyloess import lowess, stl, loess, loess_anova #####--------------------------------------------------------------------------- #---- --- LOWESS --- #####--------------------------------------------------------------------------- -class TestLowess(NumpyTestCase): +class TestLowess(TestCase): "Test class for lowess." # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) X = narray([ 1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8,10,12,14,50]) Y = narray([18, 2,15, 6,10, 4,16,11, 7, 3,14,17,20,12, 9,13, 1, 8, 5,19]) idx = X.argsort() @@ -78,11 +74,11 @@ #####--------------------------------------------------------------------------- #---- --- STL --- #####--------------------------------------------------------------------------- -class TestStl(NumpyTestCase): +class TestStl(TestCase): "Tests STL." # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) # Get CO2 data ................ filename = os.path.join('tests','co2_data') F = open(filename, 'r') @@ -124,11 +120,11 @@ #---- --- LOESS --- #####--------------------------------------------------------------------------- -class TestLoess2d(NumpyTestCase): +class TestLoess2d(TestCase): "Test class for lowess." # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) dfile = open(os.path.join('tests','madeup_data'), 'r') dfile.readline() x = fromiter((float(v) for v in dfile.readline().rstrip().split()), @@ -273,11 +269,11 @@ #####--------------------------------------------------------------------------- #---- --- test 2D #####--------------------------------------------------------------------------- -class TestLoessGas(NumpyTestCase): +class TestLoessGas(TestCase): "Test class for lowess." # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) NOx = numpy.array([4.818, 2.849, 3.275, 4.691, 4.255, 5.064, 2.118, 4.602, 2.286, 0.970, 3.965, 5.344, 3.834, 1.990, 5.199, 5.283, 3.752, 0.537, 1.640, 5.055, 4.937, 1.561]) @@ -387,4 +383,4 @@ ######################################################################## if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/rbf/__init__.py =================================================================== --- trunk/scipy/sandbox/rbf/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/rbf/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -7,5 +7,5 @@ from rbf import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/sandbox/rbf/tests/test_rbf.py =================================================================== --- trunk/scipy/sandbox/rbf/tests/test_rbf.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/rbf/tests/test_rbf.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -2,23 +2,23 @@ # Created by John Travers, Robert Hetland, 2007 """ Test functions for rbf module """ -from numpy.testing import * +from scipy.testing import * from numpy import linspace, sin, random, exp -set_package_path() -from rbf.rbf import Rbf -restore_path() -class TestRbf1d(NumpyTestCase): - def check_multiquadrics(self): +from scipy.sandbox.rbf.rbf import Rbf + + +class TestRbf1d(TestCase): + def test_multiquadrics(self): x = linspace(0,10,9) y = sin(x) rbf = Rbf(x, y) yi = rbf(x) assert_array_almost_equal(y, yi) -class TestRbf2d(NumpyTestCase): - def check_multiquadrics(self): +class TestRbf2d(TestCase): + def test_multiquadrics(self): x = random.rand(50,1)*4-2 y = random.rand(50,1)*4-2 z = x*exp(-x**2-y**2) @@ -27,8 +27,8 @@ zi.shape = x.shape assert_array_almost_equal(z, zi) -class TestRbf3d(NumpyTestCase): - def check_multiquadrics(self): +class TestRbf3d(TestCase): + def test_multiquadrics(self): x = random.rand(50,1)*4-2 y = random.rand(50,1)*4-2 z = random.rand(50,1)*4-2 @@ -39,4 +39,4 @@ assert_array_almost_equal(di, d) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/spline/__init__.py =================================================================== --- trunk/scipy/sandbox/spline/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/spline/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -10,5 +10,5 @@ from spline import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/sandbox/spline/tests/test_fitpack.py =================================================================== --- trunk/scipy/sandbox/spline/tests/test_fitpack.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/spline/tests/test_fitpack.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -12,20 +12,20 @@ """ import sys -from numpy.testing import * +from scipy.testing import * from numpy import array, arange, around, pi, sin, ravel, zeros, asarray -set_package_path() -from spline.fitpack import splprep, splrep, splev, sproot, splint, spalde -from spline.fitpack import bisplev, bisplrep, splprep -restore_path() +from scipy.sandbox.spline.fitpack import splprep, splrep, splev, sproot, \ + splint, spalde, bisplev, bisplrep, splprep + + set_local_path() from dierckx_test_data import * restore_path() -class TestSplrepSplev(NumpyTestCase): - def check_curfit_against_dierckx_smth(self): +class TestSplrepSplev(TestCase): + def test_curfit_against_dierckx_smth(self): x,y = curfit_test['x'],curfit_test['y'] k,s = curfit_test_smth['k'],curfit_test_smth['s'] iopt = curfit_test_smth['iopt'] @@ -42,7 +42,7 @@ assert_array_almost_equal(around(sp,1), curfit_test_smth['sp'][i]) - def check_curfit_against_dierckx_lsq(self): + def test_curfit_against_dierckx_lsq(self): """ Test against results obtined from the pure fortran routines. Here we check simple spline creation and evaluation. @@ -60,7 +60,7 @@ assert_array_almost_equal(around(sp,1), curfit_test_lsq['sp'][i]) - def check_percur_against_dierckx(self): + def test_percur_against_dierckx(self): x,y = percur_test['x'], percur_test['y'] k,s = percur_test['k'], percur_test['s'] iopt, res = percur_test['iopt'], percur_test['res'] @@ -83,8 +83,8 @@ yy = asarray(splev(x,tck)) assert_array_almost_equal(yy,sp[i], decimal=3) -class TestSplprepSplev(NumpyTestCase): - def check_parcur_against_dierckx(self): +class TestSplprepSplev(TestCase): + def test_parcur_against_dierckx(self): xa,xo = parcur_test['xa'], parcur_test['xo'] k,s = parcur_test['k'], parcur_test['s'] u = parcur_test['u'] @@ -120,7 +120,7 @@ yy[1::2] = y[1] assert_array_almost_equal(yy,sp[i], decimal=3) - def check_clocur_against_dierckx(self): + def test_clocur_against_dierckx(self): xa,xo = clocur_test['xa'], clocur_test['xo'] k,s = clocur_test['k'], clocur_test['s'] u = clocur_test['u'] @@ -155,8 +155,8 @@ yy[1::2] = y[1,:-1] assert_array_almost_equal(yy,sp[i], decimal=3) -class TestSplintSpalde(NumpyTestCase): - def check_splint_spalde(self): +class TestSplintSpalde(TestCase): + def test_splint_spalde(self): per = [0, 1, 0] N = [20, 20, 50] ia = [0, 0, 0.2*pi] @@ -178,8 +178,8 @@ assert_almost_equal(1, ddr/f1(dx,d), decimal=2) d=d+1 -class TestSplder(NumpyTestCase): - def check_splder(self): +class TestSplder(TestCase): + def test_splder(self): N = 50 a,b = 0,2*pi dx = 0.2*pi @@ -192,8 +192,8 @@ d2 = splev(dx,tck,der=1) assert_almost_equal(1, dr[1]/f1(dx,1.0), decimal=2) -class TestSproot(NumpyTestCase): - def check_sproot(self): +class TestSproot(TestCase): + def test_sproot(self): a=0 b=15 N=20 @@ -204,7 +204,7 @@ ex = array([0.0, pi, 2.0*pi, 3.0*pi, 4.0*pi]) assert_array_almost_equal(sproot(tck),ex, decimal=3) -class TestBisplevBisplrep(NumpyTestCase): +class TestBisplevBisplrep(TestCase): def test_bisplev_bisplrep(self): f=f2; kx=3; ky=3; xb=0; xe=2*pi yb=0; ye=2*pi; Nx=20; Ny=20; s=0 @@ -219,8 +219,8 @@ v2.shape=len(tt[0]),len(tt[1]) assert_almost_equal(0.0, norm2(ravel(v1-v2)), decimal=5) -class TestParcur(NumpyTestCase): - def check_parcur(self): +class TestParcur(TestCase): + def test_parcur(self): f=f1; per=0; s=0; a=0; b=2*pi; N=[20,50] ia=0; ib=2*pi; dx=0.2*pi @@ -239,4 +239,4 @@ around(abs(splev(uv[0],tck)-f(uv[0])),2),decimal=1) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/spline/tests/test_spline.py =================================================================== --- trunk/scipy/sandbox/spline/tests/test_spline.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/spline/tests/test_spline.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -13,22 +13,20 @@ """ import sys -from numpy.testing import * +from scipy.testing import * from numpy import array, arange, around, pi, sin, cos -set_package_path() -from spline.spline import UnivariateSpline,LSQUnivariateSpline,\ - InterpolatedUnivariateSpline -from spline.spline import LSQBivariateSpline, SmoothBivariateSpline,\ + +from scipy.sandbox.spline.spline import UnivariateSpline,LSQUnivariateSpline,\ + InterpolatedUnivariateSpline, LSQBivariateSpline, SmoothBivariateSpline,\ RectBivariateSpline -restore_path() set_local_path() from dierckx_test_data import * restore_path() -class TestUnivariateSpline(NumpyTestCase): - def check_linear_constant(self): +class TestUnivariateSpline(TestCase): + def test_linear_constant(self): x = [1,2,3] y = [3,3,3] lut = UnivariateSpline(x,y,k=1) @@ -37,7 +35,7 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2]),[3,3,3]) - def check_linear_1d(self): + def test_linear_1d(self): x = [1,2,3] y = [0,2,4] lut = UnivariateSpline(x,y,k=1) @@ -46,7 +44,7 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2]),[0,1,2]) - def check_curfit_against_dierckx(self): + def test_curfit_against_dierckx(self): """ Test against results obtined from the pure fortran routines. Here we check simple spline creation and evaluation. @@ -70,7 +68,7 @@ assert_array_almost_equal(around(uspl(x),1), curfit_test_smth['sp'][i]) - def check_spint_spalde(self): + def test_spint_spalde(self): per = [0, 0, 0] N = [20, 20, 50] ia = [0, 0, 0.2*pi] @@ -92,7 +90,7 @@ assert_almost_equal(1, ddr/f1(dx,d), decimal=2) d=d+1 - def check_sproot(self): + def test_sproot(self): a=0 b=15 N=20 @@ -103,8 +101,8 @@ ex = array([0.0, pi, 2.0*pi, 3.0*pi, 4.0*pi]) assert_array_almost_equal(uspl.roots(),ex, decimal=3) -class TestLSQUnivariateSpline(NumpyTestCase): - def check_curfit_against_dierckx(self): +class TestLSQUnivariateSpline(TestCase): + def test_curfit_against_dierckx(self): """ Test against results obtined from the pure fortran routines. Here we check simple spline creation and evaluation. @@ -121,8 +119,8 @@ assert_array_almost_equal(around(lsquspl(x),1), curfit_test_lsq['sp'][i]) -class TestLSQBivariateSpline(NumpyTestCase): - def check_linear_constant(self): +class TestLSQBivariateSpline(TestCase): + def test_linear_constant(self): x = [1,1,1,2,2,2,3,3,3] y = [1,2,3,1,2,3,1,2,3] z = [3,3,3,3,3,3,3,3,3] @@ -134,8 +132,8 @@ #print lut.get_coeffs() #print lut.get_residual() -class TestSmoothBivariateSpline(NumpyTestCase): - def check_linear_constant(self): +class TestSmoothBivariateSpline(TestCase): + def test_linear_constant(self): x = [1,1,1,2,2,2,3,3,3] y = [1,2,3,1,2,3,1,2,3] z = [3,3,3,3,3,3,3,3,3] @@ -145,7 +143,7 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[3,3],[3,3],[3,3]]) - def check_linear_1d(self): + def test_linear_1d(self): x = [1,1,1,2,2,2,3,3,3] y = [1,2,3,1,2,3,1,2,3] z = [0,0,0,2,2,2,4,4,4] @@ -155,8 +153,8 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[0,0],[1,1],[2,2]]) -class TestRectBivariateSpline(NumpyTestCase): - def check_defaults(self): +class TestRectBivariateSpline(TestCase): + def test_defaults(self): x = array([1,2,3,4,5]) y = array([1,2,3,4,5]) z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) @@ -164,4 +162,4 @@ assert_array_almost_equal(lut(x,y),z) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/timeseries/dates.py =================================================================== --- trunk/scipy/sandbox/timeseries/dates.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/dates.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -25,7 +25,7 @@ import numpy.core.numerictypes as ntypes from numpy.core.numerictypes import generic -import maskedarray as MA +import scipy.sandbox.maskedarray as MA from parser import DateFromString, DateTimeFromString Modified: trunk/scipy/sandbox/timeseries/extras.py =================================================================== --- trunk/scipy/sandbox/timeseries/extras.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/extras.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -12,8 +12,8 @@ import numpy -import maskedarray -from maskedarray import masked +import scipy.sandbox.maskedarray +from scipy.sandbox.maskedarray import masked import const as _c from tseries import TimeSeries Modified: trunk/scipy/sandbox/timeseries/lib/filters.py =================================================================== --- trunk/scipy/sandbox/timeseries/lib/filters.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/lib/filters.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -17,8 +17,8 @@ from scipy.signal import convolve, get_window -import maskedarray as MA -from maskedarray import MaskedArray, nomask, getmask, getmaskarray, masked +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray import MaskedArray, nomask, getmask, getmaskarray, masked marray = MA.array from moving_funcs import mov_average_expw, cmov_average, cmov_mean, \ Modified: trunk/scipy/sandbox/timeseries/lib/interpolate.py =================================================================== --- trunk/scipy/sandbox/timeseries/lib/interpolate.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/lib/interpolate.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -14,9 +14,9 @@ from scipy.interpolate import fitpack -import maskedarray as MA -from maskedarray.core import masked, nomask, getmask -from maskedarray.extras import flatnotmasked_edges +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray.core import masked, nomask, getmask +from scipy.sandbox.maskedarray.extras import flatnotmasked_edges marray = MA.array __all__ = [ Modified: trunk/scipy/sandbox/timeseries/lib/moving_funcs.py =================================================================== --- trunk/scipy/sandbox/timeseries/lib/moving_funcs.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/lib/moving_funcs.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -23,11 +23,11 @@ from scipy.signal import convolve, get_window -import maskedarray as MA -from maskedarray import MaskedArray, nomask, getmask, getmaskarray, masked +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray import MaskedArray, nomask, getmask, getmaskarray, masked marray = MA.array -from timeseries.cseries import MA_mov_sum, MA_mov_median, MA_mov_min, \ +from scipy.sandbox.timeseries.cseries import MA_mov_sum, MA_mov_median, MA_mov_min, \ MA_mov_max def _process_result_dict(orig_data, result_dict): Modified: trunk/scipy/sandbox/timeseries/lib/tests/test_interpolate.py =================================================================== --- trunk/scipy/sandbox/timeseries/lib/tests/test_interpolate.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/lib/tests/test_interpolate.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -11,20 +11,20 @@ import numpy as N import numpy.core.numeric as numeric -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import * +from scipy.sandbox.maskedarray.testutils import * -import maskedarray.core as coremodule -from maskedarray.core import MaskedArray, masked +import scipy.sandbox.maskedarray.core as coremodule +from scipy.sandbox.maskedarray.core import MaskedArray, masked -from timeseries.lib.interpolate import backward_fill, forward_fill, interp_masked1d +from scipy.sandbox.timeseries.lib.interpolate import \ + backward_fill, forward_fill, interp_masked1d -class TestFuncs(NumpyTestCase): +class TestFuncs(TestCase): def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.mask = [1,0,1,0,0,1,1,0,0,0] self.data = numeric.arange(10) self.test_array = masked_array(self.data, mask=self.mask) @@ -61,4 +61,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py =================================================================== --- trunk/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -13,25 +13,24 @@ import numpy as N import numpy.core.numeric as numeric -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import * +from scipy.sandbox.maskedarray.testutils import * -import maskedarray as MA -import maskedarray.core as coremodule -from maskedarray.core import MaskedArray, masked -from maskedarray import mstats +import scipy.sandbox.maskedarray as MA +import scipy.sandbox.maskedarray.core as coremodule +from scipy.sandbox.maskedarray.core import MaskedArray, masked +from scipy.sandbox.maskedarray import mstats -import timeseries as TS -from timeseries import time_series, thisday +import scipy.sandbox.timeseries as TS +from scipy.sandbox.timeseries import time_series, thisday -from timeseries.lib import moving_funcs as MF +from scipy.sandbox.timeseries.lib import moving_funcs as MF -class TestCMovAverage(NumpyTestCase): +class TestCMovAverage(TestCase): def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.data = numeric.arange(25) self.maskeddata = MaskedArray(self.data) self.maskeddata[10] = masked @@ -84,10 +83,10 @@ -class TestMovFuncs(NumpyTestCase): +class TestMovFuncs(TestCase): def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.data = numeric.arange(25) self.maskeddata = MaskedArray(self.data) self.maskeddata[10] = masked @@ -150,4 +149,4 @@ #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/timeseries/report.py =================================================================== --- trunk/scipy/sandbox/timeseries/report.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/report.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -59,8 +59,8 @@ import sys import operator, types, copy -import timeseries as ts -import maskedarray as ma +import tseries as ts +import scipy.sandbox.maskedarray as ma __all__ = [ 'Report', 'wrap_onspace', 'wrap_onspace_strict', Modified: trunk/scipy/sandbox/timeseries/tests/test_dates.py =================================================================== --- trunk/scipy/sandbox/timeseries/tests/test_dates.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/tests/test_dates.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -16,28 +16,24 @@ import numpy import numpy.core.fromnumeric as fromnumeric import numpy.core.numeric as numeric -from numpy.testing import NumpyTest, NumpyTestCase -from numpy.testing.utils import build_err_msg +from scipy.testing import * -import maskedarray -from maskedarray import masked_array +from scipy.sandbox.maskedarray import masked_array -import maskedarray.testutils -from maskedarray.testutils import assert_equal, assert_array_equal +from scipy.sandbox.maskedarray.testutils import assert_equal, assert_array_equal -import timeseries as ts -from timeseries import const as C -from timeseries.parser import DateFromString, DateTimeFromString -from timeseries import Date, DateArray,\ +import scipy.sandbox.timeseries as ts +from scipy.sandbox.timeseries import const as C, Date, DateArray,\ now, date_array, date_array_fromlist -from timeseries.cseries import freq_dict +from scipy.sandbox.timeseries.parser import DateFromString, DateTimeFromString +from scipy.sandbox.timeseries.cseries import freq_dict -class TestCreation(NumpyTestCase): +class TestCreation(TestCase): "Base test class for MaskedArrays." def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) def test_fromstrings(self): "Tests creation from list of strings" @@ -140,11 +136,11 @@ assert_equal(date_array(n, n+2), d) print "finished test_shortcuts" -class TestDateProperties(NumpyTestCase): +class TestDateProperties(TestCase): "Test properties such as year, month, weekday, etc...." def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) def test_properties(self): @@ -245,11 +241,11 @@ def noWrap(item): return item -class TestFreqConversion(NumpyTestCase): +class TestFreqConversion(TestCase): "Test frequency conversion of date objects" def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.dateWrap = [(dArrayWrap, assert_array_equal), (noWrap, assert_equal)] @@ -833,11 +829,11 @@ assert_func(date_S_end_of_minute.asfreq('T'), date_S_to_T) -class TestMethods(NumpyTestCase): +class TestMethods(TestCase): "Base test class for MaskedArrays." def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) def test_getitem(self): "Tests getitem" @@ -886,4 +882,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/timeseries/tests/test_extras.py =================================================================== --- trunk/scipy/sandbox/timeseries/tests/test_extras.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/tests/test_extras.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -13,30 +13,29 @@ import numpy -from numpy.testing import NumpyTest, NumpyTestCase -import maskedarray -from maskedarray import masked -from maskedarray.testutils import assert_equal, assert_almost_equal +from scipy.testing import * +import scipy.sandbox.maskedarray +from scipy.sandbox.maskedarray import masked +from scipy.sandbox.maskedarray.testutils import assert_equal, assert_almost_equal -from timeseries import time_series, Date -from timeseries import extras -from timeseries.extras import * +from scipy.sandbox.timeseries import time_series, Date, extras +from scipy.sandbox.timeseries.extras import * #.............................................................................. -class TestMisc(NumpyTestCase): +class TestMisc(TestCase): "Base test class for MaskedArrays." def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) # def test_leapyear(self): leap = isleapyear([1900,1901,1902,1903,1904,2000,2001,2002,2003,2004]) assert_equal(leap, [0,0,0,0,1,1,0,0,0,1]) #.............................................................................. -class TestCountmissing(NumpyTestCase): +class TestCountmissing(TestCase): # def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) data = time_series(numpy.arange(731), start_date=Date(string='2003-01-01', freq='D'), freq='D') @@ -81,4 +80,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/timeseries/tests/test_timeseries.py =================================================================== --- trunk/scipy/sandbox/timeseries/tests/test_timeseries.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/tests/test_timeseries.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -15,26 +15,23 @@ from numpy import bool_, complex_, float_, int_, object_ import numpy.core.fromnumeric as fromnumeric import numpy.core.numeric as numeric -from numpy.testing import NumpyTest, NumpyTestCase -from numpy.testing.utils import build_err_msg +from scipy.testing import * -import maskedarray -import maskedarray as MA -from maskedarray import masked_array, masked, nomask +import scipy.sandbox.maskedarray +import scipy.sandbox.maskedarray as MA +from scipy.sandbox.maskedarray import masked_array, masked, nomask -import maskedarray.testutils -from maskedarray.testutils import assert_equal, assert_array_equal +from scipy.sandbox.maskedarray.testutils import assert_equal, assert_array_equal -from timeseries import tseries -from timeseries import Date, date_array_fromlist, date_array_fromrange, date_array, thisday -from timeseries import time_series, TimeSeries, adjust_endpoints, \ - mask_period, align_series, align_with, fill_missing_dates, tsmasked, \ - concatenate, stack, split +from scipy.sandbox.timeseries import tseries, Date, date_array_fromlist, \ + date_array_fromrange, date_array, thisday, time_series, TimeSeries, \ + adjust_endpoints, mask_period, align_series, align_with, \ + fill_missing_dates, tsmasked, concatenate, stack, split -class TestCreation(NumpyTestCase): +class TestCreation(TestCase): "Base test class for MaskedArrays." def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) dlist = ['2007-01-%02i' % i for i in range(1,16)] dates = date_array_fromlist(dlist) data = masked_array(numeric.arange(15), mask=[1,0,0,0,0]*3) @@ -117,10 +114,10 @@ assert_equal(series._mask,[0,0,1]) #............................................................................... -class TestArithmetics(NumpyTestCase): +class TestArithmetics(TestCase): "Some basic arithmetic tests" def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) dlist = ['2007-01-%02i' % i for i in range(1,16)] dates = date_array_fromlist(dlist) data = masked_array(numeric.arange(15), mask=[1,0,0,0,0]*3) @@ -215,10 +212,10 @@ #............................................................................... -class TestGetitem(NumpyTestCase): +class TestGetitem(TestCase): "Some getitem tests" def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) dlist = ['2007-01-%02i' % i for i in range(1,16)] dates = date_array_fromlist(dlist) data = masked_array(numeric.arange(15), mask=[1,0,0,0,0]*3, dtype=float_) @@ -320,10 +317,10 @@ assert_equal(series[:,:,0], series._data[:,:,0]) assert_equal(series[:,:,0]._dates, series._dates) -class TestFunctions(NumpyTestCase): +class TestFunctions(TestCase): "Some getitem tests" def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) dlist = ['2007-01-%02i' % i for i in range(1,16)] dates = date_array_fromlist(dlist) data = masked_array(numeric.arange(15), mask=[1,0,0,0,0]*3) @@ -635,4 +632,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/timeseries/tests/test_trecords.py =================================================================== --- trunk/scipy/sandbox/timeseries/tests/test_trecords.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/tests/test_trecords.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -14,29 +14,27 @@ import numpy import numpy.core.fromnumeric as fromnumeric -from numpy.testing import NumpyTest, NumpyTestCase -from numpy.testing.utils import build_err_msg +from scipy.testing import * -import maskedarray.testutils -from maskedarray.testutils import assert_equal, assert_array_equal, assert_equal_records +from scipy.sandbox.maskedarray.testutils import assert_equal, assert_array_equal, assert_equal_records -import maskedarray.core as MA -import maskedarray.mrecords as MR -from maskedarray.mrecords import addfield +import scipy.sandbox.maskedarray.core as MA +import scipy.sandbox.maskedarray.mrecords as MR +from scipy.sandbox.maskedarray.mrecords import addfield -from maskedarray.core import getmaskarray, nomask, masked_array +from scipy.sandbox.maskedarray.core import getmaskarray, nomask, masked_array -from timeseries import trecords -from timeseries.trecords import TimeSeriesRecords, TimeSeries,\ +from scipy.sandbox.timeseries.trecords import \ + TimeSeriesRecords, TimeSeries,\ fromarrays, fromtextfile, fromrecords, \ date_array, time_series #.............................................................................. -class TestMRecords(NumpyTestCase): +class TestMRecords(TestCase): "Base test class for MaskedArrays." def __init__(self, *args, **kwds): - NumpyTestCase.__init__(self, *args, **kwds) + TestCase.__init__(self, *args, **kwds) self.setup() def setup(self): @@ -186,4 +184,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sandbox/timeseries/trecords.py =================================================================== --- trunk/scipy/sandbox/timeseries/trecords.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/trecords.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -26,17 +26,17 @@ from numpy.core.records import format_parser, recarray, record from numpy.core.records import fromarrays as recfromarrays -import maskedarray as MA +import scipy.sandbox.maskedarray as MA #MaskedArray = MA.MaskedArray -from maskedarray.core import MaskedArray, MAError, default_fill_value, \ - masked_print_option -from maskedarray.core import masked, nomask, getmask, getmaskarray, make_mask,\ +from scipy.sandbox.maskedarray.core import MaskedArray, MAError, \ + default_fill_value, masked_print_option, masked, nomask, \ + getmask, getmaskarray, make_mask,\ make_mask_none, mask_or, masked_array, filled -import maskedarray.mrecords as MR -from maskedarray.mrecords import _checknames, _guessvartypes, openfile,\ - MaskedRecords -from maskedarray.mrecords import fromrecords as mrecfromrecords +import scipy.sandbox.maskedarray.mrecords as MR +from scipy.sandbox.maskedarray.mrecords import _checknames, \ + _guessvartypes, openfile, MaskedRecords, \ + fromrecords as mrecfromrecords from tseries import TimeSeries, time_series, _getdatalength from dates import Date, DateArray, date_array Modified: trunk/scipy/sandbox/timeseries/tseries.py =================================================================== --- trunk/scipy/sandbox/timeseries/tseries.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sandbox/timeseries/tseries.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -25,8 +25,8 @@ from numpy.core.records import recarray from numpy.core.records import fromarrays as recfromarrays -import maskedarray -from maskedarray import MaskedArray, MAError, masked, nomask, \ +import scipy.sandbox.maskedarray as maskedarray +from scipy.sandbox.maskedarray import MaskedArray, MAError, masked, nomask, \ filled, getmask, getmaskarray, hsplit, make_mask_none, mask_or, make_mask, \ masked_array Modified: trunk/scipy/setup.py =================================================================== --- trunk/scipy/setup.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/setup.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -22,6 +22,7 @@ config.add_subpackage('ndimage') config.add_subpackage('stsci') config.add_subpackage('weave') + config.add_subpackage('testing') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config Modified: trunk/scipy/signal/__init__.py =================================================================== --- trunk/scipy/signal/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/signal/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -13,5 +13,5 @@ from wavelets import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,34 +1,34 @@ #this program corresponds to special.py -from numpy.testing import * -set_package_path() +from scipy.testing import * + import scipy.signal as signal -restore_path() + from numpy import array, arange -class TestConvolve(NumpyTestCase): - def check_basic(self): +class TestConvolve(TestCase): + def test_basic(self): a = [3,4,5,6,5,4] b = [1,2,3] c = signal.convolve(a,b) assert_array_equal(c,array([3,10,22,28,32,32,23,12])) -class TestMedFilt(NumpyTestCase): - def check_basic(self): +class TestMedFilt(TestCase): + def test_basic(self): f = [[3,4,5],[2,3,4],[1,2,5]] d = signal.medfilt(f) assert_array_equal(d, [[0,3,0],[2,3,3],[0,2,0]]) -class TestWiener(NumpyTestCase): - def check_basic(self): +class TestWiener(TestCase): + def test_basic(self): g = array([[5,6,4,3],[3,5,6,2],[2,3,5,6],[1,6,9,7]],'d') correct = array([[2.16374269,3.2222222222, 2.8888888889, 1.6666666667],[2.666666667, 4.33333333333, 4.44444444444, 2.8888888888],[2.222222222, 4.4444444444, 5.4444444444, 4.801066874837],[1.33333333333, 3.92735042735, 6.0712560386, 5.0404040404]]) h = signal.wiener(g) assert_array_almost_equal(h,correct,decimal=6) -class TestCSpline1DEval(NumpyTestCase): - def check_basic(self): +class TestCSpline1DEval(TestCase): + def test_basic(self): y=array([1,2,3,4,3,2,1,2,3.0]) x=arange(len(y)) dx=x[1]-x[0] @@ -40,10 +40,10 @@ # make sure interpolated values are on knot points assert_array_almost_equal(y2[::10], y, decimal=5) -class TestOrderFilt(NumpyTestCase): - def check_basic(self): +class TestOrderFilt(TestCase): + def test_basic(self): assert_array_equal(signal.order_filter([1,2,3],[1,0,1],1), [2,3,2]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/signal/tests/test_wavelets.py =================================================================== --- trunk/scipy/signal/tests/test_wavelets.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/signal/tests/test_wavelets.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,19 +1,18 @@ import numpy as N -from numpy.testing import * +from scipy.testing import * -set_package_path() from scipy.signal import wavelets -restore_path() -class TestWavelets(NumpyTestCase): - def check_qmf(self): + +class TestWavelets(TestCase): + def test_qmf(self): assert_array_equal(wavelets.qmf([1,1]),[1,-1]) - def check_daub(self): + def test_daub(self): for i in xrange(1,15): assert_equal(len(wavelets.daub(i)),i*2) - def check_cascade(self): + def test_cascade(self): for J in xrange(1,7): for i in xrange(1,5): lpcoef = wavelets.daub(i) @@ -22,7 +21,7 @@ assert len(x) == len(phi) == len(psi) assert_equal(len(x),(k-1)*2**J) - def check_morlet(self): + def test_morlet(self): x = wavelets.morlet(50,4.1,complete=True) y = wavelets.morlet(50,4.1,complete=False) assert_equal(len(x),len(y)) @@ -32,4 +31,4 @@ assert_equal(x,y) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sparse/__init__.py =================================================================== --- trunk/scipy/sparse/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sparse/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -15,5 +15,5 @@ from spfuncs import * __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sparse/tests/test_base.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -8,9 +8,9 @@ Build sparse: python setup.py build Run tests if scipy is installed: - python -c 'import scipy;scipy.sparse.test()' + python -c 'import scipy;scipy.sparse.test()' Run tests if sparse is not installed: - python tests/test_sparse.py [] + python tests/test_sparse.py """ import numpy @@ -18,16 +18,16 @@ asarray, vstack, ndarray, kron, transpose import random -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ coo_matrix, lil_matrix, dia_matrix, bsr_matrix, \ extract_diagonal, speye, spkron, SparseEfficiencyWarning from scipy.sparse.sputils import supported_dtypes from scipy.linsolve import splu -restore_path() + #TODO test spmatrix( [[1,2],[3,4]] ) format #TODO check that invalid shape in constructor raises exception #TODO check that spmatrix( ... , copy=X ) is respected @@ -41,11 +41,11 @@ self.dat = matrix([[1,0,0,2],[3,0,1,0],[0,2,0,0]],'d') self.datsp = self.spmatrix(self.dat) - def check_repr(self): + def test_repr(self): """make sure __repr__ works""" repr(self.spmatrix) - def check_empty(self): + def test_empty(self): """Test manipulating empty matrices. Fails in SciPy SVN <= r1768 """ shape = (5, 5) @@ -62,15 +62,15 @@ assert_equal(m.dtype,mytype) assert_equal(m.A.dtype,mytype) - def check_abs(self): + def test_abs(self): A = matrix([[-1, 0, 17],[0, -5, 0],[1, -4, 0],[0,0,0]],'d') assert_equal(abs(A),abs(self.spmatrix(A)).todense()) - def check_neg(self): + def test_neg(self): A = matrix([[-1, 0, 17],[0, -5, 0],[1, -4, 0],[0,0,0]],'d') assert_equal(-A,(-self.spmatrix(A)).todense()) - def check_sum(self): + def test_sum(self): """Does the matrix's sum(,axis=0) method work? """ assert_array_equal(self.dat.sum(), self.datsp.sum()) @@ -78,7 +78,7 @@ assert_array_equal(self.dat.sum(axis=0), self.datsp.sum(axis=0)) assert_array_equal(self.dat.sum(axis=1), self.datsp.sum(axis=1)) - def check_mean(self): + def test_mean(self): """Does the matrix's mean(,axis=0) method work? """ assert_array_equal(self.dat.mean(), self.datsp.mean()) @@ -86,13 +86,13 @@ assert_array_equal(self.dat.mean(axis=0), self.datsp.mean(axis=0)) assert_array_equal(self.dat.mean(axis=1), self.datsp.mean(axis=1)) - def check_fromdense(self): + def test_fromdense(self): A = matrix([[1,0,0],[2,3,4],[0,5,0],[0,0,0]]) assert_array_equal(self.spmatrix(A).todense(),A) assert_array_equal(self.spmatrix(A.A).todense(),A) assert_array_equal(self.spmatrix(A.tolist()).todense(),A) - def check_todense(self): + def test_todense(self): chk = self.datsp.todense() assert_array_equal(chk,self.dat) a = matrix([1.,2.,3.]) @@ -104,7 +104,7 @@ check2 = self.datsp.todense() * b assert_array_equal(dense_dot_dense, check2) - def check_toarray(self): + def test_toarray(self): dat = asarray(self.dat) chk = self.datsp.toarray() assert_array_equal(chk, dat) @@ -118,36 +118,36 @@ assert_array_equal(dense_dot_dense, check2) - def check_mul_scalar(self): + def test_mul_scalar(self): assert_array_equal(self.dat*2,(self.datsp*2).todense()) assert_array_equal(self.dat*17.3,(self.datsp*17.3).todense()) - def check_rmul_scalar(self): + def test_rmul_scalar(self): assert_array_equal(2*self.dat,(2*self.datsp).todense()) assert_array_equal(17.3*self.dat,(17.3*self.datsp).todense()) - def check_add(self): + def test_add(self): a = self.dat.copy() a[0,2] = 2.0 b = self.datsp c = b + a assert_array_equal(c,[[2,0,2,4],[6,0,2,0],[0,4,0,0]]) - def check_radd(self): + def test_radd(self): a = self.dat.copy() a[0,2] = 2.0 b = self.datsp c = a + b assert_array_equal(c,[[2,0,2,4],[6,0,2,0],[0,4,0,0]]) - def check_sub(self): + def test_sub(self): assert_array_equal((self.datsp - self.datsp).todense(),[[0,0,0,0],[0,0,0,0],[0,0,0,0]]) A = self.spmatrix(matrix([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],'d')) assert_array_equal((self.datsp - A).todense(),self.dat - A.todense()) assert_array_equal((A - self.datsp).todense(),A.todense() - self.dat) - def check_rsub(self): + def test_rsub(self): assert_array_equal((self.dat - self.datsp),[[0,0,0,0],[0,0,0,0],[0,0,0,0]]) assert_array_equal((self.datsp - self.dat),[[0,0,0,0],[0,0,0,0],[0,0,0,0]]) @@ -157,14 +157,14 @@ assert_array_equal(A.todense() - self.datsp,A.todense() - self.dat) assert_array_equal(self.datsp - A.todense(),self.dat - A.todense()) - def check_elmul(self): + def test_elmul(self): temp = self.dat.copy() temp[0,2] = 2.0 temp = self.spmatrix(temp) c = temp.multiply(self.datsp) assert_array_equal(c.todense(),[[1,0,0,4],[9,0,1,0],[0,4,0,0]]) - def check_eldiv(self): + def test_eldiv(self): expected = [[1,0,0,1],[1,0,1,0],[0,1,0,0]] assert_array_equal((self.datsp / self.datsp).todense(),expected) @@ -172,7 +172,7 @@ res = matrix([[1,0,0,0.5],[-3,0,numpy.inf,0],[0,0.25,0,0]],'d') assert_array_equal((self.datsp / denom).todense(),res) - def check_pow(self): + def test_pow(self): A = matrix([[1,0,2,0],[0,3,4,0],[0,5,0,0],[0,6,7,8]]) B = self.spmatrix( A ) @@ -188,13 +188,13 @@ self.assertRaises( Exception, B.__pow__, 1 ) - def check_rmatvec(self): + def test_rmatvec(self): M = self.spmatrix(matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])) assert_array_almost_equal([1,2,3,4]*M, dot([1,2,3,4], M.toarray())) row = matrix([[1,2,3,4]]) assert_array_almost_equal(row*M, row*M.todense()) - def check_matvec(self): + def test_matvec(self): M = self.spmatrix(matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])) col = matrix([1,2,3]).T assert_array_almost_equal(M * col, M.todense() * col) @@ -240,7 +240,7 @@ # Currently M.matvec(asarray(col)) is rank-1, whereas M.matvec(col) # is rank-2. Is this desirable? - def check_matmat_sparse(self): + def test_matmat_sparse(self): a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) a2 = array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) b = matrix([[0,1],[1,0],[0,2]],'d') @@ -291,7 +291,7 @@ assert_array_almost_equal(B.todense(), A.todense() * A.T.todense()) assert_array_almost_equal(B.todense(), A.todense() * A.todense().T) - def check_matmat_dense(self): + def test_matmat_dense(self): a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) asp = self.spmatrix(a) @@ -304,7 +304,7 @@ assert_equal( result.shape, (4,2) ) assert_equal( result, dot(a,b) ) - def check_formatconversions(self): + def test_formatconversions(self): A = spkron([[1,0,1],[0,1,1],[1,0,0]], [[1,1],[0,1]] ) D = A.todense() A = self.spmatrix(A) @@ -324,11 +324,11 @@ - def check_todia(self): + def test_todia(self): #TODO, add and test .todia(maxdiags) pass - def check_tocompressedblock(self): + def test_tocompressedblock(self): x = array([[1,0,2,0],[0,0,0,0],[0,0,4,5]]) y = array([[0,1,2],[3,0,5]]) A = kron(x,y) @@ -341,7 +341,7 @@ assert_equal( fn(blocksize=(X,Y)).todense(), A) - def check_transpose(self): + def test_transpose(self): a = self.datsp.transpose() b = self.dat.transpose() assert_array_equal(a.todense(), b) @@ -350,7 +350,7 @@ assert_array_equal( self.spmatrix((3,4)).T.todense(), zeros((4,3)) ) - def check_add_dense(self): + def test_add_dense(self): """ Check whether adding a dense matrix to a sparse matrix works """ sum1 = self.dat + self.datsp @@ -358,7 +358,7 @@ sum2 = self.datsp + self.dat assert_array_equal(sum2, 2*self.dat) - def check_sub_dense(self): + def test_sub_dense(self): """ Check whether adding a dense matrix to a sparse matrix works """ sum1 = 3*self.dat - self.datsp @@ -367,7 +367,7 @@ assert_array_equal(sum2, 2*self.dat) - def check_copy(self): + def test_copy(self): """ Check whether the copy=True and copy=False keywords work """ A = self.datsp @@ -397,20 +397,20 @@ # Eventually we'd like to allow matrix products between dense # and sparse matrices using the normal dot() function: - #def check_dense_dot_sparse(self): + #def test_dense_dot_sparse(self): # a = array([1.,2.,3.]) # dense_dot_dense = dot(a, self.dat) # dense_dot_sparse = dot(a, self.datsp) # assert_array_equal(dense_dot_dense, dense_dot_sparse) - #def check_sparse_dot_dense(self): + #def test_sparse_dot_dense(self): # b = array([1.,2.,3.,4.]) # dense_dot_dense = dot(self.dat, b) # dense_dot_sparse = dot(self.datsp, b) # assert_array_equal(dense_dot_dense, dense_dot_sparse) - def check_extract_diagonal(self): + def test_extract_diagonal(self): """ Test extraction of main diagonal from sparse matrices """ @@ -425,7 +425,7 @@ class _TestInplaceArithmetic: - def check_imul_scalar(self): + def test_imul_scalar(self): a = self.datsp.copy() a *= 2 assert_array_equal(self.dat*2,a.todense()) @@ -434,7 +434,7 @@ a *= 17.3 assert_array_equal(self.dat*17.3,a.todense()) - def check_idiv_scalar(self): + def test_idiv_scalar(self): a = self.datsp.copy() a /= 2 assert_array_equal(self.dat/2,a.todense()) @@ -446,7 +446,7 @@ class _TestMatvecOutput: """test using the matvec() output parameter""" - def check_matvec_output(self): + def test_matvec_output(self): #flat array x = array([1.25, -6.5, 0.125, -3.75],dtype='d') y = zeros(3,dtype='d') @@ -484,7 +484,7 @@ assert_equal((self.datsp*x).dtype,y.dtype) class _TestGetSet: - def check_setelement(self): + def test_setelement(self): import warnings warnings.simplefilter('ignore',SparseEfficiencyWarning) a = self.spmatrix((3,4)) @@ -495,14 +495,14 @@ a[-1,-2] = 7 assert_array_equal(a.todense(),[[0,3,0,8],[0,0,4,0],[2,0,7,0]]) - def check_getelement(self): + def test_getelement(self): assert_equal(self.datsp[0,0],1) assert_equal(self.datsp[0,1],0) assert_equal(self.datsp[1,0],3) assert_equal(self.datsp[2,1],2) class _TestSolve: - def check_solve(self): + def test_solve(self): """ Test whether the lu_solve command segfaults, as reported by Nils Wagner for a 64-bit machine, 02 March 2005 (EJS) """ @@ -526,7 +526,7 @@ """Tests horizontal slicing (e.g. [0, :]). Tests for individual sparse matrix types that implement this should derive from this class. """ - def check_get_horiz_slice(self): + def test_get_horiz_slice(self): """Test for new slice functionality (EJS)""" B = asmatrix(arange(50.).reshape(5,10)) A = self.spmatrix(B) @@ -560,7 +560,7 @@ """Tests vertical slicing (e.g. [:, 0]). Tests for individual sparse matrix types that implement this should derive from this class. """ - def check_get_vert_slice(self): + def test_get_vert_slice(self): """Test for new slice functionality (EJS)""" B = asmatrix(arange(50.).reshape(5,10)) A = self.spmatrix(B) @@ -597,7 +597,7 @@ individual sparse matrix types that implement this should derive from this class. """ - def check_get_slices(self): + def test_get_slices(self): B = asmatrix(arange(50.).reshape(5,10)) A = self.spmatrix(B) assert_array_equal(B[2:5,0:3], A[2:5,0:3].todense()) @@ -615,13 +615,13 @@ that implement these features should derive from this class. """ # This isn't supported by any matrix objects yet: - def check_sequence_indexing(self): + def test_sequence_indexing(self): B = asmatrix(arange(50.).reshape(5,10)) A = self.spmatrix(B) assert_array_equal(B[(1,2),(3,4)], A[(1,2),(3,4)].todense()) assert_array_equal(B[(1,2,3),(3,4,5)], A[(1,2,3),(3,4,5)].todense()) - def check_fancy_indexing(self): + def test_fancy_indexing(self): """Test for new indexing functionality""" B = ones((5,10), float) A = dok_matrix(B) @@ -659,7 +659,7 @@ self.Asp = self.spmatrix(self.A) self.Bsp = self.spmatrix(self.B) - def check_astype(self): + def test_astype(self): self.arith_init() #check whether dtype and value is preserved in conversion @@ -674,7 +674,7 @@ assert_array_equal(Asp.todense(),A) assert_array_equal(Bsp.todense(),B) - def check_add_sub(self): + def test_add_sub(self): self.arith_init() #basic tests @@ -707,7 +707,7 @@ assert_array_equal(A - Bsp,D1) #check dense - sparse - def check_mu(self): + def test_mu(self): self.arith_init() #basic tests @@ -731,10 +731,10 @@ class TestCSR(_TestCommon, _TestGetSet, _TestSolve, _TestInplaceArithmetic, _TestArithmetic, _TestMatvecOutput, _TestHorizSlicing, _TestVertSlicing, _TestBothSlicing, - NumpyTestCase): + TestCase): spmatrix = csr_matrix - def check_constructor1(self): + def test_constructor1(self): b = matrix([[0,4,0], [3,0,0], [0,2,0]],'d') @@ -746,7 +746,7 @@ assert_equal(bsp.getformat(),'csr') assert_array_equal(bsp.todense(),b) - def check_constructor2(self): + def test_constructor2(self): b = zeros((6,6),'d') b[3,4] = 5 bsp = csr_matrix(b) @@ -755,7 +755,7 @@ assert_array_equal(bsp.indptr,[0,0,0,0,1,1,1]) assert_array_almost_equal(bsp.todense(),b) - def check_constructor3(self): + def test_constructor3(self): b = matrix([[1,0], [0,2], [3,0]],'d') @@ -766,7 +766,7 @@ assert_array_almost_equal(bsp.todense(),b) ### currently disabled -## def check_constructor4(self): +## def test_constructor4(self): ## """try using int64 indices""" ## data = arange( 6 ) + 1 ## col = array( [1, 2, 1, 0, 0, 2], dtype='int64' ) @@ -782,7 +782,7 @@ ## assert_equal(a.indices.dtype,numpy.dtype('int64')) ## assert_array_equal(a.todense(),b) - def check_constructor4(self): + def test_constructor4(self): """using (data, ij) format""" row = numpy.array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) col = numpy.array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) @@ -793,7 +793,7 @@ csr = csr_matrix((data,ij),(4,3)) assert_array_equal(arange(12).reshape(4,3),csr.todense()) - def check_constructor5(self): + def test_constructor5(self): """infer dimensions from arrays""" indptr = array([0,1,3,3]) indices = array([0,5,1,2]) @@ -802,7 +802,7 @@ assert_array_equal(csr.shape,(3,6)) - def check_sort_indices(self): + def test_sort_indices(self): data = arange( 5 ) indices = array( [7, 2, 1, 5, 4] ) indptr = array( [0, 3, 5] ) @@ -812,7 +812,7 @@ assert_array_equal(asp.indices,[1, 2, 7, 4, 5]) assert_array_equal(asp.todense(),bsp.todense()) - def check_eliminate_zeros(self): + def test_eliminate_zeros(self): data = array( [1, 0, 0, 0, 2, 0, 3, 0] ) indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) indptr = array( [0, 3, 8] ) @@ -823,7 +823,7 @@ assert_array_equal(asp.data,[1, 2, 3]) assert_array_equal(asp.todense(),bsp.todense()) - def check_get_submatrix(self): + def test_get_submatrix(self): a = csr_matrix( array([[1,2,3,4],[1,2,3,5],[0,2,0,1]]) ) i0 = slice( 0, 2 ) i1 = ( 1, 3 ) @@ -839,10 +839,10 @@ class TestCSC(_TestCommon, _TestGetSet, _TestSolve, _TestInplaceArithmetic, _TestArithmetic, _TestMatvecOutput, _TestHorizSlicing, _TestVertSlicing, _TestBothSlicing, - NumpyTestCase): + TestCase): spmatrix = csc_matrix - def check_constructor1(self): + def test_constructor1(self): b = matrix([[1,0,0,0],[0,0,1,0],[0,2,0,3]],'d') bsp = csc_matrix(b) assert_array_almost_equal(bsp.data,[1,2,1,3]) @@ -852,7 +852,7 @@ assert_equal(bsp.shape,b.shape) assert_equal(bsp.getformat(),'csc') - def check_constructor2(self): + def test_constructor2(self): b = zeros((6,6),'d') b[2,4] = 5 bsp = csc_matrix(b) @@ -860,14 +860,14 @@ assert_array_equal(bsp.indices,[2]) assert_array_equal(bsp.indptr,[0,0,0,0,0,1,1]) - def check_constructor3(self): + def test_constructor3(self): b = matrix([[1,0],[0,0],[0,2]],'d') bsp = csc_matrix(b) assert_array_almost_equal(bsp.data,[1,2]) assert_array_equal(bsp.indices,[0,2]) assert_array_equal(bsp.indptr,[0,1,2]) - def check_constructor4(self): + def test_constructor4(self): """using (data, ij) format""" row = numpy.array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) col = numpy.array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) @@ -878,7 +878,7 @@ csc = csc_matrix((data,ij),(4,3)) assert_array_equal(arange(12).reshape(4,3),csc.todense()) - def check_constructor5(self): + def test_constructor5(self): """infer dimensions from arrays""" indptr = array([0,1,3,3]) indices = array([0,5,1,2]) @@ -886,7 +886,7 @@ csc = csc_matrix((data, indices, indptr)) assert_array_equal(csc.shape,(6,3)) - def check_eliminate_zeros(self): + def test_eliminate_zeros(self): data = array( [1, 0, 0, 0, 2, 0, 3, 0] ) indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) indptr = array( [0, 3, 8] ) @@ -897,7 +897,7 @@ assert_array_equal(asp.data,[1, 2, 3]) assert_array_equal(asp.todense(),bsp.todense()) - def check_sort_indices(self): + def test_sort_indices(self): data = arange( 5 ) row = array( [7, 2, 1, 5, 4] ) ptr = [0, 3, 5] @@ -907,7 +907,7 @@ assert_array_equal(asp.indices,[1, 2, 7, 4, 5]) assert_array_equal(asp.todense(),bsp.todense()) - def check_get_submatrix(self): + def test_get_submatrix(self): a = csc_matrix( array([[1,2,3,4],[1,2,3,5],[0,2,0,1]]) ) i0 = slice( 0, 2 ) i1 = ( 1, 3 ) @@ -920,10 +920,10 @@ assert_equal(b.shape, (2,2)) assert_equal( ab, aa[i0,i1[0]:i1[1]] ) -class TestDOK(_TestCommon, _TestGetSet, _TestSolve, NumpyTestCase): +class TestDOK(_TestCommon, _TestGetSet, _TestSolve, TestCase): spmatrix = dok_matrix - def check_mult(self): + def test_mult(self): A = dok_matrix((10,10)) A[0,3] = 10 A[5,6] = 20 @@ -931,7 +931,7 @@ E = A*A.H assert_array_equal(D.A, E.A) - def check_add(self): + def test_add(self): A = dok_matrix((3,2)) A[0,1] = -10 A[2,0] = 20 @@ -939,7 +939,7 @@ B = matrix([[10, 0], [10, 10], [30, 10]]) assert_array_equal(A.todense(), B) - def check_convert(self): + def test_convert(self): """Test provided by Andrew Straw. Fails in SciPy <= r1477. """ (m, n) = (6, 7) @@ -971,7 +971,7 @@ csr=b.tocsr() assert_array_equal( csr.toarray()[m-1,:], zeros(n,)) - def check_set_slice(self): + def test_set_slice(self): """Test for slice functionality (EJS)""" A = dok_matrix((5,10)) B = zeros((5,10), float) @@ -1030,7 +1030,7 @@ class TestLIL( _TestCommon, _TestHorizSlicing, _TestVertSlicing, _TestBothSlicing, _TestGetSet, _TestSolve, _TestArithmetic, _TestInplaceArithmetic, - NumpyTestCase): + TestCase): spmatrix = lil_matrix B = lil_matrix((4,3)) @@ -1039,7 +1039,7 @@ B[2,1] = 3 B[3,0] = 10 - def check_dot(self): + def test_dot(self): A = matrix(zeros((10,10))) A[0,3] = 10 A[5,6] = 20 @@ -1050,7 +1050,7 @@ assert_array_equal(A * A.T, (B * B.T).todense()) assert_array_equal(A * A.H, (B * B.H).todense()) - def check_scalar_mul(self): + def test_scalar_mul(self): x = lil_matrix((3,3)) x[0,0] = 2 @@ -1060,7 +1060,7 @@ x = x*0 assert_equal(x[0,0],0) - def check_reshape(self): + def test_reshape(self): x = lil_matrix((4,3)) x[0,0] = 1 x[2,1] = 3 @@ -1071,7 +1071,7 @@ assert_array_equal(x.reshape(s).todense(), x.todense().reshape(s)) - def check_lil_lil_assignment(self): + def test_lil_lil_assignment(self): """ Tests whether a row of one lil_matrix can be assigned to another. """ @@ -1099,7 +1099,7 @@ return [(self.tst_inplace_op,op,B,other,result) for op,(other,result) in data.iteritems()] - def check_lil_slice_assignment(self): + def test_lil_slice_assignment(self): B = lil_matrix((4,3)) B[0,0] = 5 B[1,2] = 3 @@ -1117,7 +1117,7 @@ B[:2,:2] = csc_matrix(array(block)) assert_array_equal(B.todense()[:2,:2],block) - def check_lil_sequence_assignement(self): + def test_lil_sequence_assignement(self): A = lil_matrix((4,3)) B = speye(3,4,format='lil') @@ -1130,13 +1130,13 @@ A[2,i2] = B[i2,2] assert_array_equal(A.todense(),B.T.todense()) - def check_lil_iteration(self): + def test_lil_iteration(self): row_data = [[1,2,3],[4,5,6]] B = lil_matrix(array(row_data)) for r,row in enumerate(B): assert_array_equal(row.todense(),array(row_data[r],ndmin=2)) - def check_lil_from_csr(self): + def test_lil_from_csr(self): """ Tests whether a lil_matrix can be constructed from a csr_matrix. """ @@ -1150,7 +1150,7 @@ D = lil_matrix(C) assert_array_equal(C.A, D.A) - def check_point_wise_multiply(self): + def test_point_wise_multiply(self): l = lil_matrix((4,3)) l[0,0] = 1 l[1,1] = 2 @@ -1175,9 +1175,9 @@ -class TestCOO(_TestCommon, NumpyTestCase): +class TestCOO(_TestCommon, TestCase): spmatrix = coo_matrix - def check_constructor1(self): + def test_constructor1(self): """unsorted triplet format""" row = numpy.array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) col = numpy.array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) @@ -1188,7 +1188,7 @@ assert_array_equal(arange(12).reshape(4,3),coo.todense()) - def check_constructor2(self): + def test_constructor2(self): """unsorted triplet format with duplicates (which are summed)""" row = numpy.array([0,1,2,2,2,2,0,0,2,2]) col = numpy.array([0,2,0,2,1,1,1,0,0,2]) @@ -1199,7 +1199,7 @@ assert_array_equal(mat,coo.todense()) - def check_constructor3(self): + def test_constructor3(self): """empty matrix""" coo = coo_matrix( (4,3) ) @@ -1209,7 +1209,7 @@ assert_array_equal(coo.data,[]) assert_array_equal(coo.todense(),zeros((4,3))) - def check_constructor4(self): + def test_constructor4(self): """from dense matrix""" mat = numpy.array([[0,1,0,0], [7,0,3,0], @@ -1223,19 +1223,19 @@ assert_array_equal(coo.todense(),mat.reshape(1,-1)) -class TestDIA(_TestCommon, _TestArithmetic, NumpyTestCase): +class TestDIA(_TestCommon, _TestArithmetic, TestCase): spmatrix = dia_matrix - def check_constructor1(self): + def test_constructor1(self): pass #TODO add test class TestBSR(_TestCommon, _TestArithmetic, _TestInplaceArithmetic, - _TestMatvecOutput, NumpyTestCase): + _TestMatvecOutput, TestCase): spmatrix = bsr_matrix - def check_constructor1(self): + def test_constructor1(self): """check native BSR format constructor""" indptr = array([0,2,2,4]) indices = array([0,2,2,3]) @@ -1258,7 +1258,7 @@ Asp = bsr_matrix((data,indices,indptr)) assert_equal(Asp.todense(),A) - def check_constructor2(self): + def test_constructor2(self): """construct from dense""" #test zero mats @@ -1282,7 +1282,7 @@ A = kron( [[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]] ) assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A) - def check_eliminate_zeros(self): + def test_eliminate_zeros(self): data = kron([1, 0, 0, 0, 2, 0, 3, 0], [[1,1],[1,1]]).T data = data.reshape(-1,2,2) indices = array( [1, 2, 3, 4, 5, 6, 7, 8] ) @@ -1295,4 +1295,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sparse/tests/test_construct.py =================================================================== --- trunk/scipy/sparse/tests/test_construct.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sparse/tests/test_construct.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,18 +1,17 @@ """test sparse matrix construction functions""" from numpy import array, kron -from numpy.testing import * +from scipy.testing import * -set_package_path() + from scipy.sparse import csr_matrix, \ spidentity, speye, spkron, spdiags, \ lil_eye, lil_diags -restore_path() #TODO check whether format=XXX is respected -class TestConstructUtils(NumpyTestCase): - def check_spdiags(self): +class TestConstructUtils(TestCase): + def test_spdiags(self): diags1 = array( [[ 1, 2, 3, 4, 5]] ) diags2 = array( [[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9,10]] ) @@ -60,12 +59,12 @@ assert_equal( spdiags(d,o,m,n).todense(), result ) - def check_identity(self): + def test_identity(self): a = spidentity(3) b = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype='d') assert_array_equal(a.toarray(), b) - def check_eye(self): + def test_eye(self): a = speye(2, 3 ) b = array([[1, 0, 0], [0, 1, 0]], dtype='d') assert_array_equal(a.toarray(), b) @@ -78,7 +77,7 @@ b = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype='d') assert_array_equal(a.toarray(), b) - def check_spkron(self): + def test_spkron(self): cases = [] cases.append(array([[ 0]])) @@ -102,7 +101,7 @@ assert_array_equal(result,expected) - def check_lil_diags(self): + def test_lil_diags(self): assert_array_equal(lil_diags([[1,2,3],[4,5],[6]], [0,1,2],(3,3)).todense(), [[1,4,6], @@ -134,5 +133,5 @@ [6,5,0]]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sparse/tests/test_sparse.py =================================================================== --- trunk/scipy/sparse/tests/test_sparse.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sparse/tests/test_sparse.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,14 +4,14 @@ from numpy import ones, array, asarray, empty import random -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ coo_matrix, lil_matrix, dia_matrix, spidentity, spdiags, \ spkron from scipy.linsolve import splu -restore_path() + def random_sparse(m,n,nnz_per_row): rows = numpy.arange(m).repeat(nnz_per_row) cols = numpy.random.random_integers(low=0,high=n-1,size=nnz_per_row*m) @@ -43,10 +43,11 @@ return dia_matrix((diags,offsets),shape=(N**2,N**2)).asformat(format) import time -class TestSparseTools(NumpyTestCase): +class TestSparseTools(TestCase): """Simple benchmarks for sparse matrix module""" - def test_arithmetic(self,level=5): + @dec.bench + def test_arithmetic(self): matrices = [] #matrices.append( ('A','Identity', spidentity(500**2,format='csr')) ) matrices.append( ('A','Poisson5pt', poisson2d(500,format='csr')) ) @@ -93,8 +94,8 @@ print fmt % (format,operation,msec_per_it) - - def bench_sort(self,level=5): + @dec.bench + def test_sort(self): """sort CSR column indices""" matrices = [] matrices.append( ('Rand10', 1e4, 10) ) @@ -127,8 +128,8 @@ print fmt % (A.format,name,shape,A.nnz,1e3*(end-start)/float(iter) ) - - def bench_matvec(self,level=4): + @dec.bench + def test_matvec(self): matrices = [] matrices.append(('Identity', spidentity(10**4,format='dia'))) matrices.append(('Identity', spidentity(10**4,format='csr'))) @@ -175,7 +176,8 @@ print fmt % (A.format,name,shape,A.nnz,MFLOPs) - def bench_construction(self,level=5): + @dec.bench + def test_construction(self): """build matrices by inserting single values""" matrices = [] matrices.append( ('Empty',csr_matrix((10000,10000))) ) @@ -210,8 +212,8 @@ print fmt % (format,name,shape,A.nnz,(end-start)/float(iter)) - - def bench_conversion(self,level=5): + @dec.bench + def test_conversion(self): A = poisson2d(100) formats = ['csr','csc','coo','lil','dok'] @@ -252,8 +254,8 @@ print output -class TestLarge(NumpyTestCase): - def check_large(self): +class TestLarge(TestCase): + def test_large(self): # Create a 100x100 matrix with 100 non-zero elements # and play around with it #TODO move this out of Common since it doesn't use spmatrix @@ -280,5 +282,5 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/sparse/tests/test_spfuncs.py =================================================================== --- trunk/scipy/sparse/tests/test_spfuncs.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sparse/tests/test_spfuncs.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,15 +1,13 @@ from numpy import array, kron, diag, matrix -from numpy.testing import * +from scipy.testing import * -set_package_path() from scipy.sparse.spfuncs import * from scipy.sparse import csr_matrix, csc_matrix, bsr_matrix from scipy.sparse.sparsetools import csr_scale_rows, csr_scale_columns, \ bsr_scale_rows, bsr_scale_columns -restore_path() -class TestSparseFunctions(NumpyTestCase): - def check_scale_rows_and_cols(self): +class TestSparseFunctions(TestCase): + def test_scale_rows_and_cols(self): D = matrix([[1,0,0,2,3], [0,4,0,5,0], [0,0,6,7,0]]) @@ -51,7 +49,7 @@ - def check_extract_diagonal(self): + def test_extract_diagonal(self): mats = [] mats.append( [[1,0,2]] ) mats.append( [[1],[0],[2]] ) @@ -81,8 +79,7 @@ assert_equal(result,expected) - def check_estimate_blocksize(self): - + def test_estimate_blocksize(self): mats = [] mats.append( [[0,1],[1,0]] ) mats.append( [[1,1,0],[0,0,1],[1,0,1]] ) @@ -103,7 +100,7 @@ assert(r >= B.shape[0]) assert(c >= B.shape[1]) - def check_count_blocks(self): + def test_count_blocks(self): def gold(A,bs): R,C = bs I,J = A.nonzero() @@ -132,7 +129,6 @@ assert_equal(count_blocks(Y,(1,2)),gold(X,(1,2))) - if __name__ == "__main__": - NumpyTest().run() + unittests.main() Modified: trunk/scipy/sparse/tests/test_sputils.py =================================================================== --- trunk/scipy/sparse/tests/test_sputils.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/sparse/tests/test_sputils.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,29 +1,25 @@ """unit tests for sparse utility functions""" import numpy as np -from numpy.testing import * - -set_package_path() +from scipy.testing import * from scipy.sparse.sputils import * -restore_path() +class TestSparseUtils(TestCase): -class TestSparseUtils(NumpyTestCase): - - def check_upcast(self): + def test_upcast(self): assert_equal(upcast('intc'),np.intc) assert_equal(upcast('int32','float32'),np.float64) assert_equal(upcast('bool',complex,float),np.complex128) assert_equal(upcast('i','d'),np.float64) - def check_getdtype(self): + def test_getdtype(self): A = np.array([1],dtype='int8') assert_equal(getdtype(None,default=float),np.float) assert_equal(getdtype(None,a=A),np.int8) - def check_isscalarlike(self): + def test_isscalarlike(self): assert_equal(isscalarlike(3.0),True) assert_equal(isscalarlike(-4),True) assert_equal(isscalarlike(2.5),True) @@ -36,7 +32,7 @@ assert_equal(isscalarlike( (1,) ), False) assert_equal(isscalarlike( (1,2) ), False) - def check_isintlike(self): + def test_isintlike(self): assert_equal(isintlike(3.0),True) assert_equal(isintlike(-4),True) assert_equal(isintlike(np.array(3)),True) @@ -47,7 +43,7 @@ assert_equal(isintlike( (1,) ), False) assert_equal(isintlike( (1,2) ), False) - def check_isshape(self): + def test_isshape(self): assert_equal(isshape( (1,2) ),True) assert_equal(isshape( (5,2) ),True) @@ -56,7 +52,7 @@ assert_equal(isshape( (0,4) ),False) assert_equal(isshape( (2,2,2) ),False) - def check_issequence(self): + def test_issequence(self): assert_equal(issequence( (1,) ),True) assert_equal(issequence( (1,2,3) ),True) assert_equal(issequence( [1] ),True) @@ -66,11 +62,11 @@ assert_equal(issequence( np.array([[1],[2],[3]]) ),False) assert_equal(issequence( 3 ),False) - def check_isdense(self): + def test_isdense(self): assert_equal(isdense( np.array([1]) ),True) assert_equal(isdense( np.matrix([1]) ),True) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/special/__init__.py =================================================================== --- trunk/scipy/special/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/special/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -19,5 +19,5 @@ register_func('i0',i0) del register_func -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/special/tests/test_basic.py =================================================================== --- trunk/scipy/special/tests/test_basic.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/special/tests/test_basic.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -32,377 +32,377 @@ #8 test_sh_jacobi #8 test_sh_legendre -from numpy import * +from numpy import dot -from numpy.testing import * -set_package_path() +from scipy.testing import * + from scipy.special import * import scipy.special._cephes as cephes -restore_path() -class TestCephes(NumpyTestCase): - def check_airy(self): + +class TestCephes(TestCase): + def test_airy(self): cephes.airy(0) - def check_airye(self): + def test_airye(self): cephes.airye(0) - def check_bdtr(self): + def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) - def check_bdtri(self): + def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) - def check_bdtrc(self): + def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) - def check_bdtrin(self): + def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) - def check_bdtrik(self): + def test_bdtrik(self): cephes.bdtrik(1,3,0.5) - def check_bei(self): + def test_bei(self): assert_equal(cephes.bei(0),0.0) - def check_beip(self): + def test_beip(self): assert_equal(cephes.beip(0),0.0) - def check_ber(self): + def test_ber(self): assert_equal(cephes.ber(0),1.0) - def check_berp(self): + def test_berp(self): assert_equal(cephes.berp(0),0.0) - def check_besselpoly(self): + def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) - def check_beta(self): + def test_beta(self): assert_equal(cephes.beta(1,1),1.0) - def check_betainc(self): + def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) - def check_betaln(self): + def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) - def check_betaincinv(self): + def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) - def check_btdtr(self): + def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) - def check_btdtri(self): + def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) - def check_btdtria(self): + def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) - def check_btdtrib(self): + def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) - def check_cbrt(self): + def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) - def check_chdtr(self): + def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) - def check_chdtrc(self): + def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) - def check_chdtri(self): + def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) - def check_chdtriv(self): + def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) - def check_chndtr(self): + def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) - def check_chndtridf(self): + def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) - def check_chndtrinc(self): + def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) - def check_chndtrix(self): + def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) - def check_cosdg(self): + def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) - def check_cosm1(self): + def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) - def check_cotdg(self): + def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) - def check_dawsn(self): + def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) - def check_ellipe(self): + def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) - def check_ellipeinc(self): + def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) - def check_ellipj(self): + def test_ellipj(self): cephes.ellipj(0,1) - def check_ellipk(self): + def test_ellipk(self): cephes.ellipk(0)#==pi/2 - def check_ellipkinc(self): + def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) - def check_erf(self): + def test_erf(self): assert_equal(cephes.erf(0),0.0) - def check_erfc(self): + def test_erfc(self): assert_equal(cephes.erfc(0),1.0) - def check_exp1(self): + def test_exp1(self): cephes.exp1(1) - def check_expi(self): + def test_expi(self): cephes.expi(1) - def check_expn(self): + def test_expn(self): cephes.expn(1,1) - def check_exp10(self): + def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) - def check_exp2(self): + def test_exp2(self): assert_equal(cephes.exp2(2),4.0) - def check_expm1(self): + def test_expm1(self): assert_equal(cephes.expm1(0),0.0) - def check_fdtr(self): + def test_fdtr(self): assert_equal(cephes.fdtr(1,1,0),0.0) - def check_fdtrc(self): + def test_fdtrc(self): assert_equal(cephes.fdtrc(1,1,0),1.0) - def check_fdtri(self): + def test_fdtri(self): cephes.fdtri(1,1,0.5) - def check_fdtridfd(self): + def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) - def check_fresnel(self): + def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) - def check_gamma(self): + def test_gamma(self): assert_equal(cephes.gamma(5),24.0) - def check_gammainc(self): + def test_gammainc(self): assert_equal(cephes.gammainc(5,0),0.0) - def check_gammaincc(self): + def test_gammaincc(self): assert_equal(cephes.gammaincc(5,0),1.0) - def check_gammainccinv(self): + def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) - def check_gammaln(self): + def test_gammaln(self): cephes.gammaln(10) - def check_gdtr(self): + def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) - def check_gdtrc(self): + def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) - def check_gdtria(self): + def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) - def check_gdtrib(self): + def test_gdtrib(self): cephes.gdtrib(1,0,1) #assert_equal(cephes.gdtrib(1,0,1),5.0) - def check_gdtrix(self): + def test_gdtrix(self): cephes.gdtrix(1,1,.1) - def check_hankel1(self): + def test_hankel1(self): cephes.hankel1(1,1) - def check_hankel1e(self): + def test_hankel1e(self): cephes.hankel1e(1,1) - def check_hankel2(self): + def test_hankel2(self): cephes.hankel2(1,1) - def check_hankel2e(self): + def test_hankel2e(self): cephes.hankel2e(1,1) - def check_hyp1f1(self): + def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) - def check_hyp1f2(self): + def test_hyp1f2(self): cephes.hyp1f2(1,1,1,1) - def check_hyp2f0(self): + def test_hyp2f0(self): cephes.hyp2f0(1,1,1,1) - def check_hyp2f1(self): + def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) - def check_hyp3f0(self): + def test_hyp3f0(self): assert_equal(cephes.hyp3f0(1,1,1,0),(1.0,0.0)) - def check_hyperu(self): + def test_hyperu(self): assert_equal(cephes.hyperu(0,1,1),1.0) - def check_i0(self): + def test_i0(self): assert_equal(cephes.i0(0),1.0) - def check_i0e(self): + def test_i0e(self): assert_equal(cephes.i0e(0),1.0) - def check_i1(self): + def test_i1(self): assert_equal(cephes.i1(0),0.0) - def check_i1e(self): + def test_i1e(self): assert_equal(cephes.i1e(0),0.0) - def check_it2i0k0(self): + def test_it2i0k0(self): cephes.it2i0k0(1) - def check_it2j0y0(self): + def test_it2j0y0(self): cephes.it2j0y0(1) - def check_it2struve0(self): + def test_it2struve0(self): cephes.it2struve0(1) - def check_itairy(self): + def test_itairy(self): cephes.itairy(1) - def check_iti0k0(self): + def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) - def check_itj0y0(self): + def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) - def check_itmodstruve0(self): + def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) - def check_itstruve0(self): + def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) - def check_iv(self): + def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) - def check_j0(self): + def test_j0(self): assert_equal(cephes.j0(0),1.0) - def check_j1(self): + def test_j1(self): assert_equal(cephes.j1(0),0.0) - def check_jn(self): + def test_jn(self): assert_equal(cephes.jn(0,0),1.0) - def check_jv(self): + def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) - def check_k0(self): + def test_k0(self): cephes.k0(2) - def check_k0e(self): + def test_k0e(self): cephes.k0e(2) - def check_k1(self): + def test_k1(self): cephes.k1(2) - def check_k1e(self): + def test_k1e(self): cephes.k1e(2) - def check_kei(self): + def test_kei(self): cephes.kei(2) - def check_keip(self): + def test_keip(self): assert_equal(cephes.keip(0),0.0) - def check_ker(self): + def test_ker(self): cephes.ker(2) - def check_kerp(self): + def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) - def check_kn(self): + def test_kn(self): cephes.kn(1,1) - def check_kolmogi(self): + def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) - def check_kolmogorov(self): + def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0),1.0) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) - def check_log1p(self): + def test_log1p(self): assert_equal(cephes.log1p(0),0.0) - def check_lpmv(self): + def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) - def check_mathieu_a(self): + def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) - def check_mathieu_b(self): + def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) - def check_mathieu_cem(self): + def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) - def check_mathieu_modcem1(self): + def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) - def check_mathieu_modcem2(self): + def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) - def check_mathieu_sem(self): + def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) - def check_mathieu_modsem1(self): + def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) - def check_mathieu_modsem2(self): + def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) - def check_modfresnelm(self): + def test_modfresnelm(self): cephes.modfresnelm(0) - def check_modfresnelp(self): + def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) - def check_nbdtr(self): + def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) - def check_nbdtrc(self): + def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) - def check_nbdtri(self): + def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) - def check_nbdtrin(self): + def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) - def check_ncfdtr(self): + def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) - def check_ncfdtri(self): + def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1,1,1,0),0.0) - def check_ncfdtridfd(self): + def test_ncfdtridfd(self): cephes.ncfdtridfd(1,0.5,0,1) def __check_ncfdtridfn(self): cephes.ncfdtridfn(1,0.5,0,1) def __check_ncfdtrinc(self): cephes.ncfdtrinc(1,0.5,0,1) - def check_nctdtr(self): + def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) - def check_nctdtrinc(self): + def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) - def check_nctdtrit(self): + def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) - def check_ndtr(self): + def test_ndtr(self): assert_equal(cephes.ndtr(0),0.5) - def check_ndtri(self): + def test_ndtri(self): assert_equal(cephes.ndtri(0.5),0.0) - def check_nrdtrimn(self): + def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) - def check_nrdtrisd(self): + def test_nrdtrisd(self): assert_equal(cephes.nrdtrisd(0.5,0.5,0.5),0.0) - def check_obl_ang1(self): + def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) - def check_obl_ang1_cv(self): + def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) - def check_obl_rad1(self): + def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) - def check_obl_rad1_cv(self): + def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) - def check_obl_rad2(self): + def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) - def check_obl_rad2_cv(self): + def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) - def check_pbdv(self): + def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,0.0)) - def check_pbvv(self): + def test_pbvv(self): cephes.pbvv(1,0) - def check_pbwa(self): + def test_pbwa(self): cephes.pbwa(1,0) - def check_pdtr(self): + def test_pdtr(self): cephes.pdtr(0,1) - def check_pdtrc(self): + def test_pdtrc(self): cephes.pdtrc(0,1) - def check_pdtri(self): + def test_pdtri(self): cephes.pdtri(0.5,0.5) - def check_pdtrik(self): + def test_pdtrik(self): cephes.pdtrik(0.5,1) - def check_pro_ang1(self): + def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) - def check_pro_ang1_cv(self): + def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) - def check_pro_rad1(self): + def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) - def check_pro_rad1_cv(self): + def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) - def check_pro_rad2(self): + def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) - def check_pro_rad2_cv(self): + def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) - def check_psi(self): + def test_psi(self): cephes.psi(1) - def check_radian(self): + def test_radian(self): assert_equal(cephes.radian(0,0,0),0) - def check_rgamma(self): + def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) - def check_round(self): + def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) @@ -410,54 +410,54 @@ assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) - def check_shichi(self): + def test_shichi(self): cephes.shichi(1) - def check_sici(self): + def test_sici(self): cephes.sici(1) - def check_sindg(self): + def test_sindg(self): assert_equal(cephes.sindg(90),1.0) - def check_smirnov(self): + def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) - def check_smirnovi(self): + def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) - def check_spence(self): + def test_spence(self): assert_equal(cephes.spence(1),0.0) - def check_stdtr(self): + def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) - def check_stdtridf(self): + def test_stdtridf(self): cephes.stdtridf(0.7,1) - def check_stdtrit(self): + def test_stdtrit(self): cephes.stdtrit(1,0.7) - def check_struve(self): + def test_struve(self): assert_equal(cephes.struve(0,0),0.0) - def check_tandg(self): + def test_tandg(self): assert_equal(cephes.tandg(45),1.0) - def check_tklmbda(self): + def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) - def check_y0(self): + def test_y0(self): cephes.y0(1) - def check_y1(self): + def test_y1(self): cephes.y1(1) - def check_yn(self): + def test_yn(self): cephes.yn(1,1) - def check_yv(self): + def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) - def check_zeta(self): + def test_zeta(self): cephes.zeta(2,2) - def check_zetac(self): + def test_zetac(self): assert_equal(cephes.zetac(0),-1.5) - def check_wofz(self): + def test_wofz(self): cephes.wofz(0) -class TestAiry(NumpyTestCase): - def check_airy(self): +class TestAiry(TestCase): + def test_airy(self): #This tests the airy function to ensure 8 place accuracy in computation x = airy(.99) @@ -467,7 +467,7 @@ x = airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) - def check_airye(self): + def test_airye(self): a = airye(0.01) b = airy(0.01) b1 = [None]*4 @@ -477,7 +477,7 @@ b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) - def check_bi_zeros(self): + def test_bi_zeros(self): bi = bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), @@ -485,43 +485,43 @@ array([ 0.60195789 , -0.76031014])) assert_array_almost_equal(bi,bia,4) - def check_ai_zeros(self): + def test_ai_zeros(self): ai = ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([ 0.5357]), array([ 0.7012])),4) -class TestAssocLaguerre(NumpyTestCase): - def check_assoc_laguerre(self): +class TestAssocLaguerre(TestCase): + def test_assoc_laguerre(self): a1 = genlaguerre(11,1) a2 = assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) -class TestBesselpoly(NumpyTestCase): - def check_besselpoly(self): +class TestBesselpoly(TestCase): + def test_besselpoly(self): pass -class TestKelvin(NumpyTestCase): - def check_bei(self): +class TestKelvin(TestCase): + def test_bei(self): mbei = bei(2) assert_almost_equal(mbei, 0.9722916273066613,5)#this may not be exact - def check_beip(self): + def test_beip(self): mbeip = beip(2) assert_almost_equal(mbeip,0.91701361338403631,5)#this may not be exact - def check_ber(self): + def test_ber(self): mber = ber(2) assert_almost_equal(mber,0.75173418271380821,5)#this may not be exact - def check_berp(self): + def test_berp(self): mberp = berp(2) assert_almost_equal(mberp,-0.49306712470943909,5)#this may not be exact - def check_bei_zeros(self): + def test_bei_zeros(self): bi = bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, @@ -548,7 +548,7 @@ 0.929983638568022]),11) - def check_beip_zeros(self): + def test_beip_zeros(self): bip = beip_zeros(5) assert_array_almost_equal(bip,array([ 3.772673304934953, 8.280987849760042, @@ -556,7 +556,7 @@ 17.193431752512542, 21.641143941167325]),4) - def check_ber_zeros(self): + def test_ber_zeros(self): ber = ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, @@ -564,7 +564,7 @@ 16.11356, 20.55463]),4) - def check_berp_zeros(self): + def test_berp_zeros(self): brp = berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, @@ -572,30 +572,30 @@ 19.41758, 23.86430]),4) - def check_kelvin(self): + def test_kelvin(self): mkelv = kelvin(2) assert_array_almost_equal(mkelv,(ber(2)+bei(2)*1j, ker(2)+kei(2)*1j, berp(2)+beip(2)*1j, kerp(2)+keip(2)*1j),8) - def check_kei(self): + def test_kei(self): mkei = kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) - def check_keip(self): + def test_keip(self): mkeip = keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) - def check_ker(self): + def test_ker(self): mker = ker(2) assert_almost_equal(mker,-0.041664513991509472,5) - def check_kerp(self): + def test_kerp(self): mkerp = kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) - def check_kei_zeros(self): + def test_kei_zeros(self): kei = kei_zeros(5) assert_array_almost_equal(kei,array([ 3.91467, 8.34422, @@ -603,7 +603,7 @@ 17.22314, 21.66464]),4) - def check_keip_zeros(self): + def test_keip_zeros(self): keip = keip_zeros(5) assert_array_almost_equal(keip,array([ 4.93181, 9.40405, @@ -614,7 +614,7 @@ # numbers come from 9.9 of A&S pg. 381 - def check_kelvin_zeros(self): + def test_kelvin_zeros(self): tmp = kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([ 2.84892, @@ -660,7 +660,7 @@ 18.30717, 22.75379]),4) - def check_ker_zeros(self): + def test_ker_zeros(self): ker = ker_zeros(5) assert_array_almost_equal(ker,array([ 1.71854, 6.12728, @@ -668,7 +668,7 @@ 15.00269, 19.44381]),4) - def check_kerp_zeros(self): + def test_kerp_zeros(self): kerp = kerp_zeros(5) assert_array_almost_equal(kerp,array([ 2.66584, 7.17212, @@ -676,8 +676,8 @@ 16.08312, 20.53068]),4) -class TestBernoulli(NumpyTestCase): - def check_bernoulli(self): +class TestBernoulli(TestCase): + def test_bernoulli(self): brn = bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, @@ -686,28 +686,28 @@ -0.0333, 0.0000]),4) -class TestBeta(NumpyTestCase): - def check_beta(self): +class TestBeta(TestCase): + def test_beta(self): bet = beta(2,4) betg = (gamma(2)*gamma(4))/gamma(6) assert_almost_equal(bet,betg,8) - def check_betaln(self): + def test_betaln(self): betln = betaln(2,4) bet = log(abs(beta(2,4))) assert_almost_equal(betln,bet,8) - def check_betainc(self): + def test_betainc(self): btinc = betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) - def check_betaincinv(self): + def test_betaincinv(self): y = betaincinv(2,4,.5) comp = betainc(2,4,y) assert_almost_equal(comp,.5,5) -class TestCheby(NumpyTestCase): - def check_chebyc(self): +class TestCheby(TestCase): + def test_chebyc(self): C0 = chebyc(0) C1 = chebyc(1) C2 = chebyc(2) @@ -722,7 +722,7 @@ assert_array_almost_equal(C4.c,[1,0,-4,0,2],13) assert_array_almost_equal(C5.c,[1,0,-5,0,5,0],13) - def check_chebys(self): + def test_chebys(self): S0 = chebys(0) S1 = chebys(1) S2 = chebys(2) @@ -736,7 +736,7 @@ assert_array_almost_equal(S4.c,[1,0,-3,0,1],13) assert_array_almost_equal(S5.c,[1,0,-4,0,3,0],13) - def check_chebyt(self): + def test_chebyt(self): T0 = chebyt(0) T1 = chebyt(1) T2 = chebyt(2) @@ -750,7 +750,7 @@ assert_array_almost_equal(T4.c,[8,0,-8,0,1],13) assert_array_almost_equal(T5.c,[16,0,-20,0,5,0],13) - def check_chebyu(self): + def test_chebyu(self): U0 = chebyu(0) U1 = chebyu(1) U2 = chebyu(2) @@ -764,43 +764,43 @@ assert_array_almost_equal(U4.c,[16,0,-12,0,1],13) assert_array_almost_equal(U5.c,[32,0,-32,0,6,0],13) -class TestTrigonometric(NumpyTestCase): - def check_cbrt(self): +class TestTrigonometric(TestCase): + def test_cbrt(self): cb = cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) - def check_cbrtmore(self): + def test_cbrtmore(self): cb1 = cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) - def check_cosdg(self): + def test_cosdg(self): cdg = cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) - def check_cosdgmore(self): + def test_cosdgmore(self): cdgm = cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) - def check_cosm1(self): + def test_cosm1(self): cs = (cosm1(0),cosm1(.3),cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) - def check_cotdg(self): + def test_cotdg(self): ct = cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) - def check_cotdgmore(self): + def test_cotdgmore(self): ct1 = cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) - def check_specialpoints(self): + def test_specialpoints(self): assert_almost_equal(cotdg(45), 1.0, 14) assert_almost_equal(cotdg(-45), -1.0, 14) assert_almost_equal(cotdg(90), 0.0, 14) @@ -815,21 +815,21 @@ assert_almost_equal(cotdg(-315), 1.0, 14) assert_almost_equal(cotdg(765), 1.0, 14) - def check_sinc(self): + def test_sinc(self): c = arange(-2,2,.1) y = sinc(c) yre = sin(pi*c)/(pi*c) yre[20] = 1.0 assert_array_almost_equal(y, yre, 4) - def check_0(self): + def test_0(self): x = 0.0 assert_equal(sinc(x),1.0) - def check_sindg(self): + def test_sindg(self): sn = sindg(90) assert_equal(sn,1.0) - def check_sindgmore(self): + def test_sindgmore(self): snm = sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) @@ -837,14 +837,14 @@ snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) -class TestTandg(NumpyTestCase): +class TestTandg(TestCase): - def check_tandg(self): + def test_tandg(self): tn = tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) - def check_tandgmore(self): + def test_tandgmore(self): tnm = tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) @@ -852,7 +852,7 @@ tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) - def check_specialpoints(self): + def test_specialpoints(self): assert_almost_equal(tandg(0), 0.0, 14) assert_almost_equal(tandg(45), 1.0, 14) assert_almost_equal(tandg(-45), -1.0, 14) @@ -865,17 +865,17 @@ assert_almost_equal(tandg(315), -1.0, 14) assert_almost_equal(tandg(-315), 1.0, 14) -class TestEllip(NumpyTestCase): - def check_ellipj(self): +class TestEllip(TestCase): + def test_ellipj(self): el = ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) - def check_ellipk(self): + def test_ellipk(self): elk = ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) - def check_ellipkinc(self): + def test_ellipkinc(self): elkinc = ellipkinc(pi/2,.2) elk = ellipk(0.2) assert_almost_equal(elkinc,elk,15) @@ -886,11 +886,11 @@ assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S - def check_ellipe(self): + def test_ellipe(self): ele = ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) - def check_ellipeinc(self): + def test_ellipeinc(self): eleinc = ellipeinc(pi/2,.2) ele = ellipe(0.2) assert_almost_equal(eleinc,ele,14) @@ -901,13 +901,13 @@ assert_almost_equal(eleinc, 0.58823065, 8) -class TestErf(NumpyTestCase): +class TestErf(TestCase): - def check_erf(self): + def test_erf(self): er = erf(.25) assert_almost_equal(er,0.2763263902,8) - def check_erf_zeros(self): + def test_erf_zeros(self): erz = erf_zeros(5) erzr= array([1.45061616+1.88094300j, 2.24465928+2.61657514j, @@ -916,15 +916,15 @@ 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) - def check_erfcinv(self): + def test_erfcinv(self): i = erfcinv(1) assert_equal(i,0) - def check_erfinv(self): + def test_erfinv(self): i = erfinv(0) assert_equal(i,0) - def check_errprint(self): + def test_errprint(self): a = errprint() b = 1-a #a is the state 1-a inverts state c = errprint(b) #returns last state 'a' @@ -933,8 +933,8 @@ assert_equal(d,b) #makes sure state was returned #assert_equal(d,1-a) -class TestEuler(NumpyTestCase): - def check_euler(self): +class TestEuler(TestCase): + def test_euler(self): eu0 = euler(0) eu1 = euler(1) eu2 = euler(2) # just checking segfaults @@ -955,45 +955,45 @@ errmax = max(err) assert_almost_equal(errmax, 0.0, 14) -class TestExp(NumpyTestCase): - def check_exp2(self): +class TestExp(TestCase): + def test_exp2(self): ex = exp2(2) exrl = 2**2 assert_equal(ex,exrl) - def check_exp2more(self): + def test_exp2more(self): exm = exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) - def check_exp10(self): + def test_exp10(self): ex = exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) - def check_exp10more(self): + def test_exp10more(self): exm = exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) - def check_expm1(self): + def test_expm1(self): ex = (expm1(2),expm1(3),expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) - def check_expm1more(self): + def test_expm1more(self): ex1 = (expm1(2),expm1(2.1),expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) -class TestFresnel(NumpyTestCase): - def check_fresnel(self): +class TestFresnel(TestCase): + def test_fresnel(self): frs = array(fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place - def check_fresnel_zeros(self): + def test_fresnel_zeros(self): szo, czo = fresnel_zeros(5) assert_array_almost_equal(szo, array([ 2.0093+0.2885j, @@ -1012,86 +1012,86 @@ assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) - def check_fresnelc_zeros(self): + def test_fresnelc_zeros(self): szo, czo = fresnel_zeros(6) frc = fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) - def check_fresnels_zeros(self): + def test_fresnels_zeros(self): szo, czo = fresnel_zeros(5) frs = fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) -class TestGamma(NumpyTestCase): - def check_gamma(self): +class TestGamma(TestCase): + def test_gamma(self): gam = gamma(5) assert_equal(gam,24.0) - def check_gammaln(self): + def test_gammaln(self): gamln = gammaln(3) lngam = log(gamma(3)) assert_almost_equal(gamln,lngam,8) - def check_gammainc(self): + def test_gammainc(self): gama = gammainc(.5,.5) assert_almost_equal(gama,.7,1) - def check_gammaincc(self): + def test_gammaincc(self): gicc = gammaincc(.5,.5) greal = 1 - gammainc(.5,.5) assert_almost_equal(gicc,greal,8) - def check_gammainccinv(self): + def test_gammainccinv(self): gccinv = gammainccinv(.5,.5) gcinv = gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) - def check_gammaincinv(self): + def test_gammaincinv(self): y = gammaincinv(.4,.4) x = gammainc(.4,y) assert_almost_equal(x,0.4,1) - def check_rgamma(self): + def test_rgamma(self): rgam = rgamma(8) rlgam = 1/gamma(8) assert_almost_equal(rgam,rlgam,8) -class TestHankel(NumpyTestCase): - def check_negv(self): +class TestHankel(TestCase): + def test_negv(self): assert_almost_equal(hankel1(-3,2), -hankel1(3,2), 14) - def check_hankel1(self): + def test_hankel1(self): hank1 = hankel1(1,.1) hankrl = (jv(1,.1)+yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(hankel1e(-3,2), -hankel1e(3,2), 14) - def check_hankel1e(self): + def test_hankel1e(self): hank1e = hankel1e(1,.1) hankrle = hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(hankel2(-3,2), -hankel2(3,2), 14) - def check_hankel2(self): + def test_hankel2(self): hank2 = hankel2(1,.1) hankrl2 = (jv(1,.1)-yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(hankel2e(-3,2), -hankel2e(3,2), 14) - def check_hankl2e(self): + def test_hankl2e(self): hank2e = hankel2e(1,.1) hankrl2e = hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) -class TestHermite(NumpyTestCase): - def check_hermite(self): +class TestHermite(TestCase): + def test_hermite(self): H0 = hermite(0) H1 = hermite(1) H2 = hermite(2) @@ -1105,7 +1105,7 @@ assert_array_almost_equal(H4.c,[16,0,-48,0,12],12) assert_array_almost_equal(H5.c,[32,0,-160,0,120,0],12) - def check_hermitenorm(self): + def test_hermitenorm(self): # He_n(x) = 2**(-n/2) H_n(x/sqrt(2)) psub = poly1d([1.0/sqrt(2),0]) H0 = hermitenorm(0) @@ -1130,9 +1130,9 @@ _gam = cephes.gamma -class TestGegenbauer(NumpyTestCase): +class TestGegenbauer(TestCase): - def check_gegenbauer(self): + def test_gegenbauer(self): a = 5*rand()-0.5 if any(a==0): a = -0.2 Ca0 = gegenbauer(0,a) @@ -1153,31 +1153,31 @@ 0,15*poch(a,3),0])/15.0,11) -class TestHyper(NumpyTestCase): - def check_h1vp(self): +class TestHyper(TestCase): + def test_h1vp(self): h1 = h1vp(1,.1) h1real = (jvp(1,.1)+yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) - def check_h2vp(self): + def test_h2vp(self): h2 = h2vp(1,.1) h2real = (jvp(1,.1)-yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) - def check_hyp0f1(self): + def test_hyp0f1(self): pass - def check_hyp1f1(self): + def test_hyp1f1(self): hyp1 = hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) - def check_hyp1f2(self): + def test_hyp1f2(self): pass - def check_hyp2f0(self): + def test_hyp2f0(self): pass - def check_hyp2f1(self): + def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], @@ -1200,10 +1200,10 @@ cv = hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) - def check_hyp3f0(self): + def test_hyp3f0(self): pass - def check_hyperu(self): + def test_hyperu(self): val1 = hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] @@ -1216,8 +1216,8 @@ /(gamma(a)*gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) -class TestBessel(NumpyTestCase): - def check_i0(self): +class TestBessel(TestCase): + def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], @@ -1231,12 +1231,12 @@ cv = i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) - def check_i0e(self): + def test_i0e(self): oize = i0e(.1) oizer = ive(0,.1) assert_almost_equal(oize,oizer,8) - def check_i1(self): + def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], @@ -1249,68 +1249,68 @@ cv = i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) - def check_i1e(self): + def test_i1e(self): oi1e = i1e(.1) oi1er = ive(1,.1) assert_almost_equal(oi1e,oi1er,8) - def check_iti0k0(self): + def test_iti0k0(self): iti0 = array(iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) - def check_it2i0k0(self): + def test_it2i0k0(self): it2k = it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) - def check_itj0y0(self): + def test_itj0y0(self): it0 = array(itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) - def check_it2j0y0(self): + def test_it2j0y0(self): it2 = array(it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) - def check_negv(self): + def test_negv(self): assert_equal(iv(3,2), iv(-3,2)) - def check_iv(self): + def test_iv(self): iv1 = iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) - def check_negv(self): + def test_negv(self): assert_equal(ive(3,2), ive(-3,2)) - def check_ive(self): + def test_ive(self): ive1 = ive(0,.1) iv1 = iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) - def check_ivp0(self): + def test_ivp0(self): assert_almost_equal(iv(1,2), ivp(0,2), 10) - def check_ivp(self): + def test_ivp(self): y=(iv(0,2)+iv(2,2))/2 x = ivp(1,2) assert_almost_equal(x,y,10) - def check_j0(self): + def test_j0(self): oz = j0(.1) ozr = jn(0,.1) assert_almost_equal(oz,ozr,8) - def check_j1(self): + def test_j1(self): o1 = j1(.1) o1r = jn(1,.1) assert_almost_equal(o1,o1r,8) - def check_jn(self): + def test_jn(self): jnnr = jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(jv(-3,2), -jv(3,2), 14) - def check_jv(self): + def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], @@ -1321,10 +1321,10 @@ yc = jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) - def check_negv(self): + def test_negv(self): assert_almost_equal(jve(-3,2), -jve(3,2), 14) - def check_jve(self): + def test_jve(self): jvexp = jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = jve(1,.2+1j) @@ -1332,7 +1332,7 @@ jvexpr = jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) - def check_jn_zeros(self): + def test_jn_zeros(self): jn0 = jn_zeros(0,5) jn1 = jn_zeros(1,5) assert_array_almost_equal(jn0,array([ 2.4048255577, @@ -1346,14 +1346,14 @@ 13.32369, 16.47063]),4) - def check_jnjnp_zeros(self): + def test_jnjnp_zeros(self): pass #jnjp = jnjnp(3) #assert_array_almost_equal(jnjp,(array([ #I don't think specfun jdzo is working properly the outputs do not seem to correlate #to the inputs - def check_jnp_zeros(self): + def test_jnp_zeros(self): jnp = jnp_zeros(1,5) assert_array_almost_equal(jnp, array([ 1.84118, 5.33144, @@ -1361,7 +1361,7 @@ 11.70600, 14.86359]),4) - def check_jnyn_zeros(self): + def test_jnyn_zeros(self): jnz = jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([ 3.83171, 7.01559, @@ -1384,32 +1384,32 @@ 13.28576, 16.44006])),4) - def check_jvp(self): + def test_jvp(self): jvprim = jvp(2,2) jv0 = (jv(1,2)-jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) - def check_k0(self): + def test_k0(self): ozk = k0(.1) ozkr = kv(0,.1) assert_almost_equal(ozk,ozkr,8) - def check_k0e(self): + def test_k0e(self): ozke = k0e(.1) ozker = kve(0,.1) assert_almost_equal(ozke,ozker,8) - def check_k1(self): + def test_k1(self): o1k = k1(.1) o1kr = kv(1,.1) assert_almost_equal(o1k,o1kr,8) - def check_k1e(self): + def test_k1e(self): o1ke = k1e(.1) o1ker = kve(1,.1) assert_almost_equal(o1ke,o1ker,8) - def check_jacobi(self): + def test_jacobi(self): a = 5*rand() - 1 b = 5*rand() - 1 P0 = jacobi(0,a,b) @@ -1427,28 +1427,28 @@ p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) - def check_kn(self): + def test_kn(self): kn1 = kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) - def check_negv(self): + def test_negv(self): assert_equal(kv(3.0, 2.2), kv(-3.0, 2.2)) - def check_kv0(self): + def test_kv0(self): kv0 = kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) - def check_kv1(self): + def test_kv1(self): kv1 = kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) - def check_kv2(self): + def test_kv2(self): kv2 = kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) - def check_negv(self): + def test_negv(self): assert_equal(kve(3.0, 2.2), kve(-3.0, 2.2)) - def check_kve(self): + def test_kve(self): kve1 = kve(0,.2) kv1 = kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) @@ -1457,35 +1457,35 @@ kv2 = kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) - def check_kvp_v0n1(self): + def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-kv(1,z), kvp(0,z, n=1), 10) - def check_kvp_n1(self): + def test_kvp_n1(self): v = 3. z = 2.2 xc = -kv(v+1,z) + v/z*kv(v,z) x = kvp(v,z, n=1) assert_almost_equal(xc, x, 10) #this function (kvp) is broken - def check_kvp_n2(self): + def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * kv(v,z) + kv(v+1,z)/z x = kvp(v, z, n=2) assert_almost_equal(xc, x, 10) - def check_y0(self): + def test_y0(self): oz = y0(.1) ozr = yn(0,.1) assert_almost_equal(oz,ozr,8) - def check_y1(self): + def test_y1(self): o1 = y1(.1) o1r = yn(1,.1) assert_almost_equal(o1,o1r,8) - def check_y0_zeros(self): + def test_y0_zeros(self): yo,ypo = y0_zeros(2) zo,zpo = y0_zeros(2,complex=1) all = r_[yo,zo] @@ -1494,51 +1494,51 @@ assert_array_almost_equal(abs(yv(1,all)-allval),0.0,11) - def check_y1_zeros(self): + def test_y1_zeros(self): y1 = y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) - def check_y1p_zeros(self): + def test_y1p_zeros(self): y1p = y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([ 0.5768+0.904j]), array([-0.7635+0.5892j])),3) - def check_yn_zeros(self): + def test_yn_zeros(self): an = yn_zeros(4,2) assert_array_almost_equal(an,array([ 5.64515, 9.36162]),5) - def check_ynp_zeros(self): + def test_ynp_zeros(self): ao = ynp_zeros(0,2) assert_array_almost_equal(ao,array([ 2.19714133, 5.42968104]),6) - def check_yn(self): + def test_yn(self): yn2n = yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(yv(-3,2), -yv(3,2), 14) - def check_yv(self): + def test_yv(self): yv2 = yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) - def check_negv(self): + def test_negv(self): assert_almost_equal(yve(-3,2), -yve(3,2), 14) - def check_yve(self): + def test_yve(self): yve2 = yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = yv(1,.2+1j)*exp(-1) yve22 = yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) - def check_yvp(self): + def test_yvp(self): yvpr = (yv(1,.2) - yv(3,.2))/2.0 yvp1 = yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) -class TestLaguerre(NumpyTestCase): - def check_laguerre(self): +class TestLaguerre(TestCase): + def test_laguerre(self): lag0 = laguerre(0) lag1 = laguerre(1) lag2 = laguerre(2) @@ -1552,7 +1552,7 @@ assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) - def check_genlaguerre(self): + def test_genlaguerre(self): k = 5*rand()-0.9 lag0 = genlaguerre(0,k) lag1 = genlaguerre(1,k) @@ -1565,8 +1565,8 @@ # Base polynomials come from Abrahmowitz and Stegan -class TestLegendre(NumpyTestCase): - def check_legendre(self): +class TestLegendre(TestCase): + def test_legendre(self): leg0 = legendre(0) leg1 = legendre(1) leg2 = legendre(2) @@ -1581,26 +1581,26 @@ assert_almost_equal(leg5.c,array([63,0,-70,0,15,0])/8.0) -class TestLambda(NumpyTestCase): - def check_lmbda(self): +class TestLambda(TestCase): + def test_lmbda(self): lam = lmbda(1,.1) lamr = (array([jn(0,.1), 2*jn(1,.1)/.1]), array([jvp(0,.1), -2*jv(1,.1)/.01 + 2*jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) -class TestLog1p(NumpyTestCase): - def check_log1p(self): +class TestLog1p(TestCase): + def test_log1p(self): l1p = (log1p(10),log1p(11),log1p(12)) l1prl = (log(11),log(12),log(13)) assert_array_almost_equal(l1p,l1prl,8) - def check_log1pmore(self): + def test_log1pmore(self): l1pm = (log1p(1),log1p(1.1),log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) -class TestLegendreFunctions(NumpyTestCase): - def check_lpmn(self): +class TestLegendreFunctions(TestCase): + def test_lpmn(self): lp = lpmn(0,2,.5) assert_array_almost_equal(lp,(array([ [ 1.00000 , 0.50000, @@ -1609,7 +1609,7 @@ 1.00000 , 1.50000]])),4) - def check_lpn(self): + def test_lpn(self): lpnf = lpn(2,.5) assert_array_almost_equal(lpnf,(array( [ 1.00000 , 0.50000, @@ -1618,111 +1618,111 @@ 1.00000 , 1.50000])),4) - def check_lpmv(self): + def test_lpmv(self): lp = lpmv(0,2,.5) assert_almost_equal(lp,-0.125,3) - def check_lqmn(self): + def test_lqmn(self): lqmnf = lqmn(0,2,.5) lqmnf = lqmn(0,2,.5) lqf = lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) - def check_lqn(self): + def test_lqn(self): lqf = lqn(2,.5) assert_array_almost_equal(lqf,(array([ 0.5493, -0.7253, -0.8187]), array([ 1.3333, 1.216 , -0.8427])),4) -class TestMathieu(NumpyTestCase): +class TestMathieu(TestCase): - def check_mathieu_a(self): + def test_mathieu_a(self): pass - def check_mathieu_even_coef(self): + def test_mathieu_even_coef(self): mc = mathieu_even_coef(2,5) #Q not defined broken and cannot figure out proper reporting order - def check_mathieu_odd_coef(self): + def test_mathieu_odd_coef(self): pass #same problem as above -class TestFresnelIntegral(NumpyTestCase): +class TestFresnelIntegral(TestCase): - def check_modfresnelp(self): + def test_modfresnelp(self): pass - def check_modfresnelm(self): + def test_modfresnelm(self): pass -class TestOblCvSeq(NumpyTestCase): - def check_obl_cv_seq(self): +class TestOblCvSeq(TestCase): + def test_obl_cv_seq(self): obl = obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([ -0.348602, 1.393206, 5.486800, 11.492120]),5) -class TestParabolicCylinder(NumpyTestCase): - def check_pbdn_seq(self): +class TestParabolicCylinder(TestCase): + def test_pbdn_seq(self): pb = pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([ 0.9975, 0.0998]), array([-0.0499, 0.9925])),4) - def check_pbdv(self): + def test_pbdv(self): pbv = pbdv(1,.2) derrl = 1/2*(.2)*pbdv(1,.2)[0] - pbdv(0,.2)[0] - def check_pbdv_seq(self): + def test_pbdv_seq(self): pbn = pbdn_seq(1,.1) pbv = pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) -class TestPolygamma(NumpyTestCase): +class TestPolygamma(TestCase): # from Table 6.2 (pg. 271) of A&S - def check_polygamma(self): + def test_polygamma(self): poly2 = polygamma(2,1) poly3 = polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) -class TestProCvSeq(NumpyTestCase): - def check_pro_cv_seq(self): +class TestProCvSeq(TestCase): + def test_pro_cv_seq(self): prol = pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([ 0.319000, 2.593084, 6.533471, 12.514462]),5) -class TestPsi(NumpyTestCase): - def check_psi(self): +class TestPsi(TestCase): + def test_psi(self): ps = psi(1) assert_almost_equal(ps,-0.57721566490153287,8) -class TestRadian(NumpyTestCase): - def check_radian(self): +class TestRadian(TestCase): + def test_radian(self): rad = radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) - def check_radianmore(self): + def test_radianmore(self): rad1 = radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) -class TestRiccati(NumpyTestCase): - def check_riccati_jn(self): +class TestRiccati(TestCase): + def test_riccati_jn(self): jnrl = (sph_jn(1,.2)[0]*.2,sph_jn(1,.2)[0]+sph_jn(1,.2)[1]*.2) ricjn = riccati_jn(1,.2) assert_array_almost_equal(ricjn,jnrl,8) - def check_riccati_yn(self): + def test_riccati_yn(self): ynrl = (sph_yn(1,.2)[0]*.2,sph_yn(1,.2)[0]+sph_yn(1,.2)[1]*.2) ricyn = riccati_yn(1,.2) assert_array_almost_equal(ricyn,ynrl,8) -class TestRound(NumpyTestCase): - def check_round(self): +class TestRound(TestCase): + def test_round(self): rnd = map(int,(round(10.1),round(10.4),round(10.5),round(10.6))) # Note: According to the documentation, scipy.special.round is @@ -1733,9 +1733,9 @@ rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) -class _test_sh_legendre(NumpyTestCase): +class _test_sh_legendre(TestCase): - def check_sh_legendre(self): + def test_sh_legendre(self): # P*_n(x) = P_n(2x-1) psub = poly1d([2,-1]) Ps0 = sh_legendre(0) @@ -1757,9 +1757,9 @@ assert_array_almost_equal(Ps4.c,pse4.c,12) assert_array_almost_equal(Ps5.c,pse5.c,12) -class _test_sh_chebyt(NumpyTestCase): +class _test_sh_chebyt(TestCase): - def check_sh_chebyt(self): + def test_sh_chebyt(self): # T*_n(x) = T_n(2x-1) psub = poly1d([2,-1]) Ts0 = sh_chebyt(0) @@ -1782,9 +1782,9 @@ assert_array_almost_equal(Ts5.c,tse5.c,12) -class _test_sh_chebyu(NumpyTestCase): +class _test_sh_chebyu(TestCase): - def check_sh_chebyu(self): + def test_sh_chebyu(self): # U*_n(x) = U_n(2x-1) psub = poly1d([2,-1]) Us0 = sh_chebyu(0) @@ -1806,9 +1806,9 @@ assert_array_almost_equal(Us4.c,use4.c,12) assert_array_almost_equal(Us5.c,use5.c,11) -class _test_sh_jacobi(NumpyTestCase): +class _test_sh_jacobi(TestCase): - def check_sh_jacobi(self): + def test_sh_jacobi(self): # G^(p,q)_n(x) = n! gamma(n+p)/gamma(2*n+p) * P^(p-q,q-1)_n(2*x-1) conv = lambda n,p: _gam(n+1)*_gam(n+p)/_gam(2*n+p) psub = poly1d([2,-1]) @@ -1835,11 +1835,11 @@ assert_array_almost_equal(G4.c,ge4.c,13) assert_array_almost_equal(G5.c,ge5.c,13) -class TestSpherical(NumpyTestCase): - def check_sph_harm(self): +class TestSpherical(TestCase): + def test_sph_harm(self): pass - def check_sph_in(self): + def test_sph_in(self): i1n = sph_in(1,.2) inp0 = (i1n[0][1]) inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1]) @@ -1847,12 +1847,12 @@ 0.066933714568029540839]),12) assert_array_almost_equal(i1n[1],[inp0,inp1],12) - def check_sph_inkn(self): + def test_sph_inkn(self): spikn = r_[sph_in(1,.2)+sph_kn(1,.2)] inkn = r_[sph_inkn(1,.2)] assert_array_almost_equal(inkn,spikn,10) - def check_sph_jn(self): + def test_sph_jn(self): s1 = sph_jn(2,.2) s10 = -s1[0][1] s11 = s1[0][0]-2.0/0.2*s1[0][1] @@ -1862,12 +1862,12 @@ 0.0026590560795273856680],12) assert_array_almost_equal(s1[1],[s10,s11,s12],12) - def check_sph_jnyn(self): + def test_sph_jnyn(self): jnyn = r_[sph_jn(1,.2) + sph_yn(1,.2)] # tuple addition jnyn1 = r_[sph_jnyn(1,.2)] assert_array_almost_equal(jnyn1,jnyn,9) - def check_sph_kn(self): + def test_sph_kn(self): kn = sph_kn(2,.2) kn0 = -kn[0][1] kn1 = -kn[0][0]-2.0/0.2*kn[0][1] @@ -1877,7 +1877,7 @@ 585.15696310385559829],12) assert_array_almost_equal(kn[1],[kn0,kn1,kn2],9) - def check_sph_yn(self): + def test_sph_yn(self): sy1 = sph_yn(2,.2)[0][2] sy2 = sph_yn(0,.2)[0][0] sphpy = (sph_yn(1,.2)[0][0]-2*sph_yn(2,.2)[0][2])/3 #correct derivative value @@ -1887,4 +1887,4 @@ assert_almost_equal(sy3,sphpy,4) #compare correct derivative val. (correct =-system val). if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/special/tests/test_spfun_stats.py =================================================================== --- trunk/scipy/special/tests/test_spfun_stats.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/special/tests/test_spfun_stats.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,11 +1,11 @@ import numpy as N -from numpy.testing import * +from scipy.testing import * -set_package_path() + from scipy.special import gammaln, multigammaln -restore_path() -class TestMultiGammaLn(NumpyTestCase): + +class TestMultiGammaLn(TestCase): def test1(self): a = N.abs(N.random.randn()) assert_array_equal(multigammaln(a, 1), gammaln(a)) @@ -35,4 +35,4 @@ pass if __name__ == '__main__': - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/__init__.py =================================================================== --- trunk/scipy/stats/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -11,5 +11,5 @@ from kde import gaussian_kde __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/stats/models/__init__.py =================================================================== --- trunk/scipy/stats/models/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/models/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -16,5 +16,5 @@ __all__ = filter(lambda s:not s.startswith('_'),dir()) -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/stats/models/tests/test_bspline.py =================================================================== --- trunk/scipy/stats/models/tests/test_bspline.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/models/tests/test_bspline.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,13 +3,13 @@ """ import numpy as N -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * import scipy.stats.models as S import scipy.stats.models.bspline as B -class TestBSpline(NumpyTestCase): +class TestBSpline(TestCase): def test1(self): b = B.BSpline(N.linspace(0,10,11), x=N.linspace(0,10,101)) @@ -20,4 +20,4 @@ if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/models/tests/test_formula.py =================================================================== --- trunk/scipy/stats/models/tests/test_formula.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/models/tests/test_formula.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -7,11 +7,11 @@ import numpy as N import numpy.random as R import numpy.linalg as L -from numpy.testing import assert_almost_equal, NumpyTest, NumpyTestCase +from scipy.testing import * from scipy.stats.models import utils, formula, contrast -class TestTerm(NumpyTestCase): +class TestTerm(TestCase): def test_init(self): t1 = formula.Term("trivial") @@ -47,7 +47,7 @@ f = intercept * t1 self.assertEqual(str(f), str(formula.Formula(t1))) -class TestFormula(NumpyTestCase): +class TestFormula(TestCase): def setUp(self): self.X = R.standard_normal((40,10)) @@ -227,4 +227,4 @@ self.assertEquals(estimable, False) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/models/tests/test_glm.py =================================================================== --- trunk/scipy/stats/models/tests/test_glm.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/models/tests/test_glm.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,16 +4,16 @@ import numpy as N import numpy.random as R -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * import scipy.stats.models as S import scipy.stats.models.glm as models W = R.standard_normal -class TestRegression(NumpyTestCase): +class TestRegression(TestCase): - def check_Logistic(self): + def test_Logistic(self): X = W((40,10)) Y = N.greater(W((40,)), 0) family = S.family.Binomial() @@ -21,7 +21,7 @@ results = cmodel.fit(Y) self.assertEquals(results.df_resid, 30) - def check_Logisticdegenerate(self): + def test_Logisticdegenerate(self): X = W((40,10)) X[:,0] = X[:,1] + X[:,2] Y = N.greater(W((40,)), 0) @@ -31,4 +31,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/models/tests/test_regression.py =================================================================== --- trunk/scipy/stats/models/tests/test_regression.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/models/tests/test_regression.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,13 +3,13 @@ """ from numpy.random import standard_normal -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * from scipy.stats.models.regression import OLSModel, ARModel W = standard_normal -class TestRegression(NumpyTestCase): +class TestRegression(TestCase): def testOLS(self): X = W((40,10)) @@ -42,4 +42,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/models/tests/test_rlm.py =================================================================== --- trunk/scipy/stats/models/tests/test_rlm.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/models/tests/test_rlm.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,13 +3,13 @@ """ import numpy.random as R -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * import scipy.stats.models.rlm as models W = R.standard_normal -class TestRegression(NumpyTestCase): +class TestRegression(TestCase): def test_Robust(self): X = W((40,10)) @@ -27,4 +27,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/models/tests/test_scale.py =================================================================== --- trunk/scipy/stats/models/tests/test_scale.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/models/tests/test_scale.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,13 +3,13 @@ """ import numpy.random as R -from numpy.testing import NumpyTest, NumpyTestCase +from scipy.testing import * import scipy.stats.models.robust.scale as scale W = R.standard_normal -class TestScale(NumpyTestCase): +class TestScale(TestCase): def test_MAD(self): X = W((40,10)) @@ -50,4 +50,4 @@ self.assertEquals(m.shape, (40,10)) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/models/tests/test_utils.py =================================================================== --- trunk/scipy/stats/models/tests/test_utils.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/models/tests/test_utils.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,11 +4,11 @@ import numpy as N import numpy.random as R -from numpy.testing import assert_almost_equal, NumpyTest, NumpyTestCase +from scipy.testing import * from scipy.stats.models import utils -class TestUtils(NumpyTestCase): +class TestUtils(TestCase): def test_recipr(self): X = N.array([[2,1],[-1,0]]) @@ -55,4 +55,4 @@ self.assertRaises(ValueError, utils.StepFunction, x, y) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/morestats.py =================================================================== --- trunk/scipy/stats/morestats.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/morestats.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -17,6 +17,7 @@ import scipy.special as special import futil import numpy as sb +from scipy.testing.decorators import is_nosetest __all__ = ['find_repeats', 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot', @@ -769,6 +770,7 @@ pval = distributions.f.sf(W,k-1,Ntot-k) # 1 - cdf return W, pval + at is_nosetest(False) def binom_test(x,n=None,p=0.5): """An exact (two-sided) test of the null hypothesis that the probability of success in a Bernoulli experiment is p. Modified: trunk/scipy/stats/tests/test_distributions.py =================================================================== --- trunk/scipy/stats/tests/test_distributions.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/tests/test_distributions.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -2,18 +2,14 @@ """ +from scipy.testing import * -from numpy.testing import * -set_package_path() import numpy from numpy import typecodes, array -import stats -restore_path() +import scipy.stats as stats -import types - -def kolmogorov_test(diststr,args=(),N=20,significance=0.01): +def kolmogorov_check(diststr,args=(),N=20,significance=0.01): qtest = stats.ksoneisf(significance,N) cdf = eval('stats.'+diststr+'.cdf') dist = eval('stats.'+diststr) @@ -27,7 +23,6 @@ # generate test cases to test cdf and distribution consistency - dists = ['uniform','norm','lognorm','expon','beta', 'powerlaw','bradford','burr','fisk','cauchy','halfcauchy', 'foldcauchy','gamma','gengamma','loggamma', @@ -40,39 +35,41 @@ 'genlogistic', 'logistic','gumbel_l','gumbel_r','gompertz', 'hypsecant', 'laplace', 'reciprocal','triang','tukeylambda'] -for dist in dists: - distfunc = eval('stats.'+dist) - nargs = distfunc.numargs - alpha = 0.01 - if dist == 'fatiguelife': - alpha = 0.001 - if dist == 'erlang': - args = str((4,)+tuple(rand(2))) - elif dist == 'frechet': - args = str(tuple(2*rand(1))+(0,)+tuple(2*rand(2))) - elif dist == 'triang': - args = str(tuple(rand(nargs))) - elif dist == 'reciprocal': - vals = rand(nargs) - vals[1] = vals[0] + 1.0 - args = str(tuple(vals)) - else: - args = str(tuple(1.0+rand(nargs))) - exstr = r""" -class Test%(dist)s(NumpyTestCase): - def check_cdf(self): - D,pval = stats.kstest('%(dist)s','',args=%(args)s,N=30) - if (pval < %(alpha)f): - D,pval = stats.kstest('%(dist)s','',args=%(args)s,N=30) - #if (pval < %(alpha)f): - # D,pval = stats.kstest('%(dist)s','',args=%(args)s,N=30) - assert (pval > %(alpha)f), "D = " + str(D) + "; pval = " + str(pval) + "; alpha = " + str(alpha) + "\nargs = " + str(%(args)s) -""" % {'dist' : dist, 'args' : args, 'alpha' : alpha} - exec exstr +# check function for test generator +def check_distribution(dist, args, alpha): + D,pval = stats.kstest(dist,'', args=args, N=30) + if (pval < alpha): + D,pval = stats.kstest(dist,'',args=args, N=30) + #if (pval < alpha): + # D,pval = stats.kstest(dist,'',args=args, N=30) + assert (pval > alpha), "D = " + str(D) + "; pval = " + str(pval) + \ + "; alpha = " + str(alpha) + "\nargs = " + str(args) +# nose test generator +def test_all_distributions(): + for dist in dists: + distfunc = eval('stats.'+dist) + nargs = distfunc.numargs + alpha = 0.01 + if dist == 'fatiguelife': + alpha = 0.001 + if dist == 'erlang': + args = (4,)+tuple(rand(2)) + elif dist == 'frechet': + args = tuple(2*rand(1))+(0,)+tuple(2*rand(2)) + elif dist == 'triang': + args = tuple(rand(nargs)) + elif dist == 'reciprocal': + vals = rand(nargs) + vals[1] = vals[0] + 1.0 + args = tuple(vals) + else: + args = tuple(1.0+rand(nargs)) + yield check_distribution, dist, args, alpha -class TestRandInt(NumpyTestCase): - def check_rvs(self): + +class TestRandInt(TestCase): + def test_rvs(self): vals = stats.randint.rvs(5,30,size=100) assert(numpy.all(vals < 30) & numpy.all(vals >= 5)) assert(len(vals) == 100) @@ -84,21 +81,21 @@ assert isinstance(val, numpy.ScalarType),`type(val)` assert(val.dtype.char in typecodes['AllInteger']) - def check_pdf(self): + def test_pdf(self): k = numpy.r_[0:36] out = numpy.where((k >= 5) & (k < 30), 1.0/(30-5), 0) vals = stats.randint.pmf(k,5,30) assert_array_almost_equal(vals,out) - def check_cdf(self): + def test_cdf(self): x = numpy.r_[0:36:100j] k = numpy.floor(x) out = numpy.select([k>=30,k>=5],[1.0,(k-5.0+1)/(30-5.0)],0) vals = stats.randint.cdf(x,5,30) assert_array_almost_equal(vals, out, decimal=12) -class TestBinom(NumpyTestCase): - def check_rvs(self): +class TestBinom(TestCase): + def test_rvs(self): vals = stats.binom.rvs(10, 0.75, size=(2, 50)) assert(numpy.all(vals >= 0) & numpy.all(vals <= 10)) assert(numpy.shape(vals) == (2, 50)) @@ -108,8 +105,8 @@ assert(val.dtype.char in typecodes['AllInteger']) -class TestBernoulli(NumpyTestCase): - def check_rvs(self): +class TestBernoulli(TestCase): + def test_rvs(self): vals = stats.bernoulli.rvs(0.75, size=(2, 50)) assert(numpy.all(vals >= 0) & numpy.all(vals <= 1)) assert(numpy.shape(vals) == (2, 50)) @@ -118,8 +115,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestNBinom(NumpyTestCase): - def check_rvs(self): +class TestNBinom(TestCase): + def test_rvs(self): vals = stats.nbinom.rvs(10, 0.75, size=(2, 50)) assert(numpy.all(vals >= 0)) assert(numpy.shape(vals) == (2, 50)) @@ -128,8 +125,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestGeom(NumpyTestCase): - def check_rvs(self): +class TestGeom(TestCase): + def test_rvs(self): vals = stats.geom.rvs(0.75, size=(2, 50)) assert(numpy.all(vals >= 0)) assert(numpy.shape(vals) == (2, 50)) @@ -138,11 +135,11 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) - def check_pmf(self): + def test_pmf(self): vals = stats.geom.pmf([1,2,3],0.5) assert_array_almost_equal(vals,[0.5,0.25,0.125]) - def check_cdf_sf(self): + def test_cdf_sf(self): vals = stats.geom.cdf([1,2,3],0.5) vals_sf = stats.geom.sf([1,2,3],0.5) expected = array([0.5,0.75,0.875]) @@ -150,8 +147,8 @@ assert_array_almost_equal(vals_sf,1-expected) -class TestHypergeom(NumpyTestCase): - def check_rvs(self): +class TestHypergeom(TestCase): + def test_rvs(self): vals = stats.hypergeom.rvs(20, 10, 3, size=(2, 50)) assert(numpy.all(vals >= 0) & numpy.all(vals <= 3)) @@ -161,8 +158,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestLogser(NumpyTestCase): - def check_rvs(self): +class TestLogser(TestCase): + def test_rvs(self): vals = stats.logser.rvs(0.75, size=(2, 50)) assert(numpy.all(vals >= 1)) assert(numpy.shape(vals) == (2, 50)) @@ -171,8 +168,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestPoisson(NumpyTestCase): - def check_rvs(self): +class TestPoisson(TestCase): + def test_rvs(self): vals = stats.poisson.rvs(0.5, size=(2, 50)) assert(numpy.all(vals >= 0)) assert(numpy.shape(vals) == (2, 50)) @@ -181,8 +178,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestZipf(NumpyTestCase): - def check_rvs(self): +class TestZipf(TestCase): + def test_rvs(self): vals = stats.zipf.rvs(1.5, size=(2, 50)) assert(numpy.all(vals >= 1)) assert(numpy.shape(vals) == (2, 50)) @@ -191,8 +188,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestDLaplace(NumpyTestCase): - def check_rvs(self): +class TestDLaplace(TestCase): + def test_rvs(self): vals = stats.dlaplace.rvs(1.5 , size=(2, 50)) assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) @@ -200,8 +197,8 @@ assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) -class TestRvDiscrete(NumpyTestCase): - def check_rvs(self): +class TestRvDiscrete(TestCase): + def test_rvs(self): states = [-1,0,1,2,3,4] probability = [0.0,0.3,0.4,0.0,0.3,0.0] samples = 1000 @@ -211,9 +208,9 @@ for s,p in zip(states,probability): assert abs(sum(x == s)/float(samples) - p) < 0.05 -class TestExpon(NumpyTestCase): - def check_zero(self): +class TestExpon(TestCase): + def test_zero(self): assert_equal(stats.expon.pdf(0),1) if __name__ == "__main__": - NumpyTest('stats.distributions').run() + unittest.main() Modified: trunk/scipy/stats/tests/test_morestats.py =================================================================== --- trunk/scipy/stats/tests/test_morestats.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/tests/test_morestats.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,14 +1,11 @@ # Author: Travis Oliphant, 2002 # -from numpy.testing import * +from scipy.testing import * -set_package_path() -import scipy -import numpy -import stats -restore_path() +import scipy.stats as stats + import numpy as N from numpy.random import RandomState @@ -23,49 +20,49 @@ g9 = [1.002, 0.998, 0.996, 0.995, 0.996, 1.004, 1.004, 0.998, 0.999, 0.991] g10= [0.991, 0.995, 0.984, 0.994, 0.997, 0.997, 0.991, 0.998, 1.004, 0.997] -class TestShapiro(NumpyTestCase): - def check_basic(self): +class TestShapiro(TestCase): + def test_basic(self): x1 = [0.11,7.87,4.61,10.14,7.95,3.14,0.46, 4.43,0.21,4.75,0.71,1.52,3.24, 0.93,0.42,4.97,9.53,4.55,0.47,6.66] - w,pw = scipy.stats.shapiro(x1) + w,pw = stats.shapiro(x1) assert_almost_equal(w,0.90047299861907959,6) assert_almost_equal(pw,0.042089745402336121,6) x2 = [1.36,1.14,2.92,2.55,1.46,1.06,5.27,-1.11, 3.48,1.10,0.88,-0.51,1.46,0.52,6.20,1.69, 0.08,3.67,2.81,3.49] - w,pw = scipy.stats.shapiro(x2) + w,pw = stats.shapiro(x2) assert_almost_equal(w,0.9590270,6) assert_almost_equal(pw,0.52460,3) -class TestAnderson(NumpyTestCase): - def check_normal(self): +class TestAnderson(TestCase): + def test_normal(self): rs = RandomState(1234567890) x1 = rs.standard_exponential(size=50) x2 = rs.standard_normal(size=50) - A,crit,sig = scipy.stats.anderson(x1) + A,crit,sig = stats.anderson(x1) assert_array_less(crit[:-1], A) - A,crit,sig = scipy.stats.anderson(x2) + A,crit,sig = stats.anderson(x2) assert_array_less(A, crit[-2:]) - def check_expon(self): + def test_expon(self): rs = RandomState(1234567890) x1 = rs.standard_exponential(size=50) x2 = rs.standard_normal(size=50) - A,crit,sig = scipy.stats.anderson(x1,'expon') + A,crit,sig = stats.anderson(x1,'expon') assert_array_less(A, crit[-2:]) - A,crit,sig = scipy.stats.anderson(x2,'expon') + A,crit,sig = stats.anderson(x2,'expon') assert_array_less(crit[:-1], A) -class TestAnsari(NumpyTestCase): - def check_small(self): +class TestAnsari(TestCase): + def test_small(self): x = [1,2,3,3,4] y = [3,2,6,1,6,1,4,1] W, pval = stats.ansari(x,y) assert_almost_equal(W,23.5,11) assert_almost_equal(pval,0.13499256881897437,11) - def check_approx(self): + def test_approx(self): ramsay = N.array((111, 107, 100, 99, 102, 106, 109, 108, 104, 99, 101, 96, 97, 102, 107, 113, 116, 113, 110, 98)) parekh = N.array((107, 108, 106, 98, 105, 103, 110, 105, 104, @@ -74,13 +71,13 @@ assert_almost_equal(W,185.5,11) assert_almost_equal(pval,0.18145819972867083,11) - def check_exact(self): + def test_exact(self): W,pval = stats.ansari([1,2,3,4],[15,5,20,8,10,12]) assert_almost_equal(W,10.0,11) assert_almost_equal(pval,0.533333333333333333,7) -class TestBartlett(NumpyTestCase): - def check_data(self): +class TestBartlett(TestCase): + def test_data(self): args = [] for k in range(1,11): args.append(eval('g%d'%k)) @@ -88,8 +85,8 @@ assert_almost_equal(T,20.78587342806484,7) assert_almost_equal(pval,0.0136358632781,7) -class TestLevene(NumpyTestCase): - def check_data(self): +class TestLevene(TestCase): + def test_data(self): args = [] for k in range(1,11): args.append(eval('g%d'%k)) @@ -97,8 +94,8 @@ assert_almost_equal(W,1.7059176930008939,7) assert_almost_equal(pval,0.0990829755522,7) -class TestBinomTest(NumpyTestCase): - def check_data(self): +class TestBinomP(TestCase): + def test_data(self): pval = stats.binom_test(100,250) assert_almost_equal(pval,0.0018833009350757682,11) pval = stats.binom_test(201,405) @@ -106,12 +103,12 @@ pval = stats.binom_test([682,243],p=3.0/4) assert_almost_equal(pval,0.38249155957481695,11) -class TestFindRepeats(NumpyTestCase): - def check_basic(self): +class TestFindRepeats(TestCase): + def test_basic(self): a = [1,2,3,4,1,2,3,4,1,2,5] - res,nums = scipy.stats.find_repeats(a) + res,nums = stats.find_repeats(a) assert_array_equal(res,[1,2,3,4]) assert_array_equal(nums,[3,3,2,2]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/stats/tests/test_stats.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -7,15 +7,13 @@ """ import sys -from numpy.testing import * -from numpy import * +from scipy.testing import * +from numpy import array, arange, zeros, ravel, float32, float64, power import numpy -import scipy -set_package_path() -import stats -restore_path() +import scipy.stats as stats + """ Numbers in docstrings begining with 'W' refer to the section numbers and headings found in the STATISTICS QUIZ of Leland Wilkinson. These are considered to be essential functionality. True testing and @@ -28,7 +26,7 @@ ## Datasets ## These data sets are from the nasty.dat sets used by Wilkinson ## for MISS, need to be able to represent missing values -## For completeness, I should write the relavant tests and count them as failures +## For completeness, I should write the relevant tests and count them as failures ## Somewhat acceptable, since this is still beta software. It would count as a ## good target for 1.0 status X = array([1,2,3,4,5,6,7,8,9],float) @@ -48,7 +46,7 @@ X8 = X7 * X X9 = X8 * X -class TestRound(NumpyTestCase): +class TestRound(TestCase): """ W.II. ROUND You should get the numbers 1 to 9. Many language compilers, @@ -71,7 +69,7 @@ statistical calculations. """ - def check_rounding0(self): + def test_rounding0(self): """ W.II.A.0. Print ROUND with only one digit. You should get the numbers 1 to 9. Many language compilers, @@ -83,22 +81,22 @@ y = round(ROUND[i]) assert_equal(y,i+1) - def check_rounding1(self): + def test_rounding1(self): """ W.II.A.1. Y = INT(2.6*7 -0.2) (Y should be 18)""" y = int(2.6*7 -0.2) assert_equal(y, 18) - def check_rounding2(self): + def test_rounding2(self): """ W.II.A.2. Y = 2-INT(EXP(LOG(SQR(2)*SQR(2)))) (Y should be 0)""" y=2-int(numpy.exp(numpy.log(numpy.sqrt(2.)*numpy.sqrt(2.)))) assert_equal(y,0) - def check_rounding3(self): + def test_rounding3(self): """ W.II.A.3. Y = INT(3-EXP(LOG(SQR(2)*SQR(2)))) (Y should be 1)""" y=(int(round((3-numpy.exp(numpy.log(numpy.sqrt(2.0)*numpy.sqrt(2.0))))))) assert_equal(y,1) -class TestBasicStats(NumpyTestCase): +class TestBasicStats(TestCase): """ W.II.C. Compute basic statistic on all the variables. The means should be the fifth value of all the variables (case FIVE). @@ -107,86 +105,86 @@ II. C. Basic Statistics """ - def check_meanX(self): - y = scipy.stats.mean(X) + def test_meanX(self): + y = stats.mean(X) assert_almost_equal(y, 5.0) - def check_stdX(self): - y = scipy.stats.std(X) + def test_stdX(self): + y = stats.std(X) assert_almost_equal(y, 2.738612788) - def check_tmeanX(self): - y = scipy.stats.tmean(X, (2, 8), (True, True)) + def test_tmeanX(self): + y = stats.tmean(X, (2, 8), (True, True)) assert_almost_equal(y, 5.0) - def check_tvarX(self): - y = scipy.stats.tvar(X, (2, 8), (True, True)) + def test_tvarX(self): + y = stats.tvar(X, (2, 8), (True, True)) assert_almost_equal(y, 4.6666666666666661) - def check_tstdX(self): - y = scipy.stats.tstd(X, (2, 8), (True, True)) + def test_tstdX(self): + y = stats.tstd(X, (2, 8), (True, True)) assert_almost_equal(y, 2.1602468994692865) - def check_meanZERO(self): - y = scipy.stats.mean(ZERO) + def test_meanZERO(self): + y = stats.mean(ZERO) assert_almost_equal(y, 0.0) - def check_stdZERO(self): - y = scipy.stats.std(ZERO) + def test_stdZERO(self): + y = stats.std(ZERO) assert_almost_equal(y, 0.0) ## Really need to write these tests to handle missing values properly -## def check_meanMISS(self): -## y = scipy.stats.mean(MISS) +## def test_meanMISS(self): +## y = stats.mean(MISS) ## assert_almost_equal(y, 0.0) ## -## def check_stdMISS(self): -## y = scipy.stats.stdev(MISS) +## def test_stdMISS(self): +## y = stats.stdev(MISS) ## assert_almost_equal(y, 0.0) - def check_meanBIG(self): - y = scipy.stats.mean(BIG) + def test_meanBIG(self): + y = stats.mean(BIG) assert_almost_equal(y, 99999995.00) - def check_stdBIG(self): - y = scipy.stats.std(BIG) + def test_stdBIG(self): + y = stats.std(BIG) assert_almost_equal(y, 2.738612788) - def check_meanLITTLE(self): - y = scipy.stats.mean(LITTLE) + def test_meanLITTLE(self): + y = stats.mean(LITTLE) assert_approx_equal(y, 0.999999950) - def check_stdLITTLE(self): - y = scipy.stats.std(LITTLE) + def test_stdLITTLE(self): + y = stats.std(LITTLE) assert_approx_equal(y, 2.738612788e-8) - def check_meanHUGE(self): - y = scipy.stats.mean(HUGE) + def test_meanHUGE(self): + y = stats.mean(HUGE) assert_approx_equal(y, 5.00000e+12) - def check_stdHUGE(self): - y = scipy.stats.std(HUGE) + def test_stdHUGE(self): + y = stats.std(HUGE) assert_approx_equal(y, 2.738612788e12) - def check_meanTINY(self): - y = scipy.stats.mean(TINY) + def test_meanTINY(self): + y = stats.mean(TINY) assert_almost_equal(y, 0.0) - def check_stdTINY(self): - y = scipy.stats.std(TINY) + def test_stdTINY(self): + y = stats.std(TINY) assert_almost_equal(y, 0.0) - def check_meanROUND(self): - y = scipy.stats.mean(ROUND) + def test_meanROUND(self): + y = stats.mean(ROUND) assert_approx_equal(y, 4.500000000) - def check_stdROUND(self): - y = scipy.stats.std(ROUND) + def test_stdROUND(self): + y = stats.std(ROUND) assert_approx_equal(y, 2.738612788) -class TestNanFunc(NumpyTestCase): +class TestNanFunc(TestCase): def __init__(self, *args, **kw): - NumpyTestCase.__init__(self, *args, **kw) + TestCase.__init__(self, *args, **kw) self.X = X.copy() self.Xall = X.copy() @@ -197,52 +195,52 @@ self.Xsome[0] = numpy.nan self.Xsomet = self.Xsomet[1:] - def check_nanmean_none(self): + def test_nanmean_none(self): """Check nanmean when no values are nan.""" m = stats.stats.nanmean(X) assert_approx_equal(m, X[4]) - def check_nanmean_some(self): + def test_nanmean_some(self): """Check nanmean when some values only are nan.""" m = stats.stats.nanmean(self.Xsome) assert_approx_equal(m, 5.5) - def check_nanmean_all(self): + def test_nanmean_all(self): """Check nanmean when all values are nan.""" m = stats.stats.nanmean(self.Xall) assert numpy.isnan(m) - def check_nanstd_none(self): + def test_nanstd_none(self): """Check nanstd when no values are nan.""" s = stats.stats.nanstd(self.X) assert_approx_equal(s, stats.stats.std(self.X)) - def check_nanstd_some(self): + def test_nanstd_some(self): """Check nanstd when some values only are nan.""" s = stats.stats.nanstd(self.Xsome) assert_approx_equal(s, stats.stats.std(self.Xsomet)) - def check_nanstd_all(self): + def test_nanstd_all(self): """Check nanstd when all values are nan.""" s = stats.stats.nanstd(self.Xall) assert numpy.isnan(s) - def check_nanmedian_none(self): + def test_nanmedian_none(self): """Check nanmedian when no values are nan.""" m = stats.stats.nanmedian(self.X) assert_approx_equal(m, stats.stats.median(self.X)) - def check_nanmedian_some(self): + def test_nanmedian_some(self): """Check nanmedian when some values only are nan.""" m = stats.stats.nanmedian(self.Xsome) assert_approx_equal(m, stats.stats.median(self.Xsomet)) - def check_nanmedian_all(self): + def test_nanmedian_all(self): """Check nanmedian when all values are nan.""" m = stats.stats.nanmedian(self.Xall) assert numpy.isnan(m) -class TestCorr(NumpyTestCase): +class TestCorr(TestCase): """ W.II.D. Compute a correlation matrix on all the variables. All the correlations, except for ZERO and MISS, shoud be exactly 1. @@ -250,172 +248,172 @@ other variables. The same should go for SPEARMAN corelations, if your program has them. """ - def check_pXX(self): - y = scipy.stats.pearsonr(X,X) + def test_pXX(self): + y = stats.pearsonr(X,X) r = y[0] assert_approx_equal(r,1.0) - def check_pXBIG(self): - y = scipy.stats.pearsonr(X,BIG) + def test_pXBIG(self): + y = stats.pearsonr(X,BIG) r = y[0] assert_approx_equal(r,1.0) - def check_pXLITTLE(self): - y = scipy.stats.pearsonr(X,LITTLE) + def test_pXLITTLE(self): + y = stats.pearsonr(X,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_pXHUGE(self): - y = scipy.stats.pearsonr(X,HUGE) + def test_pXHUGE(self): + y = stats.pearsonr(X,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_pXTINY(self): - y = scipy.stats.pearsonr(X,TINY) + def test_pXTINY(self): + y = stats.pearsonr(X,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pXROUND(self): - y = scipy.stats.pearsonr(X,ROUND) + def test_pXROUND(self): + y = stats.pearsonr(X,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGBIG(self): - y = scipy.stats.pearsonr(BIG,BIG) + def test_pBIGBIG(self): + y = stats.pearsonr(BIG,BIG) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGLITTLE(self): - y = scipy.stats.pearsonr(BIG,LITTLE) + def test_pBIGLITTLE(self): + y = stats.pearsonr(BIG,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGHUGE(self): - y = scipy.stats.pearsonr(BIG,HUGE) + def test_pBIGHUGE(self): + y = stats.pearsonr(BIG,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGTINY(self): - y = scipy.stats.pearsonr(BIG,TINY) + def test_pBIGTINY(self): + y = stats.pearsonr(BIG,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pBIGROUND(self): - y = scipy.stats.pearsonr(BIG,ROUND) + def test_pBIGROUND(self): + y = stats.pearsonr(BIG,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pLITTLELITTLE(self): - y = scipy.stats.pearsonr(LITTLE,LITTLE) + def test_pLITTLELITTLE(self): + y = stats.pearsonr(LITTLE,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_pLITTLEHUGE(self): - y = scipy.stats.pearsonr(LITTLE,HUGE) + def test_pLITTLEHUGE(self): + y = stats.pearsonr(LITTLE,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_pLITTLETINY(self): - y = scipy.stats.pearsonr(LITTLE,TINY) + def test_pLITTLETINY(self): + y = stats.pearsonr(LITTLE,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pLITTLEROUND(self): - y = scipy.stats.pearsonr(LITTLE,ROUND) + def test_pLITTLEROUND(self): + y = stats.pearsonr(LITTLE,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pHUGEHUGE(self): - y = scipy.stats.pearsonr(HUGE,HUGE) + def test_pHUGEHUGE(self): + y = stats.pearsonr(HUGE,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_pHUGETINY(self): - y = scipy.stats.pearsonr(HUGE,TINY) + def test_pHUGETINY(self): + y = stats.pearsonr(HUGE,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pHUGEROUND(self): - y = scipy.stats.pearsonr(HUGE,ROUND) + def test_pHUGEROUND(self): + y = stats.pearsonr(HUGE,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pTINYTINY(self): - y = scipy.stats.pearsonr(TINY,TINY) + def test_pTINYTINY(self): + y = stats.pearsonr(TINY,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_pTINYROUND(self): - y = scipy.stats.pearsonr(TINY,ROUND) + def test_pTINYROUND(self): + y = stats.pearsonr(TINY,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_pROUNDROUND(self): - y = scipy.stats.pearsonr(ROUND,ROUND) + def test_pROUNDROUND(self): + y = stats.pearsonr(ROUND,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sXX(self): - y = scipy.stats.spearmanr(X,X) + def test_sXX(self): + y = stats.spearmanr(X,X) r = y[0] assert_approx_equal(r,1.0) - def check_sXBIG(self): - y = scipy.stats.spearmanr(X,BIG) + def test_sXBIG(self): + y = stats.spearmanr(X,BIG) r = y[0] assert_approx_equal(r,1.0) - def check_sXLITTLE(self): - y = scipy.stats.spearmanr(X,LITTLE) + def test_sXLITTLE(self): + y = stats.spearmanr(X,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_sXHUGE(self): - y = scipy.stats.spearmanr(X,HUGE) + def test_sXHUGE(self): + y = stats.spearmanr(X,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_sXTINY(self): - y = scipy.stats.spearmanr(X,TINY) + def test_sXTINY(self): + y = stats.spearmanr(X,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sXROUND(self): - y = scipy.stats.spearmanr(X,ROUND) + def test_sXROUND(self): + y = stats.spearmanr(X,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGBIG(self): - y = scipy.stats.spearmanr(BIG,BIG) + def test_sBIGBIG(self): + y = stats.spearmanr(BIG,BIG) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGLITTLE(self): - y = scipy.stats.spearmanr(BIG,LITTLE) + def test_sBIGLITTLE(self): + y = stats.spearmanr(BIG,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGHUGE(self): - y = scipy.stats.spearmanr(BIG,HUGE) + def test_sBIGHUGE(self): + y = stats.spearmanr(BIG,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGTINY(self): - y = scipy.stats.spearmanr(BIG,TINY) + def test_sBIGTINY(self): + y = stats.spearmanr(BIG,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sBIGROUND(self): - y = scipy.stats.spearmanr(BIG,ROUND) + def test_sBIGROUND(self): + y = stats.spearmanr(BIG,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sLITTLELITTLE(self): - y = scipy.stats.spearmanr(LITTLE,LITTLE) + def test_sLITTLELITTLE(self): + y = stats.spearmanr(LITTLE,LITTLE) r = y[0] assert_approx_equal(r,1.0) - def check_sLITTLEHUGE(self): - y = scipy.stats.spearmanr(LITTLE,HUGE) + def test_sLITTLEHUGE(self): + y = stats.spearmanr(LITTLE,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_sLITTLETINY(self): - y = scipy.stats.spearmanr(LITTLE,TINY) + def test_sLITTLETINY(self): + y = stats.spearmanr(LITTLE,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sLITTLEROUND(self): - y = scipy.stats.spearmanr(LITTLE,ROUND) + def test_sLITTLEROUND(self): + y = stats.spearmanr(LITTLE,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sHUGEHUGE(self): - y = scipy.stats.spearmanr(HUGE,HUGE) + def test_sHUGEHUGE(self): + y = stats.spearmanr(HUGE,HUGE) r = y[0] assert_approx_equal(r,1.0) - def check_sHUGETINY(self): - y = scipy.stats.spearmanr(HUGE,TINY) + def test_sHUGETINY(self): + y = stats.spearmanr(HUGE,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sHUGEROUND(self): - y = scipy.stats.spearmanr(HUGE,ROUND) + def test_sHUGEROUND(self): + y = stats.spearmanr(HUGE,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sTINYTINY(self): - y = scipy.stats.spearmanr(TINY,TINY) + def test_sTINYTINY(self): + y = stats.spearmanr(TINY,TINY) r = y[0] assert_approx_equal(r,1.0) - def check_sTINYROUND(self): - y = scipy.stats.spearmanr(TINY,ROUND) + def test_sTINYROUND(self): + y = stats.spearmanr(TINY,ROUND) r = y[0] assert_approx_equal(r,1.0) - def check_sROUNDROUND(self): - y = scipy.stats.spearmanr(ROUND,ROUND) + def test_sROUNDROUND(self): + y = stats.spearmanr(ROUND,ROUND) r = y[0] assert_approx_equal(r,1.0) @@ -429,13 +427,13 @@ ### I need to figure out how to do this one. -class TestRegression(NumpyTestCase): - def check_linregressBIGX(self): +class TestRegression(TestCase): + def test_linregressBIGX(self): """ W.II.F. Regress BIG on X. The constant should be 99999990 and the regression coefficient should be 1. """ - y = scipy.stats.linregress(X,BIG) + y = stats.linregress(X,BIG) intercept = y[1] r=y[2] assert_almost_equal(intercept,99999990) @@ -453,13 +451,13 @@ ## The datasets X1 . . X9 are at the top of the file. - def check_regressXX(self): + def test_regressXX(self): """ W.IV.B. Regress X on X. The constant should be exactly 0 and the regression coefficient should be 1. This is a perfectly valid regression. The program should not complain. """ - y = scipy.stats.linregress(X,X) + y = stats.linregress(X,X) intercept = y[1] r=y[2] assert_almost_equal(intercept,0.0) @@ -471,14 +469,14 @@ ## fundamental regression error. ### Need to figure out how to handle multiple linear regression. Not obvious - def check_regressZEROX(self): + def test_regressZEROX(self): """ W.IV.D. Regress ZERO on X. The program should inform you that ZERO has no variance or it should go ahead and compute the regression and report a correlation and total sum of squares of exactly 0. """ - y = scipy.stats.linregress(X,ZERO) + y = stats.linregress(X,ZERO) intercept = y[1] r=y[2] assert_almost_equal(intercept,0.0) @@ -494,9 +492,9 @@ ################################################## ### Test for sum -class TestGMean(NumpyTestCase): +class TestGMean(TestCase): - def check_1D_list(self): + def test_1D_list(self): a = (1,2,3,4) actual= stats.gmean(a) desired = power(1*2*3*4,1./4.) @@ -505,7 +503,7 @@ desired1 = stats.gmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=14) - def check_1D_array(self): + def test_1D_array(self): a = array((1,2,3,4), float32) actual= stats.gmean(a) desired = power(1*2*3*4,1./4.) @@ -514,7 +512,7 @@ desired1 = stats.gmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=7) - def check_2D_array_default(self): + def test_2D_array_default(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) @@ -525,7 +523,7 @@ desired1 = stats.gmean(a,axis=0) assert_array_almost_equal(actual, desired1, decimal=14) - def check_2D_array_dim1(self): + def test_2D_array_dim1(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) @@ -534,13 +532,13 @@ desired = array((v,v,v)) assert_array_almost_equal(actual, desired, decimal=14) - def check_large_values(self): + def test_large_values(self): a = array([1e100, 1e200, 1e300]) actual = stats.gmean(a) assert_approx_equal(actual, 1e200, significant=14) -class TestHMean(NumpyTestCase): - def check_1D_list(self): +class TestHMean(TestCase): + def test_1D_list(self): a = (1,2,3,4) actual= stats.hmean(a) desired = 4. / (1./1 + 1./2 + 1./3 + 1./4) @@ -548,7 +546,7 @@ desired1 = stats.hmean(array(a),axis=-1) assert_almost_equal(actual, desired1, decimal=14) - def check_1D_array(self): + def test_1D_array(self): a = array((1,2,3,4), float64) actual= stats.hmean(a) desired = 4. / (1./1 + 1./2 + 1./3 + 1./4) @@ -557,7 +555,7 @@ desired1 = stats.hmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=14) - def check_2D_array_default(self): + def test_2D_array_default(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) @@ -568,7 +566,7 @@ actual1 = stats.hmean(a,axis=0) assert_array_almost_equal(actual1, desired, decimal=14) - def check_2D_array_dim1(self): + def test_2D_array_dim1(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) @@ -579,8 +577,8 @@ assert_array_almost_equal(actual1, desired1, decimal=14) -class TestMean(NumpyTestCase): - def check_basic(self): +class TestMean(TestCase): + def test_basic(self): a = [3,4,5,10,-3,-5,6] af = [3.,4,5,10,-3,-5,-6] Na = len(a) @@ -594,7 +592,7 @@ mn2 += el / float(Naf) assert_almost_equal(stats.mean(af),mn2,11) - def check_2d(self): + def test_2d(self): a = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [8.0, 12.0, 7.0]] @@ -611,15 +609,15 @@ mn2 /= N2 assert_almost_equal(stats.mean(a, axis=1), mn2, decimal=13) - def check_ravel(self): + def test_ravel(self): a = rand(5,3,5) A = 0 for val in ravel(a): A += val assert_almost_equal(stats.mean(a,axis=None),A/(5*3.0*5)) -class TestMedian(NumpyTestCase): - def check_basic(self): +class TestMedian(TestCase): + def test_basic(self): a1 = [3,4,5,10,-3,-5,6] a2 = [3,-6,-2,8,7,4,2,1] a3 = [3.,4,5,10,-3,-5,-6,7.0] @@ -627,18 +625,18 @@ assert_equal(stats.median(a2),2.5) assert_equal(stats.median(a3),3.5) -class TestPercentile(NumpyTestCase): +class TestPercentile(TestCase): def setUp(self): self.a1 = [3,4,5,10,-3,-5,6] self.a2 = [3,-6,-2,8,7,4,2,1] self.a3 = [3.,4,5,10,-3,-5,-6,7.0] - def check_median(self): + def test_median(self): assert_equal(stats.median(self.a1), 4) assert_equal(stats.median(self.a2), 2.5) assert_equal(stats.median(self.a3), 3.5) - def check_percentile(self): + def test_percentile(self): x = arange(8) * 0.5 assert_equal(stats.scoreatpercentile(x, 0), 0.) assert_equal(stats.scoreatpercentile(x, 100), 3.5) @@ -654,14 +652,14 @@ [1,1,1]) -class TestStd(NumpyTestCase): - def check_basic(self): +class TestStd(TestCase): + def test_basic(self): a = [3,4,5,10,-3,-5,6] b = [3,4,5,10,-3,-5,-6] assert_almost_equal(stats.std(a),5.2098807225172772,11) assert_almost_equal(stats.std(b),5.9281411203561225,11) - def check_2d(self): + def test_2d(self): a = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [8.0, 12.0, 7.0]] @@ -673,109 +671,109 @@ assert_array_almost_equal(stats.std(a,axis=1),b2,11) -class TestCMedian(NumpyTestCase): - def check_basic(self): +class TestCMedian(TestCase): + def test_basic(self): data = [1,2,3,1,5,3,6,4,3,2,4,3,5,2.0] assert_almost_equal(stats.cmedian(data,5),3.2916666666666665) assert_almost_equal(stats.cmedian(data,3),3.083333333333333) assert_almost_equal(stats.cmedian(data),3.0020020020020022) -class TestMedian(NumpyTestCase): - def check_basic(self): +class TestMedian(TestCase): + def test_basic(self): data1 = [1,3,5,2,3,1,19,-10,2,4.0] data2 = [3,5,1,10,23,-10,3,-2,6,8,15] assert_almost_equal(stats.median(data1),2.5) assert_almost_equal(stats.median(data2),5) -class TestMode(NumpyTestCase): - def check_basic(self): +class TestMode(TestCase): + def test_basic(self): data1 = [3,5,1,10,23,3,2,6,8,6,10,6] vals = stats.mode(data1) assert_almost_equal(vals[0][0],6) assert_almost_equal(vals[1][0],3) -class TestVariability(NumpyTestCase): +class TestVariability(TestCase): """ Comparison numbers are found using R v.1.5.1 note that length(testcase) = 4 """ testcase = [1,2,3,4] - def check_std(self): - y = scipy.stats.std(self.testcase) + def test_std(self): + y = stats.std(self.testcase) assert_approx_equal(y,1.290994449) - def check_var(self): + def test_var(self): """ var(testcase) = 1.666666667 """ - #y = scipy.stats.var(self.shoes[0]) + #y = stats.var(self.shoes[0]) #assert_approx_equal(y,6.009) - y = scipy.stats.var(self.testcase) + y = stats.var(self.testcase) assert_approx_equal(y,1.666666667) - def check_samplevar(self): + def test_samplevar(self): """ R does not have 'samplevar' so the following was used var(testcase)*(4-1)/4 where 4 = length(testcase) """ - #y = scipy.stats.samplevar(self.shoes[0]) + #y = stats.samplevar(self.shoes[0]) #assert_approx_equal(y,5.4081) - y = scipy.stats.samplevar(self.testcase) + y = stats.samplevar(self.testcase) assert_approx_equal(y,1.25) - def check_samplestd(self): - #y = scipy.stats.samplestd(self.shoes[0]) + def test_samplestd(self): + #y = stats.samplestd(self.shoes[0]) #assert_approx_equal(y,2.325532197) - y = scipy.stats.samplestd(self.testcase) + y = stats.samplestd(self.testcase) assert_approx_equal(y,1.118033989) - def check_signaltonoise(self): + def test_signaltonoise(self): """ this is not in R, so used mean(testcase,axis=0)/(sqrt(var(testcase)*3/4)) """ - #y = scipy.stats.signaltonoise(self.shoes[0]) + #y = stats.signaltonoise(self.shoes[0]) #assert_approx_equal(y,4.5709967) - y = scipy.stats.signaltonoise(self.testcase) + y = stats.signaltonoise(self.testcase) assert_approx_equal(y,2.236067977) - def check_stderr(self): + def test_stderr(self): """ this is not in R, so used sqrt(var(testcase))/sqrt(4) """ -## y = scipy.stats.stderr(self.shoes[0]) +## y = stats.stderr(self.shoes[0]) ## assert_approx_equal(y,0.775177399) - y = scipy.stats.stderr(self.testcase) + y = stats.stderr(self.testcase) assert_approx_equal(y,0.6454972244) - def check_sem(self): + def test_sem(self): """ this is not in R, so used sqrt(var(testcase)*3/4)/sqrt(3) """ - #y = scipy.stats.sem(self.shoes[0]) + #y = stats.sem(self.shoes[0]) #assert_approx_equal(y,0.775177399) - y = scipy.stats.sem(self.testcase) + y = stats.sem(self.testcase) assert_approx_equal(y,0.6454972244) - def check_z(self): + def test_z(self): """ not in R, so used (10-mean(testcase,axis=0))/sqrt(var(testcase)*3/4) """ - y = scipy.stats.z(self.testcase,scipy.stats.mean(self.testcase)) + y = stats.z(self.testcase,stats.mean(self.testcase)) assert_almost_equal(y,0.0) - def check_zs(self): + def test_zs(self): """ not in R, so tested by using (testcase[i]-mean(testcase,axis=0))/sqrt(var(testcase)*3/4) """ - y = scipy.stats.zs(self.testcase) + y = stats.zs(self.testcase) desired = ([-1.3416407864999, -0.44721359549996 , 0.44721359549996 , 1.3416407864999]) assert_array_almost_equal(desired,y,decimal=12) -class TestMoments(NumpyTestCase): +class TestMoments(TestCase): """ Comparison numbers are found using R v.1.5.1 note that length(testcase) = 4 @@ -787,56 +785,56 @@ """ testcase = [1,2,3,4] testmathworks = [1.165 , 0.6268, 0.0751, 0.3516, -0.6965] - def check_moment(self): + def test_moment(self): """ mean((testcase-mean(testcase))**power,axis=0),axis=0))**power))""" - y = scipy.stats.moment(self.testcase,1) + y = stats.moment(self.testcase,1) assert_approx_equal(y,0.0,10) - y = scipy.stats.moment(self.testcase,2) + y = stats.moment(self.testcase,2) assert_approx_equal(y,1.25) - y = scipy.stats.moment(self.testcase,3) + y = stats.moment(self.testcase,3) assert_approx_equal(y,0.0) - y = scipy.stats.moment(self.testcase,4) + y = stats.moment(self.testcase,4) assert_approx_equal(y,2.5625) - def check_variation(self): + def test_variation(self): """ variation = samplestd/mean """ -## y = scipy.stats.variation(self.shoes[0]) +## y = stats.variation(self.shoes[0]) ## assert_approx_equal(y,21.8770668) - y = scipy.stats.variation(self.testcase) + y = stats.variation(self.testcase) assert_approx_equal(y,0.44721359549996, 10) - def check_skewness(self): + def test_skewness(self): """ sum((testmathworks-mean(testmathworks,axis=0))**3,axis=0)/((sqrt(var(testmathworks)*4/5))**3)/5 """ - y = scipy.stats.skew(self.testmathworks) + y = stats.skew(self.testmathworks) assert_approx_equal(y,-0.29322304336607,10) - y = scipy.stats.skew(self.testmathworks,bias=0) + y = stats.skew(self.testmathworks,bias=0) assert_approx_equal(y,-0.437111105023940,10) - y = scipy.stats.skew(self.testcase) + y = stats.skew(self.testcase) assert_approx_equal(y,0.0,10) - def check_kurtosis(self): + def test_kurtosis(self): """ sum((testcase-mean(testcase,axis=0))**4,axis=0)/((sqrt(var(testcase)*3/4))**4)/4 sum((test2-mean(testmathworks,axis=0))**4,axis=0)/((sqrt(var(testmathworks)*4/5))**4)/5 Set flags for axis = 0 and fisher=0 (Pearson's defn of kurtosis for compatiability with Matlab) """ - y = scipy.stats.kurtosis(self.testmathworks,0,fisher=0,bias=1) + y = stats.kurtosis(self.testmathworks,0,fisher=0,bias=1) assert_approx_equal(y, 2.1658856802973,10) # Note that MATLAB has confusing docs for the following case # kurtosis(x,0) gives an unbiased estimate of Pearson's skewness # kurtosis(x) gives a biased estimate of Fisher's skewness (Pearson-3) # The MATLAB docs imply that both should give Fisher's - y = scipy.stats.kurtosis(self.testmathworks,fisher=0,bias=0) + y = stats.kurtosis(self.testmathworks,fisher=0,bias=0) assert_approx_equal(y, 3.663542721189047,10) - y = scipy.stats.kurtosis(self.testcase,0,0) + y = stats.kurtosis(self.testcase,0,0) assert_approx_equal(y,1.64) -class TestThreshold(NumpyTestCase): - def check_basic(self): +class TestThreshold(TestCase): + def test_basic(self): a = [-1,2,3,4,5,-1,-2] assert_array_equal(stats.threshold(a),a) assert_array_equal(stats.threshold(a,3,None,0), @@ -847,4 +845,4 @@ [0,2,3,4,0,0,0]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/testing/nosetester.py =================================================================== --- trunk/scipy/testing/nosetester.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/testing/nosetester.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -17,7 +17,7 @@ package = f.f_locals.get('__file__', None) assert package is not None package = os.path.dirname(package) - else isinstance(package, type(os)): + elif isinstance(package, type(os)): package = os.path.dirname(package.__file__) self.package_path = package Modified: trunk/scipy/weave/__init__.py =================================================================== --- trunk/scipy/weave/__init__.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/__init__.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -18,5 +18,5 @@ except: pass -from numpy.testing import NumpyTest -test = NumpyTest().test +from scipy.testing.pkgtester import Tester +test = Tester().test Modified: trunk/scipy/weave/c_spec.py =================================================================== --- trunk/scipy/weave/c_spec.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/c_spec.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -455,10 +455,6 @@ def type_match(self,value): return 1 -def test(level=10,verbosity=1): - from numpy.testing import NumpyTest - NumpyTest().test(level, verbosity) - if __name__ == "__main__": x = list_converter().type_spec("x",1) print x.py_to_c_code() Modified: trunk/scipy/weave/size_check.py =================================================================== --- trunk/scipy/weave/size_check.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/size_check.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -279,5 +279,3 @@ def take(ary,axis=0): raise NotImplemented # and all the rest -#from numpy.testing import NumpyTest -#test = NumpyTest().test Modified: trunk/scipy/weave/tests/test_ast_tools.py =================================================================== --- trunk/scipy/weave/tests/test_ast_tools.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_ast_tools.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,31 +1,29 @@ +from scipy.testing import * -from numpy.testing import * -set_package_path() -from weave import ast_tools -restore_path() +from scipy.weave import ast_tools set_local_path() from weave_test_utils import * restore_path() -class TestHarvestVariables(NumpyTestCase): +class TestHarvestVariables(TestCase): """ Not much testing going on here, but at least it is a flame test. """ - def generic_test(self,expr,desired): + def generic_check(self,expr,desired): import parser ast_list = parser.suite(expr).tolist() actual = ast_tools.harvest_variables(ast_list) print_assert_equal(expr,actual,desired) - def check_simple_expr(self): + def test_simple_expr(self): """convert simple expr to blitz a[:1:2] = b[:1+i+2:] """ expr = "a[:1:2] = b[:1+i+2:]" desired = ['a','b','i'] - self.generic_test(expr,desired) + self.generic_check(expr,desired) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_blitz_tools.py =================================================================== --- trunk/scipy/weave/tests/test_blitz_tools.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_blitz_tools.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,22 +1,22 @@ import os import time -from numpy import * +from numpy import dot, float32, float64, complex64, complex128, \ + zeros, random, array, sum, abs, allclose -from numpy.testing import * -set_package_path() -from weave import blitz_tools -from weave.ast_tools import harvest_variables -restore_path() +from scipy.testing import * +from scipy.weave import blitz_tools +from scipy.weave.ast_tools import harvest_variables + set_local_path() from weave_test_utils import * restore_path() -class TestAstToBlitzExpr(NumpyTestCase): +class TestAstToBlitzExpr(TestCase): - def generic_test(self,expr,desired): + def generic_check(self,expr,desired): import parser ast = parser.suite(expr) ast_list = ast.tolist() @@ -25,7 +25,7 @@ desired = remove_whitespace(desired) print_assert_equal(expr,actual,desired) - def check_simple_expr(self): + def test_simple_expr(self): """convert simple expr to blitz a[:1:2] = b[:1+i+2:] @@ -33,9 +33,9 @@ expr = "a[:1:2] = b[:1+i+2:]" desired = "a(blitz::Range(_beg,1-1,2))="\ "b(blitz::Range(_beg,1+i+2-1));" - self.generic_test(expr,desired) + self.generic_check(expr,desired) - def check_fdtd_expr(self): + def test_fdtd_expr(self): """ convert fdtd equation to blitz. ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:] + cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:]) @@ -55,14 +55,14 @@ ' -cb_z_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\ '*(hy(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\ '-hy(_all,blitz::Range(1,_end),blitz::Range(_beg,Nhy(2)-1-1)));' - self.generic_test(expr,desired) + self.generic_check(expr,desired) -class TestBlitz(NumpyTestCase): +class TestBlitz(TestCase): """* These are long running tests... I'd like to benchmark these things somehow. *""" - def generic_test(self,expr,arg_dict,type,size,mod_location): + def generic_check(self,expr,arg_dict,type,size,mod_location): clean_result = array(arg_dict['result'],copy=1) t1 = time.time() exec expr in globals(),arg_dict @@ -113,7 +113,7 @@ try: arg_dict[arg].imag = arg_dict[arg].real except: pass print 'Run:', size,typ - standard,compiled = self.generic_test(expr,arg_dict,type,size, + standard,compiled = self.generic_check(expr,arg_dict,type,size, mod_location) try: speed_up = standard/compiled @@ -121,7 +121,7 @@ speed_up = -1. print "1st run(numpy.numerix,compiled,speed up): %3.4f, %3.4f, " \ "%3.4f" % (standard,compiled,speed_up) - standard,compiled = self.generic_test(expr,arg_dict,type,size, + standard,compiled = self.generic_check(expr,arg_dict,type,size, mod_location) try: speed_up = standard/compiled @@ -130,25 +130,30 @@ print "2nd run(numpy.numerix,compiled,speed up): %3.4f, %3.4f, " \ "%3.4f" % (standard,compiled,speed_up) cleanup_temp_dir(mod_location) - #def check_simple_2d(self): + #def test_simple_2d(self): # """ result = a + b""" # expr = "result = a + b" # self.generic_2d(expr) - def check_5point_avg_2d_float(self,level=10): + @dec.slow + def test_5point_avg_2d_float(self): """ result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1] + b[1:-1,2:] + b[1:-1,:-2]) / 5. """ expr = "result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]" \ "+ b[1:-1,2:] + b[1:-1,:-2]) / 5." self.generic_2d(expr,float32) - def check_5point_avg_2d_double(self,level=10): + + @dec.slow + def test_5point_avg_2d_double(self): """ result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1] + b[1:-1,2:] + b[1:-1,:-2]) / 5. """ expr = "result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]" \ "+ b[1:-1,2:] + b[1:-1,:-2]) / 5." self.generic_2d(expr,float64) - def _check_5point_avg_2d_complex_float(self,level=10): + + @dec.slow + def _check_5point_avg_2d_complex_float(self): """ Note: THIS TEST is KNOWN TO FAIL ON GCC 3.x. It will not adversely affect 99.99 percent of weave result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1] @@ -165,7 +170,9 @@ expr = "result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]" \ "+ b[1:-1,2:] + b[1:-1,:-2]) / 5." self.generic_2d(expr,complex64) - def check_5point_avg_2d_complex_double(self,level=10): + + @dec.slow + def test_5point_avg_2d_complex_double(self): """ result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1] + b[1:-1,2:] + b[1:-1,:-2]) / 5. """ @@ -174,4 +181,4 @@ self.generic_2d(expr,complex128) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_build_tools.py =================================================================== --- trunk/scipy/weave/tests/test_build_tools.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_build_tools.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,34 +4,33 @@ import os, sys, tempfile -from numpy.testing import * -set_package_path() -from weave import build_tools -restore_path() +from scipy.testing import * +from scipy.weave import build_tools + def is_writable(val): return os.access(val,os.W_OK) -class TestConfigureBuildDir(NumpyTestCase): - def check_default(self): +class TestConfigureBuildDir(TestCase): + def test_default(self): " default behavior is to return current directory " d = build_tools.configure_build_dir() if is_writable('.'): assert(d == os.path.abspath('.')) assert(is_writable(d)) - def check_curdir(self): + def test_curdir(self): " make sure it handles relative values. " d = build_tools.configure_build_dir('.') if is_writable('.'): assert(d == os.path.abspath('.')) assert(is_writable(d)) - def check_pardir(self): + def test_pardir(self): " make sure it handles relative values " d = build_tools.configure_build_dir('..') if is_writable('..'): assert(d == os.path.abspath('..')) assert(is_writable(d)) - def check_bad_path(self): + def test_bad_path(self): " bad path should return same as default (and warn) " d = build_tools.configure_build_dir('_bad_path_') d2 = build_tools.configure_build_dir() @@ -39,15 +38,15 @@ assert(is_writable(d)) class TestConfigureTempDir(TestConfigureBuildDir): - def check_default(self): + def test_default(self): " default behavior returns tempdir" # this'll fail if the temp directory isn't writable. d = build_tools.configure_temp_dir() assert(d == tempfile.gettempdir()) assert(is_writable(d)) -class TestConfigureSysArgv(NumpyTestCase): - def check_simple(self): +class TestConfigureSysArgv(TestCase): + def test_simple(self): build_dir = 'build_dir' temp_dir = 'temp_dir' compiler = 'compiler' @@ -63,4 +62,4 @@ assert(pre_argv == sys.argv[:]) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_c_spec.py =================================================================== --- trunk/scipy/weave/tests/test_c_spec.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_c_spec.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -3,19 +3,17 @@ import sys # Note: test_dir is global to this file. -# It is made by setup_test_location() +# It is made by setup_location() #globals global test_dir test_dir = '' -from numpy.testing import * -set_package_path() -from weave import inline_tools,ext_tools,c_spec -from weave.build_tools import msvc_exists, gcc_exists -from weave.catalog import unique_file -restore_path() +from scipy.testing import * +from scipy.weave import inline_tools,ext_tools,c_spec +from scipy.weave.build_tools import msvc_exists, gcc_exists +from scipy.weave.catalog import unique_file def unique_mod(d,file_name): @@ -66,21 +64,26 @@ # compilers.append(c) -class IntConverter(NumpyTestCase): +class IntConverter(TestCase): compiler = '' - def check_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): s = c_spec.int_converter() assert( not s.type_match('string') ) - def check_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): s = c_spec.int_converter() assert(s.type_match(5)) - def check_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): s = c_spec.int_converter() assert(not s.type_match(5.)) - def check_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): s = c_spec.int_converter() assert(not s.type_match(5.+1j)) - def check_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'int_var_in' + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -103,7 +106,8 @@ except TypeError: pass - def check_int_return(self,level=5): + @dec.slow + def test_int_return(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -121,21 +125,26 @@ assert( c == 3) -class FloatConverter(NumpyTestCase): +class FloatConverter(TestCase): compiler = '' - def check_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): s = c_spec.float_converter() assert( not s.type_match('string')) - def check_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): s = c_spec.float_converter() assert(not s.type_match(5)) - def check_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): s = c_spec.float_converter() assert(s.type_match(5.)) - def check_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): s = c_spec.float_converter() assert(not s.type_match(5.+1j)) - def check_float_var_in(self,level=5): + @dec.slow + def test_float_var_in(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -159,7 +168,8 @@ pass - def check_float_return(self,level=5): + @dec.slow + def test_float_return(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -176,21 +186,26 @@ c = test(b) assert( c == 3.) -class ComplexConverter(NumpyTestCase): +class ComplexConverter(TestCase): compiler = '' - def check_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): s = c_spec.complex_converter() assert( not s.type_match('string') ) - def check_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): s = c_spec.complex_converter() assert(not s.type_match(5)) - def check_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): s = c_spec.complex_converter() assert(not s.type_match(5.)) - def check_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): s = c_spec.complex_converter() assert(s.type_match(5.+1j)) - def check_complex_var_in(self,level=5): + @dec.slow + def test_complex_var_in(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -213,7 +228,8 @@ except TypeError: pass - def check_complex_return(self,level=5): + @dec.slow + def test_complex_return(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -234,9 +250,10 @@ # File conversion tests #---------------------------------------------------------------------------- -class FileConverter(NumpyTestCase): +class FileConverter(TestCase): compiler = '' - def check_py_to_file(self,level=5): + @dec.slow + def test_py_to_file(self): import tempfile file_name = tempfile.mktemp() file = open(file_name,'w') @@ -247,7 +264,8 @@ file.close() file = open(file_name,'r') assert(file.read() == "hello bob") - def check_file_to_py(self,level=5): + @dec.slow + def test_file_to_py(self): import tempfile file_name = tempfile.mktemp() # not sure I like Py::String as default -- might move to std::sting @@ -268,16 +286,17 @@ # Instance conversion tests #---------------------------------------------------------------------------- -class InstanceConverter(NumpyTestCase): +class InstanceConverter(TestCase): pass #---------------------------------------------------------------------------- # Callable object conversion tests #---------------------------------------------------------------------------- -class CallableConverter(NumpyTestCase): +class CallableConverter(TestCase): compiler='' - def check_call_function(self,level=5): + @dec.slow + def test_call_function(self): import string func = string.find search_str = "hello world hello" @@ -295,36 +314,45 @@ desired = func(search_str,sub_str) assert(desired == actual) -class SequenceConverter(NumpyTestCase): +class SequenceConverter(TestCase): compiler = '' - def check_convert_to_dict(self,level=5): + @dec.slow + def test_convert_to_dict(self): d = {} inline_tools.inline("",['d'],compiler=self.compiler,force=1) - def check_convert_to_list(self,level=5): + @dec.slow + def test_convert_to_list(self): l = [] inline_tools.inline("",['l'],compiler=self.compiler,force=1) - def check_convert_to_string(self,level=5): + @dec.slow + def test_convert_to_string(self): s = 'hello' inline_tools.inline("",['s'],compiler=self.compiler,force=1) - def check_convert_to_tuple(self,level=5): + @dec.slow + def test_convert_to_tuple(self): t = () inline_tools.inline("",['t'],compiler=self.compiler,force=1) -class StringConverter(NumpyTestCase): +class StringConverter(TestCase): compiler = '' - def check_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): s = c_spec.string_converter() assert( s.type_match('string') ) - def check_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): s = c_spec.string_converter() assert(not s.type_match(5)) - def check_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): s = c_spec.string_converter() assert(not s.type_match(5.)) - def check_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): s = c_spec.string_converter() assert(not s.type_match(5.+1j)) - def check_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'string_var_in'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -348,7 +376,8 @@ except TypeError: pass - def check_return(self,level=5): + @dec.slow + def test_return(self): mod_name = 'string_return'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -365,17 +394,20 @@ c = test(b) assert( c == 'hello') -class ListConverter(NumpyTestCase): +class ListConverter(TestCase): compiler = '' - def check_type_match_bad(self,level=5): + @dec.slow + def test_type_match_bad(self): s = c_spec.list_converter() objs = [{},(),'',1,1.,1+1j] for i in objs: assert( not s.type_match(i) ) - def check_type_match_good(self,level=5): + @dec.slow + def test_type_match_good(self): s = c_spec.list_converter() assert(s.type_match([])) - def check_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'list_var_in'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -398,7 +430,8 @@ except TypeError: pass - def check_return(self,level=5): + @dec.slow + def test_return(self): mod_name = 'list_return'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -416,7 +449,8 @@ c = test(b) assert( c == ['hello']) - def check_speed(self,level=5): + @dec.slow + def test_speed(self): mod_name = 'list_speed'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -476,17 +510,20 @@ print 'python:', t2 - t1 assert( sum1 == sum2 and sum1 == sum3) -class TupleConverter(NumpyTestCase): +class TupleConverter(TestCase): compiler = '' - def check_type_match_bad(self,level=5): + @dec.slow + def test_type_match_bad(self): s = c_spec.tuple_converter() objs = [{},[],'',1,1.,1+1j] for i in objs: assert( not s.type_match(i) ) - def check_type_match_good(self,level=5): + @dec.slow + def test_type_match_good(self): s = c_spec.tuple_converter() assert(s.type_match((1,))) - def check_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'tuple_var_in'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -509,7 +546,8 @@ except TypeError: pass - def check_return(self,level=5): + @dec.slow + def test_return(self): mod_name = 'tuple_return'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -529,7 +567,7 @@ assert( c == ('hello',None)) -class DictConverter(NumpyTestCase): +class DictConverter(TestCase): """ Base Class for dictionary conversion tests. """ @@ -539,15 +577,18 @@ # so that it can run on its own. compiler='' - def check_type_match_bad(self,level=5): + @dec.slow + def test_type_match_bad(self): s = c_spec.dict_converter() objs = [[],(),'',1,1.,1+1j] for i in objs: assert( not s.type_match(i) ) - def check_type_match_good(self,level=5): + @dec.slow + def test_type_match_good(self): s = c_spec.dict_converter() assert(s.type_match({})) - def check_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod_name = 'dict_var_in'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -570,7 +611,8 @@ except TypeError: pass - def check_return(self,level=5): + @dec.slow + def test_return(self): mod_name = 'dict_return'+self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -682,7 +724,7 @@ # class TestGccInstanceConverter(TestInstanceConverter): # compiler = 'gcc' -def setup_test_location(): +def setup_location(): import tempfile #test_dir = os.path.join(tempfile.gettempdir(),'test_files') test_dir = tempfile.mktemp() @@ -691,9 +733,9 @@ sys.path.insert(0,test_dir) return test_dir -test_dir = setup_test_location() +test_dir = setup_location() -def teardown_test_location(): +def teardown_location(): import tempfile test_dir = os.path.join(tempfile.gettempdir(),'test_files') if sys.path[0] == test_dir: @@ -715,4 +757,4 @@ # if _n[:7]=='TestGcc': exec 'del '+_n # if __name__ == "__main__": - NumpyTest('weave.c_spec').run() + unittest.main() Modified: trunk/scipy/weave/tests/test_catalog.py =================================================================== --- trunk/scipy/weave/tests/test_catalog.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_catalog.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -2,18 +2,17 @@ import os -from numpy.testing import * -set_package_path() -from weave import catalog -restore_path() +from scipy.testing import * +from scipy.weave import catalog + set_local_path() from weave_test_utils import * restore_path() -class TestDefaultDir(NumpyTestCase): - def check_is_writable(self): +class TestDefaultDir(TestCase): + def test_is_writable(self): path = catalog.default_dir() name = os.path.join(path,'dummy_catalog') test_file = open(name,'w') @@ -23,49 +22,49 @@ test_file.close() os.remove(name) -class TestOsDependentCatalogName(NumpyTestCase): +class TestOsDependentCatalogName(TestCase): pass -class TestCatalogPath(NumpyTestCase): - def check_default(self): +class TestCatalogPath(TestCase): + def test_default(self): in_path = catalog.default_dir() path = catalog.catalog_path(in_path) d,f = os.path.split(path) assert(d == in_path) assert(f == catalog.os_dependent_catalog_name()) - def check_current(self): + def test_current(self): in_path = '.' path = catalog.catalog_path(in_path) d,f = os.path.split(path) assert(d == os.path.abspath(in_path)) assert(f == catalog.os_dependent_catalog_name()) - def check_user(path): + def test_user(path): if sys.platform != 'win32': in_path = '~' path = catalog.catalog_path(in_path) d,f = os.path.split(path) assert(d == os.path.expanduser(in_path)) assert(f == catalog.os_dependent_catalog_name()) - def check_module(self): + def test_module(self): # hand it a module and see if it uses the parent directory # of the module. path = catalog.catalog_path(os.__file__) d,f = os.path.split(os.__file__) d2,f = os.path.split(path) assert (d2 == d) - def check_path(self): + def test_path(self): # use os.__file__ to get a usable directory. in_path,f = os.path.split(os.__file__) path = catalog.catalog_path(in_path) d,f = os.path.split(path) assert (d == in_path) - def check_bad_path(self): + def test_bad_path(self): # stupid_path_name in_path = 'stupid_path_name' path = catalog.catalog_path(in_path) assert (path is None) -class TestGetCatalog(NumpyTestCase): +class TestGetCatalog(TestCase): """ This only tests whether new catalogs are created correctly. And whether non-existent return None correctly with read mode. Putting catalogs in the right place is all tested with @@ -88,18 +87,18 @@ import distutils.dir_util distutils.dir_util.remove_tree(d) - def check_nonexistent_catalog_is_none(self): + def test_nonexistent_catalog_is_none(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'r') self.remove_dir(pardir) assert(cat is None) - def check_create_catalog(self): + def test_create_catalog(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'c') self.remove_dir(pardir) assert(cat is not None) -class TestCatalog(NumpyTestCase): +class TestCatalog(TestCase): def clear_environ(self): if 'PYTHONCOMPILED' in os.environ: @@ -116,46 +115,46 @@ def tearDown(self): self.reset_environ() - def check_set_module_directory(self): + def test_set_module_directory(self): q = catalog.catalog() q.set_module_directory('bob') r = q.get_module_directory() assert (r == 'bob') - def check_clear_module_directory(self): + def test_clear_module_directory(self): q = catalog.catalog() r = q.get_module_directory() assert (r is None) q.set_module_directory('bob') r = q.clear_module_directory() assert (r is None) - def check_get_environ_path(self): + def test_get_environ_path(self): if sys.platform == 'win32': sep = ';' else: sep = ':' os.environ['PYTHONCOMPILED'] = sep.join(('path1','path2','path3')) q = catalog.catalog() path = q.get_environ_path() assert(path == ['path1','path2','path3']) - def check_build_search_order1(self): + def test_build_search_order1(self): """ MODULE in search path should be replaced by module_dir. """ q = catalog.catalog(['first','MODULE','third']) q.set_module_directory('second') order = q.build_search_order() assert(order == ['first','second','third',catalog.default_dir()]) - def check_build_search_order2(self): + def test_build_search_order2(self): """ MODULE in search path should be removed if module_dir==None. """ q = catalog.catalog(['first','MODULE','third']) order = q.build_search_order() assert(order == ['first','third',catalog.default_dir()]) - def check_build_search_order3(self): + def test_build_search_order3(self): """ If MODULE is absent, module_dir shouldn't be in search path. """ q = catalog.catalog(['first','second']) q.set_module_directory('third') order = q.build_search_order() assert(order == ['first','second',catalog.default_dir()]) - def check_build_search_order4(self): + def test_build_search_order4(self): """ Make sure environment variable is getting used. """ q = catalog.catalog(['first','second']) @@ -166,14 +165,14 @@ order = q.build_search_order() assert(order == ['first','second','third','fourth','fifth',catalog.default_dir()]) - def check_catalog_files1(self): + def test_catalog_files1(self): """ Be sure we get at least one file even without specifying the path. """ q = catalog.catalog() files = q.get_catalog_files() assert(len(files) == 1) - def check_catalog_files2(self): + def test_catalog_files2(self): """ Ignore bad paths in the path. """ q = catalog.catalog() @@ -181,7 +180,7 @@ files = q.get_catalog_files() assert(len(files) == 1) - def check_get_existing_files1(self): + def test_get_existing_files1(self): """ Shouldn't get any files when temp doesn't exist and no path set. """ clear_temp_catalog() @@ -189,7 +188,7 @@ files = q.get_existing_files() restore_temp_catalog() assert(len(files) == 0) - def check_get_existing_files2(self): + def test_get_existing_files2(self): """ Shouldn't get a single file from the temp dir. """ clear_temp_catalog() @@ -203,7 +202,7 @@ restore_temp_catalog() assert(len(files) == 1) - def check_access_writable_file(self): + def test_access_writable_file(self): """ There should always be a writable file -- even if it is in temp """ q = catalog.catalog() @@ -214,7 +213,7 @@ finally: f.close() os.remove(file) - def check_writable_with_bad_path(self): + def test_writable_with_bad_path(self): """ There should always be a writable file -- even if search paths contain bad values. """ @@ -229,7 +228,7 @@ finally: f.close() os.remove(file) - def check_writable_dir(self): + def test_writable_dir(self): """ Check that we can create a file in the writable directory """ q = catalog.catalog() @@ -241,7 +240,7 @@ finally: f.close() os.remove(file) - def check_unique_module_name(self): + def test_unique_module_name(self): """ Check that we can create a file in the writable directory """ q = catalog.catalog() @@ -259,7 +258,7 @@ cfile2 = file+'.cpp' assert(not os.path.exists(cfile2+'.cpp')) os.remove(cfile1) - def check_add_function_persistent1(self): + def test_add_function_persistent1(self): """ Test persisting a function in the default catalog """ clear_temp_catalog() @@ -275,7 +274,7 @@ for i in funcs: assert(i in pfuncs) - def check_add_function_ordered(self): + def test_add_function_ordered(self): clear_temp_catalog() q = catalog.catalog() import string @@ -332,4 +331,4 @@ if __name__ == '__main__': - NumpyTest('weave.catalog').run() + unittest.main() Modified: trunk/scipy/weave/tests/test_ext_tools.py =================================================================== --- trunk/scipy/weave/tests/test_ext_tools.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_ext_tools.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,15 +1,15 @@ import time -from numpy.testing import * -set_package_path() -from weave import ext_tools, c_spec +from scipy.testing import * + +from scipy.weave import ext_tools, c_spec try: - from weave.standard_array_spec import array_converter + from scipy.weave.standard_array_spec import array_converter except ImportError: pass # requires numpy.numerix -restore_path() + set_local_path() from weave_test_utils import * restore_path() @@ -17,14 +17,16 @@ build_dir = empty_temp_dir() print 'building extensions here:', build_dir -class TestExtModule(NumpyTestCase): +class TestExtModule(TestCase): #should really do some testing of where modules end up - def check_simple(self,level=5): + @dec.slow + def test_simple(self): """ Simplest possible module """ mod = ext_tools.ext_module('simple_ext_module') mod.compile(location = build_dir) import simple_ext_module - def check_multi_functions(self,level=5): + @dec.slow + def test_multi_functions(self): mod = ext_tools.ext_module('module_multi_function') var_specs = [] code = "" @@ -36,7 +38,8 @@ import module_multi_function module_multi_function.test() module_multi_function.test2() - def check_with_include(self,level=5): + @dec.slow + def test_with_include(self): # decalaring variables a = 2.; @@ -57,7 +60,8 @@ import ext_module_with_include ext_module_with_include.test(a) - def check_string_and_int(self,level=5): + @dec.slow + def test_string_and_int(self): # decalaring variables a = 2;b = 'string' # declare module @@ -73,7 +77,8 @@ c = ext_string_and_int.test(a,b) assert(c == len(b)) - def check_return_tuple(self,level=5): + @dec.slow + def test_return_tuple(self): # decalaring variables a = 2 # declare module @@ -94,9 +99,10 @@ c,d = ext_return_tuple.test(a) assert(c==a and d == a+1) -class TestExtFunction(NumpyTestCase): +class TestExtFunction(TestCase): #should really do some testing of where modules end up - def check_simple(self,level=5): + @dec.slow + def test_simple(self): """ Simplest possible function """ mod = ext_tools.ext_module('simple_ext_function') var_specs = [] @@ -107,8 +113,8 @@ import simple_ext_function simple_ext_function.test() -class TestAssignVariableTypes(NumpyTestCase): - def check_assign_variable_types(self): +class TestAssignVariableTypes(TestCase): + def test_assign_variable_types(self): try: from numpy.numerix import arange, Float32, Float64 except: @@ -135,4 +141,4 @@ print_assert_equal(expr,actual,desired) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_inline_tools.py =================================================================== --- trunk/scipy/weave/tests/test_inline_tools.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_inline_tools.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,20 +1,21 @@ from numpy import * -from numpy.testing import * -set_package_path() -from weave import inline_tools -restore_path() +from scipy.testing import * + +from scipy.weave import inline_tools + set_local_path() from test_scxx import * restore_path() -class TestInline(NumpyTestCase): +class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ - def check_exceptions(self,level=5): + @dec.slow + def test_exceptions(self): a = 3 code = """ if (a < 2) @@ -43,4 +44,4 @@ pass if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_numpy_scalar_spec.py =================================================================== --- trunk/scipy/weave/tests/test_numpy_scalar_spec.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_numpy_scalar_spec.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -10,16 +10,13 @@ test_dir = '' import numpy -from numpy.testing import * -set_package_path() -from weave import inline_tools,ext_tools -from weave.build_tools import msvc_exists, gcc_exists -from weave.catalog import unique_file -from weave.numpy_scalar_spec import numpy_complex_scalar_converter +from scipy.testing import * -restore_path() +from scipy.weave import inline_tools,ext_tools +from scipy.weave.build_tools import msvc_exists, gcc_exists +from scipy.weave.catalog import unique_file +from scipy.weave.numpy_scalar_spec import numpy_complex_scalar_converter - def unique_mod(d,file_name): f = os.path.basename(unique_file(d,file_name)) m = os.path.splitext(f)[0] @@ -52,22 +49,27 @@ # int, float, complex #---------------------------------------------------------------------------- -class NumpyComplexScalarConverter(NumpyTestCase): +class NumpyComplexScalarConverter(TestCase): compiler = '' def setUp(self): self.converter = numpy_complex_scalar_converter() - def check_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): assert( not self.converter.type_match('string') ) - def check_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): assert( not self.converter.type_match(5)) - def check_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): assert( not self.converter.type_match(5.)) - def check_type_match_complex128(self,level=5): + @dec.slow + def test_type_match_complex128(self): assert(self.converter.type_match(numpy.complex128(5.+1j))) - def check_complex_var_in(self,level=5): + @dec.slow + def test_complex_var_in(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -90,7 +92,8 @@ except TypeError: pass - def check_complex_return(self,level=5): + @dec.slow + def test_complex_return(self): mod_name = sys._getframe().f_code.co_name + self.compiler mod_name = unique_mod(test_dir,mod_name) mod = ext_tools.ext_module(mod_name) @@ -107,7 +110,8 @@ c = test(b) assert( c == 3.+3j) - def check_inline(self, level=5): + @dec.slow + def test_inline(self): a = numpy.complex128(1+1j) result = inline_tools.inline("return_val=1.0/a;",['a']) assert( result==.5-.5j) @@ -164,4 +168,4 @@ if _n[:7]=='TestGcc': exec 'del '+_n if __name__ == "__main__": - NumpyTest('weave.numpy_scalar_spec').run() + unittest.main() Modified: trunk/scipy/weave/tests/test_scxx.py =================================================================== --- trunk/scipy/weave/tests/test_scxx.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_scxx.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,12 +4,12 @@ import time import os,sys -from numpy.testing import * +from scipy.testing import * set_local_path() from test_scxx_object import * from test_scxx_sequence import * from test_scxx_dict import * -restore_path() + if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_scxx_dict.py =================================================================== --- trunk/scipy/weave/tests/test_scxx_dict.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_scxx_dict.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,18 +4,19 @@ import os import sys -from numpy.testing import * -set_package_path() -from weave import inline_tools -restore_path() +from scipy.testing import * +from scipy.weave import inline_tools -class TestDictConstruct(NumpyTestCase): + + +class TestDictConstruct(TestCase): #------------------------------------------------------------------------ # Check that construction from basic types is allowed and have correct # reference counts #------------------------------------------------------------------------ - def check_empty(self,level=5): + @dec.slow + def test_empty(self): # strange int value used to try and make sure refcount is 2. code = """ py::dict val; @@ -26,8 +27,9 @@ assert res == {} -class TestDictHasKey(NumpyTestCase): - def check_obj(self,level=5): +class TestDictHasKey(TestCase): + @dec.slow + def test_obj(self): class Foo: pass key = Foo() @@ -38,7 +40,8 @@ """ res = inline_tools.inline(code,['a','key']) assert res - def check_int(self,level=5): + @dec.slow + def test_int(self): a = {} a[1234] = 12345 code = """ @@ -46,7 +49,8 @@ """ res = inline_tools.inline(code,['a']) assert res - def check_double(self,level=5): + @dec.slow + def test_double(self): a = {} a[1234.] = 12345 code = """ @@ -54,7 +58,8 @@ """ res = inline_tools.inline(code,['a']) assert res - def check_complex(self,level=5): + @dec.slow + def test_complex(self): a = {} a[1+1j] = 12345 key = 1+1j @@ -64,7 +69,8 @@ res = inline_tools.inline(code,['a','key']) assert res - def check_string(self,level=5): + @dec.slow + def test_string(self): a = {} a["b"] = 12345 code = """ @@ -72,7 +78,8 @@ """ res = inline_tools.inline(code,['a']) assert res - def check_std_string(self,level=5): + @dec.slow + def test_std_string(self): a = {} a["b"] = 12345 key_name = "b" @@ -81,7 +88,8 @@ """ res = inline_tools.inline(code,['a','key_name']) assert res - def check_string_fail(self,level=5): + @dec.slow + def test_string_fail(self): a = {} a["b"] = 12345 code = """ @@ -90,7 +98,7 @@ res = inline_tools.inline(code,['a']) assert not res -class TestDictGetItemOp(NumpyTestCase): +class TestDictGetItemOp(TestCase): def generic_get(self,code,args=['a']): a = {} @@ -99,10 +107,13 @@ res = inline_tools.inline(code,args) assert res == a['b'] - def check_char(self,level=5): + @dec.slow + def test_char(self): self.generic_get('return_val = a["b"];') - def DOESNT_WORK_check_char_fail(self,level=5): + @dec.slow + @dec.willfail + def test_char_fail(self): # We can't through a KeyError for dicts on RHS of # = but not on LHS. Not sure how to deal with this. try: @@ -110,18 +121,22 @@ except KeyError: pass - def check_string(self,level=5): + @dec.slow + def test_string(self): self.generic_get('return_val = a[std::string("b")];') - def check_obj(self,level=5): + @dec.slow + def test_obj(self): code = """ py::object name = "b"; return_val = a[name]; """ self.generic_get(code,['a']) - def DOESNT_WORK_check_obj_fail(self,level=5): + @dec.slow + @dec.willfail + def test_obj_fail(self): # We can't through a KeyError for dicts on RHS of # = but not on LHS. Not sure how to deal with this. try: @@ -133,7 +148,7 @@ except KeyError: pass -class TestDictSetOperator(NumpyTestCase): +class TestDictSetOperator(TestCase): def generic_new(self,key,val): # test that value is set correctly and that reference counts # on dict, key, and val are being handled correctly. @@ -164,43 +179,53 @@ assert before == after assert before_overwritten == after_overwritten - def check_new_int_int(self,level=5): + @dec.slow + def test_new_int_int(self): key,val = 1234,12345 self.generic_new(key,val) - def check_new_double_int(self,level=5): + @dec.slow + def test_new_double_int(self): key,val = 1234.,12345 self.generic_new(key,val) - def check_new_std_string_int(self,level=5): + @dec.slow + def test_new_std_string_int(self): key,val = "hello",12345 self.generic_new(key,val) - def check_new_complex_int(self,level=5): + @dec.slow + def test_new_complex_int(self): key,val = 1+1j,12345 self.generic_new(key,val) - def check_new_obj_int(self,level=5): + @dec.slow + def test_new_obj_int(self): class Foo: pass key,val = Foo(),12345 self.generic_new(key,val) - def check_overwrite_int_int(self,level=5): + @dec.slow + def test_overwrite_int_int(self): key,val = 1234,12345 self.generic_overwrite(key,val) - def check_overwrite_double_int(self,level=5): + @dec.slow + def test_overwrite_double_int(self): key,val = 1234.,12345 self.generic_overwrite(key,val) - def check_overwrite_std_string_int(self,level=5): + @dec.slow + def test_overwrite_std_string_int(self): key,val = "hello",12345 self.generic_overwrite(key,val) - def check_overwrite_complex_int(self,level=5): + @dec.slow + def test_overwrite_complex_int(self): key,val = 1+1j,12345 self.generic_overwrite(key,val) - def check_overwrite_obj_int(self,level=5): + @dec.slow + def test_overwrite_obj_int(self): class Foo: pass key,val = Foo(),12345 self.generic_overwrite(key,val) -class TestDictDel(NumpyTestCase): +class TestDictDel(TestCase): def generic(self,key): # test that value is set correctly and that reference counts # on dict, key, are being handled correctly. after deletion, @@ -216,46 +241,56 @@ after = sys.getrefcount(a), sys.getrefcount(key) assert before[0] == after[0] assert before[1] == after[1] + 1 - def check_int(self,level=5): + @dec.slow + def test_int(self): key = 1234 self.generic(key) - def check_double(self,level=5): + @dec.slow + def test_double(self): key = 1234. self.generic(key) - def check_std_string(self,level=5): + @dec.slow + def test_std_string(self): key = "hello" self.generic(key) - def check_complex(self,level=5): + @dec.slow + def test_complex(self): key = 1+1j self.generic(key) - def check_obj(self,level=5): + @dec.slow + def test_obj(self): class Foo: pass key = Foo() self.generic(key) -class TestDictOthers(NumpyTestCase): - def check_clear(self,level=5): +class TestDictOthers(TestCase): + @dec.slow + def test_clear(self): a = {} a["hello"] = 1 inline_tools.inline("a.clear();",['a']) assert not a - def check_items(self,level=5): + @dec.slow + def test_items(self): a = {} a["hello"] = 1 items = inline_tools.inline("return_val = a.items();",['a']) assert items == a.items() - def check_values(self,level=5): + @dec.slow + def test_values(self): a = {} a["hello"] = 1 values = inline_tools.inline("return_val = a.values();",['a']) assert values == a.values() - def check_keys(self,level=5): + @dec.slow + def test_keys(self): a = {} a["hello"] = 1 keys = inline_tools.inline("return_val = a.keys();",['a']) assert keys == a.keys() - def check_update(self,level=5): + @dec.slow + def test_update(self): a,b = {},{} a["hello"] = 1 b["hello"] = 2 @@ -263,4 +298,4 @@ assert a == b if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_scxx_object.py =================================================================== --- trunk/scipy/weave/tests/test_scxx_object.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_scxx_object.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,17 +4,18 @@ import os import sys -from numpy.testing import * -set_package_path() -from weave import inline_tools -restore_path() +from scipy.testing import * -class TestObjectConstruct(NumpyTestCase): +from scipy.weave import inline_tools + + +class TestObjectConstruct(TestCase): #------------------------------------------------------------------------ # Check that construction from basic types is allowed and have correct # reference counts #------------------------------------------------------------------------ - def check_int(self,level=5): + @dec.slow + def test_int(self): # strange int value used to try and make sure refcount is 2. code = """ py::object val = 1001; @@ -23,7 +24,8 @@ res = inline_tools.inline(code) assert_equal(sys.getrefcount(res),2) assert_equal(res,1001) - def check_float(self,level=5): + @dec.slow + def test_float(self): code = """ py::object val = (float)1.0; return_val = val; @@ -31,7 +33,8 @@ res = inline_tools.inline(code) assert_equal(sys.getrefcount(res),2) assert_equal(res,1.0) - def check_double(self,level=5): + @dec.slow + def test_double(self): code = """ py::object val = 1.0; return_val = val; @@ -39,7 +42,8 @@ res = inline_tools.inline(code) assert_equal(sys.getrefcount(res),2) assert_equal(res,1.0) - def check_complex(self,level=5): + @dec.slow + def test_complex(self): code = """ std::complex num = std::complex(1.0,1.0); py::object val = num; @@ -48,7 +52,8 @@ res = inline_tools.inline(code) assert_equal(sys.getrefcount(res),2) assert_equal(res,1.0+1.0j) - def check_string(self,level=5): + @dec.slow + def test_string(self): code = """ py::object val = "hello"; return_val = val; @@ -57,7 +62,8 @@ assert_equal(sys.getrefcount(res),2) assert_equal(res,"hello") - def check_std_string(self,level=5): + @dec.slow + def test_std_string(self): code = """ std::string s = std::string("hello"); py::object val = s; @@ -67,18 +73,20 @@ assert_equal(sys.getrefcount(res),2) assert_equal(res,"hello") -class TestObjectPrint(NumpyTestCase): +class TestObjectPrint(TestCase): #------------------------------------------------------------------------ # Check the object print protocol. #------------------------------------------------------------------------ - def check_stdout(self,level=5): + @dec.slow + def test_stdout(self): code = """ py::object val = "how now brown cow"; val.print(stdout); """ res = inline_tools.inline(code) # visual check on this one. - def check_stringio(self,level=5): + @dec.slow + def test_stringio(self): import cStringIO file_imposter = cStringIO.StringIO() code = """ @@ -89,7 +97,8 @@ print file_imposter.getvalue() assert_equal(file_imposter.getvalue(),"'how now brown cow'") -## def check_failure(self,level=5): +## @dec.slow +## def test_failure(self): ## code = """ ## FILE* file = 0; ## py::object val = "how now brown cow"; @@ -102,33 +111,38 @@ ## pass -class TestObjectCast(NumpyTestCase): - def check_int_cast(self,level=5): +class TestObjectCast(TestCase): + @dec.slow + def test_int_cast(self): code = """ py::object val = 1; int raw_val = val; """ inline_tools.inline(code) - def check_double_cast(self,level=5): + @dec.slow + def test_double_cast(self): code = """ py::object val = 1.0; double raw_val = val; """ inline_tools.inline(code) - def check_float_cast(self,level=5): + @dec.slow + def test_float_cast(self): code = """ py::object val = 1.0; float raw_val = val; """ inline_tools.inline(code) - def check_complex_cast(self,level=5): + @dec.slow + def test_complex_cast(self): code = """ std::complex num = std::complex(1.0,1.0); py::object val = num; std::complex raw_val = val; """ inline_tools.inline(code) - def check_string_cast(self,level=5): + @dec.slow + def test_string_cast(self): code = """ py::object val = "hello"; std::string raw_val = val; @@ -148,8 +162,9 @@ # def __str__(self): # return "b" -class TestObjectHasattr(NumpyTestCase): - def check_string(self,level=5): +class TestObjectHasattr(TestCase): + @dec.slow + def test_string(self): a = Foo() a.b = 12345 code = """ @@ -157,7 +172,8 @@ """ res = inline_tools.inline(code,['a']) assert res - def check_std_string(self,level=5): + @dec.slow + def test_std_string(self): a = Foo() a.b = 12345 attr_name = "b" @@ -166,7 +182,8 @@ """ res = inline_tools.inline(code,['a','attr_name']) assert res - def check_string_fail(self,level=5): + @dec.slow + def test_string_fail(self): a = Foo() a.b = 12345 code = """ @@ -174,7 +191,8 @@ """ res = inline_tools.inline(code,['a']) assert not res - def check_inline(self,level=5): + @dec.slow + def test_inline(self): """ THIS NEEDS TO MOVE TO THE INLINE TEST SUITE """ a = Foo() @@ -195,7 +213,8 @@ print 'before, after, after2:', before, after, after2 pass - def check_func(self,level=5): + @dec.slow + def test_func(self): a = Foo() a.b = 12345 code = """ @@ -204,7 +223,7 @@ res = inline_tools.inline(code,['a']) assert res -class TestObjectAttr(NumpyTestCase): +class TestObjectAttr(TestCase): def generic_attr(self,code,args=['a']): a = Foo() @@ -217,32 +236,38 @@ after = sys.getrefcount(a.b) assert_equal(after,before) - def check_char(self,level=5): + @dec.slow + def test_char(self): self.generic_attr('return_val = a.attr("b");') - def check_char_fail(self,level=5): + @dec.slow + def test_char_fail(self): try: self.generic_attr('return_val = a.attr("c");') except AttributeError: pass - def check_string(self,level=5): + @dec.slow + def test_string(self): self.generic_attr('return_val = a.attr(std::string("b"));') - def check_string_fail(self,level=5): + @dec.slow + def test_string_fail(self): try: self.generic_attr('return_val = a.attr(std::string("c"));') except AttributeError: pass - def check_obj(self,level=5): + @dec.slow + def test_obj(self): code = """ py::object name = "b"; return_val = a.attr(name); """ self.generic_attr(code,['a']) - def check_obj_fail(self,level=5): + @dec.slow + def test_obj_fail(self): try: code = """ py::object name = "c"; @@ -252,7 +277,8 @@ except AttributeError: pass - def check_attr_call(self,level=5): + @dec.slow + def test_attr_call(self): a = Foo() res = inline_tools.inline('return_val = a.attr("bar").call();',['a']) first = sys.getrefcount(res) @@ -262,7 +288,7 @@ assert_equal(res,"bar results") assert_equal(first,second) -class TestObjectSetAttr(NumpyTestCase): +class TestObjectSetAttr(TestCase): def generic_existing(self, code, desired): args = ['a'] @@ -277,27 +303,34 @@ res = inline_tools.inline(code,args) assert_equal(a.b,desired) - def check_existing_char(self,level=5): + @dec.slow + def test_existing_char(self): self.generic_existing('a.set_attr("b","hello");',"hello") - def check_new_char(self,level=5): + @dec.slow + def test_new_char(self): self.generic_new('a.set_attr("b","hello");',"hello") - def check_existing_string(self,level=5): + @dec.slow + def test_existing_string(self): self.generic_existing('a.set_attr("b",std::string("hello"));',"hello") - def check_new_string(self,level=5): + @dec.slow + def test_new_string(self): self.generic_new('a.set_attr("b",std::string("hello"));',"hello") - def check_existing_object(self,level=5): + @dec.slow + def test_existing_object(self): code = """ py::object obj = "hello"; a.set_attr("b",obj); """ self.generic_existing(code,"hello") - def check_new_object(self,level=5): + @dec.slow + def test_new_object(self): code = """ py::object obj = "hello"; a.set_attr("b",obj); """ self.generic_new(code,"hello") - def check_new_fail(self,level=5): + @dec.slow + def test_new_fail(self): try: code = """ py::object obj = 1; @@ -307,26 +340,31 @@ except: pass - def check_existing_int(self,level=5): + @dec.slow + def test_existing_int(self): self.generic_existing('a.set_attr("b",1);',1) - def check_existing_double(self,level=5): + @dec.slow + def test_existing_double(self): self.generic_existing('a.set_attr("b",1.0);',1.0) - def check_existing_complex(self,level=5): + @dec.slow + def test_existing_complex(self): code = """ std::complex obj = std::complex(1,1); a.set_attr("b",obj); """ self.generic_existing(code,1+1j) - def check_existing_char1(self,level=5): + @dec.slow + def test_existing_char1(self): self.generic_existing('a.set_attr("b","hello");',"hello") - def check_existing_string1(self,level=5): + @dec.slow + def test_existing_string1(self): code = """ std::string obj = std::string("hello"); a.set_attr("b",obj); """ self.generic_existing(code,"hello") -class TestObjectDel(NumpyTestCase): +class TestObjectDel(TestCase): def generic(self, code): args = ['a'] a = Foo() @@ -334,27 +372,32 @@ res = inline_tools.inline(code,args) assert not hasattr(a,"b") - def check_char(self,level=5): + @dec.slow + def test_char(self): self.generic('a.del("b");') - def check_string(self,level=5): + @dec.slow + def test_string(self): code = """ std::string name = std::string("b"); a.del(name); """ self.generic(code) - def check_object(self,level=5): + @dec.slow + def test_object(self): code = """ py::object name = py::object("b"); a.del(name); """ self.generic(code) -class TestObjectCmp(NumpyTestCase): - def check_equal(self,level=5): +class TestObjectCmp(TestCase): + @dec.slow + def test_equal(self): a,b = 1,1 res = inline_tools.inline('return_val = (a == b);',['a','b']) assert_equal(res,(a == b)) - def check_equal_objects(self,level=5): + @dec.slow + def test_equal_objects(self): class Foo: def __init__(self,x): self.x = x @@ -363,47 +406,58 @@ a,b = Foo(1),Foo(2) res = inline_tools.inline('return_val = (a == b);',['a','b']) assert_equal(res,(a == b)) - def check_lt(self,level=5): + @dec.slow + def test_lt(self): a,b = 1,2 res = inline_tools.inline('return_val = (a < b);',['a','b']) assert_equal(res,(a < b)) - def check_gt(self,level=5): + @dec.slow + def test_gt(self): a,b = 1,2 res = inline_tools.inline('return_val = (a > b);',['a','b']) assert_equal(res,(a > b)) - def check_gte(self,level=5): + @dec.slow + def test_gte(self): a,b = 1,2 res = inline_tools.inline('return_val = (a >= b);',['a','b']) assert_equal(res,(a >= b)) - def check_lte(self,level=5): + @dec.slow + def test_lte(self): a,b = 1,2 res = inline_tools.inline('return_val = (a <= b);',['a','b']) assert_equal(res,(a <= b)) - def check_not_equal(self,level=5): + @dec.slow + def test_not_equal(self): a,b = 1,2 res = inline_tools.inline('return_val = (a != b);',['a','b']) assert_equal(res,(a != b)) - def check_int(self,level=5): + @dec.slow + def test_int(self): a = 1 res = inline_tools.inline('return_val = (a == 1);',['a']) assert_equal(res,(a == 1)) - def check_int2(self,level=5): + @dec.slow + def test_int2(self): a = 1 res = inline_tools.inline('return_val = (1 == a);',['a']) assert_equal(res,(a == 1)) - def check_unsigned_long(self,level=5): + @dec.slow + def test_unsigned_long(self): a = 1 res = inline_tools.inline('return_val = (a == (unsigned long)1);',['a']) assert_equal(res,(a == 1)) - def check_double(self,level=5): + @dec.slow + def test_double(self): a = 1 res = inline_tools.inline('return_val = (a == 1.0);',['a']) assert_equal(res,(a == 1.0)) - def check_char(self,level=5): + @dec.slow + def test_char(self): a = "hello" res = inline_tools.inline('return_val = (a == "hello");',['a']) assert_equal(res,(a == "hello")) - def check_std_string(self,level=5): + @dec.slow + def test_std_string(self): a = "hello" code = """ std::string hello = std::string("hello"); @@ -412,8 +466,9 @@ res = inline_tools.inline(code,['a']) assert_equal(res,(a == "hello")) -class TestObjectRepr(NumpyTestCase): - def check_repr(self,level=5): +class TestObjectRepr(TestCase): + @dec.slow + def test_repr(self): class Foo: def __str__(self): return "str return" @@ -428,8 +483,9 @@ assert_equal(first,second) assert_equal(res,"repr return") -class TestObjectStr(NumpyTestCase): - def check_str(self,level=5): +class TestObjectStr(TestCase): + @dec.slow + def test_str(self): class Foo: def __str__(self): return "str return" @@ -445,9 +501,10 @@ print res assert_equal(res,"str return") -class TestObjectUnicode(NumpyTestCase): +class TestObjectUnicode(TestCase): # This ain't going to win awards for test of the year... - def check_unicode(self,level=5): + @dec.slow + def test_unicode(self): class Foo: def __repr__(self): return "repr return" @@ -462,29 +519,33 @@ assert_equal(first,second) assert_equal(res,"unicode") -class TestObjectIsCallable(NumpyTestCase): - def check_true(self,level=5): +class TestObjectIsCallable(TestCase): + @dec.slow + def test_true(self): class Foo: def __call__(self): return 0 a= Foo() res = inline_tools.inline('return_val = a.is_callable();',['a']) assert res - def check_false(self,level=5): + @dec.slow + def test_false(self): class Foo: pass a= Foo() res = inline_tools.inline('return_val = a.is_callable();',['a']) assert not res -class TestObjectCall(NumpyTestCase): - def check_noargs(self,level=5): +class TestObjectCall(TestCase): + @dec.slow + def test_noargs(self): def Foo(): return (1,2,3) res = inline_tools.inline('return_val = Foo.call();',['Foo']) assert_equal(res,(1,2,3)) assert_equal(sys.getrefcount(res),3) # should be 2? - def check_args(self,level=5): + @dec.slow + def test_args(self): def Foo(val1,val2): return (val1,val2) code = """ @@ -496,7 +557,8 @@ res = inline_tools.inline(code,['Foo']) assert_equal(res,(1,"hello")) assert_equal(sys.getrefcount(res),2) - def check_args_kw(self,level=5): + @dec.slow + def test_args_kw(self): def Foo(val1,val2,val3=1): return (val1,val2,val3) code = """ @@ -510,7 +572,8 @@ res = inline_tools.inline(code,['Foo']) assert_equal(res,(1,"hello",3)) assert_equal(sys.getrefcount(res),2) - def check_noargs_with_args(self,level=5): + @dec.slow + def test_noargs_with_args(self): # calling a function that does take args with args # should fail. def Foo(): @@ -533,8 +596,9 @@ # first should == second, but the weird refcount error assert_equal(second,third) -class TestObjectMcall(NumpyTestCase): - def check_noargs(self,level=5): +class TestObjectMcall(TestCase): + @dec.slow + def test_noargs(self): a = Foo() res = inline_tools.inline('return_val = a.mcall("bar");',['a']) assert_equal(res,"bar results") @@ -544,7 +608,8 @@ assert_equal(res,"bar results") second = sys.getrefcount(res) assert_equal(first,second) - def check_args(self,level=5): + @dec.slow + def test_args(self): a = Foo() code = """ py::tuple args(2); @@ -555,7 +620,8 @@ res = inline_tools.inline(code,['a']) assert_equal(res,(1,"hello")) assert_equal(sys.getrefcount(res),2) - def check_args_kw(self,level=5): + @dec.slow + def test_args_kw(self): a = Foo() code = """ py::tuple args(2); @@ -568,7 +634,8 @@ res = inline_tools.inline(code,['a']) assert_equal(res,(1,"hello",3)) assert_equal(sys.getrefcount(res),2) - def check_std_noargs(self,level=5): + @dec.slow + def test_std_noargs(self): a = Foo() method = "bar" res = inline_tools.inline('return_val = a.mcall(method);',['a','method']) @@ -579,7 +646,8 @@ assert_equal(res,"bar results") second = sys.getrefcount(res) assert_equal(first,second) - def check_std_args(self,level=5): + @dec.slow + def test_std_args(self): a = Foo() method = "bar2" code = """ @@ -591,7 +659,8 @@ res = inline_tools.inline(code,['a','method']) assert_equal(res,(1,"hello")) assert_equal(sys.getrefcount(res),2) - def check_std_args_kw(self,level=5): + @dec.slow + def test_std_args_kw(self): a = Foo() method = "bar3" code = """ @@ -605,7 +674,8 @@ res = inline_tools.inline(code,['a','method']) assert_equal(res,(1,"hello",3)) assert_equal(sys.getrefcount(res),2) - def check_noargs_with_args(self,level=5): + @dec.slow + def test_noargs_with_args(self): # calling a function that does take args with args # should fail. a = Foo() @@ -627,8 +697,9 @@ # first should == second, but the weird refcount error assert_equal(second,third) -class TestObjectHash(NumpyTestCase): - def check_hash(self,level=5): +class TestObjectHash(TestCase): + @dec.slow + def test_hash(self): class Foo: def __hash__(self): return 123 @@ -637,42 +708,48 @@ print 'hash:', res assert_equal(res,123) -class TestObjectIsTrue(NumpyTestCase): - def check_true(self,level=5): +class TestObjectIsTrue(TestCase): + @dec.slow + def test_true(self): class Foo: pass a= Foo() res = inline_tools.inline('return_val = a.is_true();',['a']) assert_equal(res,1) - def check_false(self,level=5): + @dec.slow + def test_false(self): a= None res = inline_tools.inline('return_val = a.is_true();',['a']) assert_equal(res,0) -class TestObjectType(NumpyTestCase): - def check_type(self,level=5): +class TestObjectType(TestCase): + @dec.slow + def test_type(self): class Foo: pass a= Foo() res = inline_tools.inline('return_val = a.type();',['a']) assert_equal(res,type(a)) -class TestObjectSize(NumpyTestCase): - def check_size(self,level=5): +class TestObjectSize(TestCase): + @dec.slow + def test_size(self): class Foo: def __len__(self): return 10 a= Foo() res = inline_tools.inline('return_val = a.size();',['a']) assert_equal(res,len(a)) - def check_len(self,level=5): + @dec.slow + def test_len(self): class Foo: def __len__(self): return 10 a= Foo() res = inline_tools.inline('return_val = a.len();',['a']) assert_equal(res,len(a)) - def check_length(self,level=5): + @dec.slow + def test_length(self): class Foo: def __len__(self): return 10 @@ -681,43 +758,50 @@ assert_equal(res,len(a)) from UserList import UserList -class TestObjectSetItemOpIndex(NumpyTestCase): - def check_list_refcount(self,level=5): +class TestObjectSetItemOpIndex(TestCase): + @dec.slow + def test_list_refcount(self): a = UserList([1,2,3]) # temporary refcount fix until I understand why it incs by one. inline_tools.inline("a[1] = 1234;",['a']) before1 = sys.getrefcount(a) after1 = sys.getrefcount(a) assert_equal(after1,before1) - def check_set_int(self,level=5): + @dec.slow + def test_set_int(self): a = UserList([1,2,3]) inline_tools.inline("a[1] = 1234;",['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],1234) - def check_set_double(self,level=5): + @dec.slow + def test_set_double(self): a = UserList([1,2,3]) inline_tools.inline("a[1] = 123.0;",['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],123.0) - def check_set_char(self,level=5): + @dec.slow + def test_set_char(self): a = UserList([1,2,3]) inline_tools.inline('a[1] = "bubba";',['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],'bubba') - def check_set_string(self,level=5): + @dec.slow + def test_set_string(self): a = UserList([1,2,3]) inline_tools.inline('a[1] = std::string("sissy");',['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],'sissy') - def check_set_string(self,level=5): + @dec.slow + def test_set_string(self): a = UserList([1,2,3]) inline_tools.inline('a[1] = std::complex(1,1);',['a']) assert_equal(sys.getrefcount(a[1]),2) assert_equal(a[1],1+1j) from UserDict import UserDict -class TestObjectSetItemOpKey(NumpyTestCase): - def check_key_refcount(self,level=5): +class TestObjectSetItemOpKey(TestCase): + @dec.slow + def test_key_refcount(self): a = UserDict() code = """ py::object one = 1; @@ -751,7 +835,8 @@ assert_equal(val[0] + 1, val[1]) assert_equal(val[1], val[2]) - def check_set_double_exists(self,level=5): + @dec.slow + def test_set_double_exists(self): a = UserDict() key = 10.0 a[key] = 100.0 @@ -764,27 +849,31 @@ assert_equal(sys.getrefcount(key),5) assert_equal(sys.getrefcount(a[key]),2) assert_equal(a[key],123.0) - def check_set_double_new(self,level=5): + @dec.slow + def test_set_double_new(self): a = UserDict() key = 1.0 inline_tools.inline('a[key] = 123.0;',['a','key']) assert_equal(sys.getrefcount(key),4) # should be 3 assert_equal(sys.getrefcount(a[key]),2) assert_equal(a[key],123.0) - def check_set_complex(self,level=5): + @dec.slow + def test_set_complex(self): a = UserDict() key = 1+1j inline_tools.inline("a[key] = 1234;",['a','key']) assert_equal(sys.getrefcount(key),4) # should be 3 assert_equal(sys.getrefcount(a[key]),2) assert_equal(a[key],1234) - def check_set_char(self,level=5): + @dec.slow + def test_set_char(self): a = UserDict() inline_tools.inline('a["hello"] = 123.0;',['a']) assert_equal(sys.getrefcount(a["hello"]),2) assert_equal(a["hello"],123.0) - def check_set_class(self,level=5): + @dec.slow + def test_set_class(self): a = UserDict() class Foo: def __init__(self,val): @@ -802,7 +891,8 @@ assert_equal(sys.getrefcount(key),4) assert_equal(sys.getrefcount(a[key]),2) assert_equal(a[key],'bubba') - def check_set_from_member(self,level=5): + @dec.slow + def test_set_from_member(self): a = UserDict() a['first'] = 1 a['second'] = 2 @@ -810,7 +900,4 @@ assert_equal(a['first'],a['second']) if __name__ == "__main__": - import sys - if len(sys.argv) == 1: - sys.argv.extend(["--level=5"]) - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_scxx_sequence.py =================================================================== --- trunk/scipy/weave/tests/test_scxx_sequence.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_scxx_sequence.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -4,11 +4,11 @@ import time import os,sys -from numpy.testing import * -set_package_path() -from weave import inline_tools -restore_path() +from scipy.testing import * +from scipy.weave import inline_tools + + # Test: # append DONE # insert DONE @@ -20,10 +20,11 @@ from UserList import UserList -class _TestSequenceBase(NumpyTestCase): +class _TestSequenceBase(TestCase): seq_type = None - def check_conversion(self,level=5): + @dec.slow + def test_conversion(self): a = self.seq_type([1]) before = sys.getrefcount(a) inline_tools.inline(" ",['a']) @@ -35,7 +36,8 @@ #print '2nd,3rd:', before, after assert(after == before) - def check_in(self,level=5): + @dec.slow + def test_in(self): """ Test the "in" method for lists. We'll assume it works for sequences if it works here. """ @@ -87,7 +89,8 @@ res = inline_tools.inline(code,['a']) assert res == 0 - def check_count(self,level=5): + @dec.slow + def test_count(self): """ Test the "count" method for lists. We'll assume it works for sequences if it works hre. """ @@ -121,7 +124,8 @@ res = inline_tools.inline(code,['a']) assert res == 1 - def check_access_speed(self,level=5): + @dec.slow + def test_access_speed(self): N = 1000000 print '%s access -- val = a[i] for N =', (self.seq_type, N) a = self.seq_type([0]) * N @@ -151,7 +155,8 @@ print 'weave:', t2 - t1 # Fails - def check_access_set_speed(self,level=5): + @dec.slow + def test_access_set_speed(self): N = 1000000 print '%s access/set -- b[i] = a[i] for N =', (self.seq_type,N) a = self.seq_type([0]) * N @@ -181,7 +186,8 @@ class TestTuple(_TestSequenceBase): seq_type = tuple - def check_set_item_operator_equal_fail(self,level=5): + @dec.slow + def test_set_item_operator_equal_fail(self): # Tuples should only allow setting of variables # immediately after creation. a = (1,2,3) @@ -189,7 +195,8 @@ inline_tools.inline("a[1] = 1234;",['a']) except TypeError: pass - def check_set_item_operator_equal(self,level=5): + @dec.slow + def test_set_item_operator_equal(self): code = """ py::tuple a(3); a[0] = 1; @@ -202,7 +209,8 @@ # returned value should only have a single refcount assert sys.getrefcount(a) == 2 - def check_set_item_index_error(self,level=5): + @dec.slow + def test_set_item_index_error(self): code = """ py::tuple a(3); a[4] = 1; @@ -213,7 +221,8 @@ assert 0 except IndexError: pass - def check_get_item_operator_index_error(self,level=5): + @dec.slow + def test_get_item_operator_index_error(self): code = """ py::tuple a(3); py::object b = a[4]; // should fail. @@ -226,7 +235,8 @@ class TestList(_TestSequenceBase): seq_type = list - def check_append_passed_item(self,level=5): + @dec.slow + def test_append_passed_item(self): a = [] item = 1 @@ -243,7 +253,8 @@ after2 = sys.getrefcount(item) assert after1 == before1 assert after2 == before2 - def check_append(self,level=5): + @dec.slow + def test_append(self): a = [] # temporary refcount fix until I understand why it incs by one. inline_tools.inline("a.append(1);",['a']) @@ -277,7 +288,8 @@ after1 = sys.getrefcount(a) assert after1 == before1 - def check_insert(self,level=5): + @dec.slow + def test_insert(self): a = [1,2,3] a.insert(1,234) @@ -316,7 +328,8 @@ after1 = sys.getrefcount(a) assert after1 == before1 - def check_set_item_operator_equal(self,level=5): + @dec.slow + def test_set_item_operator_equal(self): a = self.seq_type([1,2,3]) # temporary refcount fix until I understand why it incs by one. inline_tools.inline("a[1] = 1234;",['a']) @@ -348,7 +361,8 @@ after1 = sys.getrefcount(a) assert after1 == before1 - def check_set_item_operator_equal_created(self,level=5): + @dec.slow + def test_set_item_operator_equal_created(self): code = """ py::list a(3); a[0] = 1; @@ -360,7 +374,8 @@ assert a == [1,2,3] # returned value should only have a single refcount assert sys.getrefcount(a) == 2 - def check_set_item_index_error(self,level=5): + @dec.slow + def test_set_item_index_error(self): code = """ py::list a(3); a[4] = 1; @@ -370,7 +385,8 @@ assert 0 except IndexError: pass - def check_get_item_index_error(self,level=5): + @dec.slow + def test_get_item_index_error(self): code = """ py::list a(3); py::object o = a[4]; @@ -381,7 +397,8 @@ except IndexError: pass - def check_string_add_speed(self,level=5): + @dec.slow + def test_string_add_speed(self): N = 1000000 print 'string add -- b[i] = a[i] + "blah" for N =', N a = ["blah"] * N @@ -407,7 +424,8 @@ t2 = time.time() print 'weave:', t2 - t1 assert b == desired - def check_int_add_speed(self,level=5): + @dec.slow + def test_int_add_speed(self): N = 1000000 print 'int add -- b[i] = a[i] + 1 for N =', N a = [0] * N @@ -434,4 +452,4 @@ assert b == desired if __name__ == "__main__": - NumpyTest().test(10,10) + unittest.main() Modified: trunk/scipy/weave/tests/test_size_check.py =================================================================== --- trunk/scipy/weave/tests/test_size_check.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_size_check.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,105 +1,105 @@ import os from numpy import * -from numpy.testing import * -set_package_path() -from weave import size_check -from weave.ast_tools import * -restore_path() +from scipy.testing import * +from scipy.weave import size_check +from scipy.weave.ast_tools import * + + import numpy as nx empty = array(()) -class TestMakeSameLength(NumpyTestCase): +class TestMakeSameLength(TestCase): - def generic_test(self,x,y,desired): + def generic_check(self,x,y,desired): actual = size_check.make_same_length(x,y) desired = desired assert_array_equal(actual,desired) - def check_scalar(self): + def test_scalar(self): x,y = (),() desired = empty,empty - self.generic_test(x,y,desired) - def check_x_scalar(self): + self.generic_check(x,y,desired) + def test_x_scalar(self): x,y = (),(1,2) desired = array((1,1)),array((1,2)) - self.generic_test(x,y,desired) - def check_y_scalar(self): + self.generic_check(x,y,desired) + def test_y_scalar(self): x,y = (1,2),() desired = array((1,2)),array((1,1)) - self.generic_test(x,y,desired) - def check_x_short(self): + self.generic_check(x,y,desired) + def test_x_short(self): x,y = (1,2),(1,2,3) desired = array((1,1,2)),array((1,2,3)) - self.generic_test(x,y,desired) - def check_y_short(self): + self.generic_check(x,y,desired) + def test_y_short(self): x,y = (1,2,3),(1,2) desired = array((1,2,3)),array((1,1,2)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) -class TestBinaryOpSize(NumpyTestCase): - def generic_test(self,x,y,desired): +class TestBinaryOpSize(TestCase): + def generic_check(self,x,y,desired): actual = size_check.binary_op_size(x,y) desired = desired assert_array_equal(actual,desired) - def generic_error_test(self,x,y): + def generic_error_check(self,x,y): self.failUnlessRaises(ValueError, size_check.binary_op_size, x, y) def desired_type(self,val): return array(val) - def check_scalar(self): + def test_scalar(self): x,y = (),() desired = self.desired_type(()) - self.generic_test(x,y,desired) - def check_x1(self): + self.generic_check(x,y,desired) + def test_x1(self): x,y = (1,),() desired = self.desired_type((1,)) - self.generic_test(x,y,desired) - def check_y1(self): + self.generic_check(x,y,desired) + def test_y1(self): x,y = (),(1,) desired = self.desired_type((1,)) - self.generic_test(x,y,desired) - def check_x_y(self): + self.generic_check(x,y,desired) + def test_x_y(self): x,y = (5,),(5,) desired = self.desired_type((5,)) - self.generic_test(x,y,desired) - def check_x_y2(self): + self.generic_check(x,y,desired) + def test_x_y2(self): x,y = (5,10),(5,10) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) - def check_x_y3(self): + self.generic_check(x,y,desired) + def test_x_y3(self): x,y = (5,10),(1,10) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) - def check_x_y4(self): + self.generic_check(x,y,desired) + def test_x_y4(self): x,y = (1,10),(5,10) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) - def check_x_y5(self): + self.generic_check(x,y,desired) + def test_x_y5(self): x,y = (5,1),(1,10) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) - def check_x_y6(self): + self.generic_check(x,y,desired) + def test_x_y6(self): x,y = (1,10),(5,1) desired = self.desired_type((5,10)) - self.generic_test(x,y,desired) - def check_x_y7(self): + self.generic_check(x,y,desired) + def test_x_y7(self): x,y = (5,4,3,2,1),(3,2,1) desired = self.desired_type((5,4,3,2,1)) - self.generic_test(x,y,desired) + self.generic_check(x,y,desired) - def check_error1(self): + def test_error1(self): x,y = (5,),(4,) - self.generic_error_test(x,y) + self.generic_error_check(x,y) - def check_error2(self): + def test_error2(self): x,y = (5,5),(4,5) - self.generic_error_test(x,y) + self.generic_error_check(x,y) class TestDummyArray(TestBinaryOpSize): - def generic_test(self,x,y,desired): + def generic_check(self,x,y,desired): if type(x) is type(()): x = ones(x) if type(y) is type(()): @@ -115,8 +115,8 @@ def desired_type(self,val): return size_check.dummy_array(array(val),1) -class TestDummyArrayIndexing(NumpyTestCase): - def generic_test(self,ary,expr,desired): +class TestDummyArrayIndexing(TestCase): + def generic_check(self,ary,expr,desired): a = size_check.dummy_array(ary) actual = eval(expr).shape #print desired, actual @@ -124,7 +124,7 @@ def generic_wrap(self,a,expr): desired = array(eval(expr).shape) try: - self.generic_test(a,expr,desired) + self.generic_check(a,expr,desired) except IndexError: if 0 not in desired: msg = '%s raised IndexError in dummy_array, but forms\n' \ @@ -144,72 +144,72 @@ a = arange(10) #print expr ,eval(expr) desired = array(()) - self.generic_test(a,expr,desired) - def check_1d_index_0(self): + self.generic_check(a,expr,desired) + def test_1d_index_0(self): self.generic_1d_index('a[0]') - def check_1d_index_1(self): + def test_1d_index_1(self): self.generic_1d_index('a[4]') - def check_1d_index_2(self): + def test_1d_index_2(self): self.generic_1d_index('a[-4]') - def check_1d_index_3(self): + def test_1d_index_3(self): try: self.generic_1d('a[12]') except IndexError: pass - def check_1d_index_calculated(self): + def test_1d_index_calculated(self): self.generic_1d_index('a[0+1]') - def check_1d_0(self): + def test_1d_0(self): self.generic_1d('a[:]') - def check_1d_1(self): + def test_1d_1(self): self.generic_1d('a[1:]') - def check_1d_2(self): + def test_1d_2(self): self.generic_1d('a[-1:]') - def check_1d_3(self): + def test_1d_3(self): self.generic_1d('a[-11:]') - def check_1d_4(self): + def test_1d_4(self): self.generic_1d('a[:1]') - def check_1d_5(self): + def test_1d_5(self): self.generic_1d('a[:-1]') - def check_1d_6(self): + def test_1d_6(self): self.generic_1d('a[:-11]') - def check_1d_7(self): + def test_1d_7(self): self.generic_1d('a[1:5]') - def check_1d_8(self): + def test_1d_8(self): self.generic_1d('a[1:-5]') - def check_1d_9(self): + def test_1d_9(self): # don't support zero length slicing at the moment. try: self.generic_1d('a[-1:-5]') except IndexError: pass - def check_1d_10(self): + def test_1d_10(self): self.generic_1d('a[-5:-1]') - def check_1d_stride_0(self): + def test_1d_stride_0(self): self.generic_1d('a[::1]') - def check_1d_stride_1(self): + def test_1d_stride_1(self): self.generic_1d('a[::-1]') - def check_1d_stride_2(self): + def test_1d_stride_2(self): self.generic_1d('a[1::1]') - def check_1d_stride_3(self): + def test_1d_stride_3(self): self.generic_1d('a[1::-1]') - def check_1d_stride_4(self): + def test_1d_stride_4(self): # don't support zero length slicing at the moment. try: self.generic_1d('a[1:5:-1]') except IndexError: pass - def check_1d_stride_5(self): + def test_1d_stride_5(self): self.generic_1d('a[5:1:-1]') - def check_1d_stride_6(self): + def test_1d_stride_6(self): self.generic_1d('a[:4:1]') - def check_1d_stride_7(self): + def test_1d_stride_7(self): self.generic_1d('a[:4:-1]') - def check_1d_stride_8(self): + def test_1d_stride_8(self): self.generic_1d('a[:-4:1]') - def check_1d_stride_9(self): + def test_1d_stride_9(self): self.generic_1d('a[:-4:-1]') - def check_1d_stride_10(self): + def test_1d_stride_10(self): self.generic_1d('a[:-3:2]') - def check_1d_stride_11(self): + def test_1d_stride_11(self): self.generic_1d('a[:-3:-2]') - def check_1d_stride_12(self): + def test_1d_stride_12(self): self.generic_1d('a[:-3:-7]') - def check_1d_random(self): + def test_1d_random(self): """ through a bunch of different indexes at it for good measure. """ import random @@ -224,13 +224,13 @@ except IndexError: pass - def check_2d_0(self): + def test_2d_0(self): self.generic_2d('a[:]') - def check_2d_1(self): + def test_2d_1(self): self.generic_2d('a[:2]') - def check_2d_2(self): + def test_2d_2(self): self.generic_2d('a[:,:]') - def check_2d_random(self): + def test_2d_random(self): """ through a bunch of different indexes at it for good measure. """ import random @@ -249,7 +249,7 @@ self.generic_2d(expr) except IndexError: pass - def check_3d_random(self): + def test_3d_random(self): """ through a bunch of different indexes at it for good measure. """ import random @@ -267,42 +267,42 @@ except IndexError: pass -class TestReduction(NumpyTestCase): - def check_1d_0(self): +class TestReduction(TestCase): + def test_1d_0(self): a = ones((5,)) actual = size_check.reduction(a,0) desired = size_check.dummy_array((),1) assert_array_equal(actual.shape,desired.shape) - def check_2d_0(self): + def test_2d_0(self): a = ones((5,10)) actual = size_check.reduction(a,0) desired = size_check.dummy_array((10,),1) assert_array_equal(actual.shape,desired.shape) - def check_2d_1(self): + def test_2d_1(self): a = ones((5,10)) actual = size_check.reduction(a,1) desired = size_check.dummy_array((5,),1) assert_array_equal(actual.shape,desired.shape) - def check_3d_0(self): + def test_3d_0(self): a = ones((5,6,7)) actual = size_check.reduction(a,1) desired = size_check.dummy_array((5,7),1) assert_array_equal(actual.shape,desired.shape) - def check_error0(self): + def test_error0(self): a = ones((5,)) try: actual = size_check.reduction(a,-2) except ValueError: pass - def check_error1(self): + def test_error1(self): a = ones((5,)) try: actual = size_check.reduction(a,1) except ValueError: pass -class TestExpressions(NumpyTestCase): - def generic_test(self,expr,desired,**kw): +class TestExpressions(TestCase): + def generic_check(self,expr,desired,**kw): import parser ast_list = parser.expr(expr).tolist() args = harvest_variables(ast_list) @@ -331,8 +331,8 @@ desired = zeros(()) except: desired = 'failed' - self.generic_test(expr,desired,**kw) - def check_generic_1d(self): + self.generic_check(expr,desired,**kw) + def test_generic_1d(self): a = arange(10) expr = 'a[:]' self.generic_wrap(expr,a=a) @@ -346,17 +346,17 @@ self.generic_wrap(expr,a=a,b=b) bad_expr = 'a[:5] + b' self.generic_wrap(bad_expr,a=a,b=b) - def check_single_index(self): + def test_single_index(self): a = arange(10) expr = 'a[5] + a[3]' self.generic_wrap(expr,a=a) - def check_calculated_index(self): + def test_calculated_index(self): a = arange(10) nx = 0 expr = 'a[5] + a[nx+3]' size_check.check_expr(expr,locals()) - def check_calculated_index2(self): + def test_calculated_index2(self): a = arange(10) nx = 0 expr = 'a[1:5] + a[nx+1:5+nx]' @@ -370,4 +370,4 @@ if __name__ == "__main__": - NumpyTest('weave.size_check').run() + unittest.main() Modified: trunk/scipy/weave/tests/test_slice_handler.py =================================================================== --- trunk/scipy/weave/tests/test_slice_handler.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_slice_handler.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,11 +1,11 @@ -from numpy.testing import * -set_package_path() -from weave import slice_handler -from weave.slice_handler import indexed_array_pattern -from weave.ast_tools import * -restore_path() +from scipy.testing import * +from scipy.weave import slice_handler +from scipy.weave.slice_handler import indexed_array_pattern +from scipy.weave.ast_tools import * + + def print_assert_equal(test_string,actual,desired): """this should probably be in scipy_test.testing """ @@ -22,21 +22,21 @@ pprint.pprint(desired,msg) raise AssertionError, msg.getvalue() -class TestBuildSliceAtom(NumpyTestCase): - def generic_test(self,slice_vars,desired): +class TestBuildSliceAtom(TestCase): + def generic_check(self,slice_vars,desired): pos = slice_vars['pos'] ast_list = slice_handler.build_slice_atom(slice_vars,pos) actual = ast_to_string(ast_list) print_assert_equal('',actual,desired) - def check_exclusive_end(self): + def test_exclusive_end(self): slice_vars = {'begin':'1', 'end':'2', 'step':'_stp', 'single_index':'_index','pos':0} desired = 'slice(1,2-1)' - self.generic_test(slice_vars,desired) + self.generic_check(slice_vars,desired) -class TestSlice(NumpyTestCase): +class TestSlice(TestCase): - def generic_test(self,suite_string,desired): + def generic_check(self,suite_string,desired): import parser ast_tuple = parser.suite(suite_string).totuple() found, data = find_first_pattern(ast_tuple,indexed_array_pattern) @@ -44,89 +44,89 @@ actual = slice_handler.slice_ast_to_dict(subscript) print_assert_equal(suite_string,actual,desired) - def check_empty_2_slice(self): + def test_empty_2_slice(self): """match slice from a[:]""" test ="a[:]" desired = {'begin':'_beg', 'end':'_end', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_begin_2_slice(self): + self.generic_check(test,desired) + def test_begin_2_slice(self): """match slice from a[1:]""" test ="a[1:]" desired = {'begin':'1', 'end':'_end', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_end_2_slice(self): + self.generic_check(test,desired) + def test_end_2_slice(self): """match slice from a[:2]""" test ="a[:2]" desired = {'begin':'_beg', 'end':'2', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_begin_end_2_slice(self): + self.generic_check(test,desired) + def test_begin_end_2_slice(self): """match slice from a[1:2]""" test ="a[1:2]" desired = {'begin':'1', 'end':'2', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_empty_3_slice(self): + self.generic_check(test,desired) + def test_empty_3_slice(self): """match slice from a[::]""" test ="a[::]" desired = {'begin':'_beg', 'end':'_end', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_begin_3_slice(self): + self.generic_check(test,desired) + def test_begin_3_slice(self): """match slice from a[1::]""" test ="a[1::]" desired = {'begin':'1', 'end':'_end', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_end_3_slice(self): + self.generic_check(test,desired) + def test_end_3_slice(self): """match slice from a[:2:]""" test ="a[:2:]" desired = {'begin':'_beg', 'end':'2', 'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_stp3_slice(self): + self.generic_check(test,desired) + def test_stp3_slice(self): """match slice from a[::3]""" test ="a[::3]" desired = {'begin':'_beg', 'end':'_end', 'step':'3', 'single_index':'_index'} - self.generic_test(test,desired) - def check_begin_end_3_slice(self): + self.generic_check(test,desired) + def test_begin_end_3_slice(self): """match slice from a[1:2:]""" test ="a[1:2:]" desired = {'begin':'1', 'end':'2','step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_begin_step_3_slice(self): + self.generic_check(test,desired) + def test_begin_step_3_slice(self): """match slice from a[1::3]""" test ="a[1::3]" desired = {'begin':'1', 'end':'_end','step':'3', 'single_index':'_index'} - self.generic_test(test,desired) - def check_end_step_3_slice(self): + self.generic_check(test,desired) + def test_end_step_3_slice(self): """match slice from a[:2:3]""" test ="a[:2:3]" desired = {'begin':'_beg', 'end':'2', 'step':'3', 'single_index':'_index'} - self.generic_test(test,desired) - def check_begin_end_stp3_slice(self): + self.generic_check(test,desired) + def test_begin_end_stp3_slice(self): """match slice from a[1:2:3]""" test ="a[1:2:3]" desired = {'begin':'1', 'end':'2', 'step':'3','single_index':'_index'} - self.generic_test(test,desired) - def check_expr_3_slice(self): + self.generic_check(test,desired) + def test_expr_3_slice(self): """match slice from a[:1+i+2:]""" test ="a[:1+i+2:]" desired = {'begin':'_beg', 'end':"1+i+2",'step':'_stp', 'single_index':'_index'} - self.generic_test(test,desired) - def check_single_index(self): + self.generic_check(test,desired) + def test_single_index(self): """match slice from a[0]""" test ="a[0]" desired = {'begin':'_beg', 'end':"_end",'step':'_stp', 'single_index':'0'} - self.generic_test(test,desired) + self.generic_check(test,desired) def replace_whitespace(in_str): out = in_str.replace(" ","") @@ -134,8 +134,8 @@ out = out.replace("\n","") return out -class TestTransformSlices(NumpyTestCase): - def generic_test(self,suite_string,desired): +class TestTransformSlices(TestCase): + def generic_check(self,suite_string,desired): import parser ast_list = parser.suite(suite_string).tolist() slice_handler.transform_slices(ast_list) @@ -146,20 +146,20 @@ desired = replace_whitespace(desired) print_assert_equal(suite_string,actual,desired) - def check_simple_expr(self): + def test_simple_expr(self): """transform a[:] to slice notation""" test ="a[:]" desired = 'a[slice(_beg,_end,_stp)]' - self.generic_test(test,desired) - def check_simple_expr(self): + self.generic_check(test,desired) + def test_simple_expr(self): """transform a[:,:] = b[:,1:1+2:3] *(c[1-2+i:,:] - c[:,:])""" test ="a[:,:] = b[:,1:1+2:3] *(c[1-2+i:,:] - c[:,:])" desired = " a[slice(_beg,_end),slice(_beg,_end)] = "\ " b[slice(_beg,_end), slice(1,1+2-1,3)] *"\ " (c[slice(1-2+i,_end), slice(_beg,_end)] -"\ " c[slice(_beg,_end), slice(_beg,_end)])" - self.generic_test(test,desired) + self.generic_check(test,desired) if __name__ == "__main__": - NumpyTest('weave.slice_handler').run() + unittest.main() Modified: trunk/scipy/weave/tests/test_standard_array_spec.py =================================================================== --- trunk/scipy/weave/tests/test_standard_array_spec.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_standard_array_spec.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -1,10 +1,9 @@ from numpy import * -from numpy.testing import * -set_package_path() -from weave import standard_array_spec -restore_path() +from scipy.testing import * +from scipy.weave import standard_array_spec + def remove_whitespace(in_str): out = in_str.replace(" ","") out = out.replace("\t","") @@ -27,16 +26,16 @@ pprint.pprint(desired,msg) raise AssertionError, msg.getvalue() -class TestArrayConverter(NumpyTestCase): - def check_type_match_string(self): +class TestArrayConverter(TestCase): + def test_type_match_string(self): s = standard_array_spec.array_converter() assert( not s.type_match('string') ) - def check_type_match_int(self): + def test_type_match_int(self): s = standard_array_spec.array_converter() assert(not s.type_match(5)) - def check_type_match_array(self): + def test_type_match_array(self): s = standard_array_spec.array_converter() assert(s.type_match(arange(4))) if __name__ == "__main__": - NumpyTest().run() + unittest.main() Modified: trunk/scipy/weave/tests/test_wx_spec.py =================================================================== --- trunk/scipy/weave/tests/test_wx_spec.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/test_wx_spec.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -8,38 +8,45 @@ then returned as a function return value correctly """ -from numpy.testing import * -set_package_path() -from weave import ext_tools, wx_spec -restore_path() +from scipy.testing import * +from scipy.weave import ext_tools, wx_spec + + import wx -class TestWxConverter(NumpyTestCase): +class TestWxConverter(TestCase): def setUp(self): self.app = wx.App() self.s = wx_spec.wx_converter() - def check_type_match_string(self,level=5): + @dec.slow + def test_type_match_string(self): assert(not self.s.type_match('string') ) - def check_type_match_int(self,level=5): + @dec.slow + def test_type_match_int(self): assert(not self.s.type_match(5)) - def check_type_match_float(self,level=5): + @dec.slow + def test_type_match_float(self): assert(not self.s.type_match(5.)) - def check_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): assert(not self.s.type_match(5.+1j)) - def check_type_match_complex(self,level=5): + @dec.slow + def test_type_match_complex(self): assert(not self.s.type_match(5.+1j)) - def check_type_match_wxframe(self,level=5): + @dec.slow + def test_type_match_wxframe(self): f=wx.Frame(None,-1,'bob') assert(self.s.type_match(f)) - def check_var_in(self,level=5): + @dec.slow + def test_var_in(self): mod = ext_tools.ext_module('wx_var_in',compiler='') mod.customize.add_header('') mod.customize.add_extra_compile_arg(' '.join(self.s.extra_compile_args)) @@ -69,7 +76,8 @@ except AttributeError: pass - def no_check_var_local(self,level=5): + @dec.slow + def no_check_var_local(self): mod = ext_tools.ext_module('wx_var_local') a = 'string' code = 'a="hello";' @@ -83,7 +91,8 @@ wx_var_local.test(b,q) assert('a' == 'string') - def no_test_no_check_return(self,level=5): + @dec.slow + def no_test_no_check_return(self): mod = ext_tools.ext_module('wx_return') a = 'string' code = """ @@ -99,7 +108,4 @@ assert(c == 'hello') if __name__ == "__main__": - import sys - if len(sys.argv) == 1: - sys.argv.extend(["--level=5"]) - NumpyTest().test(10,10) + unittest.main() Modified: trunk/scipy/weave/tests/weave_test_utils.py =================================================================== --- trunk/scipy/weave/tests/weave_test_utils.py 2008-01-12 09:23:49 UTC (rev 3821) +++ trunk/scipy/weave/tests/weave_test_utils.py 2008-01-12 10:06:39 UTC (rev 3822) @@ -28,10 +28,7 @@ # mainly used by catalog tests ################################################### -from numpy.testing import set_package_path, restore_path -set_package_path() -from weave import catalog -restore_path() +from scipy.weave import catalog import glob From scipy-svn at scipy.org Sat Jan 12 06:17:56 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 05:17:56 -0600 (CST) Subject: [Scipy-svn] r3823 - trunk/scipy/misc Message-ID: <20080112111756.4B6E039C019@new.scipy.org> Author: wnbell Date: 2008-01-12 05:17:53 -0600 (Sat, 12 Jan 2008) New Revision: 3823 Modified: trunk/scipy/misc/ppimport.py Log: fixed syntax error Modified: trunk/scipy/misc/ppimport.py =================================================================== --- trunk/scipy/misc/ppimport.py 2008-01-12 10:06:39 UTC (rev 3822) +++ trunk/scipy/misc/ppimport.py 2008-01-12 11:17:53 UTC (rev 3823) @@ -284,7 +284,7 @@ # XXX: Should we check the existence of module.test? Warn? from scipy.testing.pkgtester import Tester - test = Tester(os.path.dirname(module).test + test = Tester(os.path.dirname(module).test) return module def __setattr__(self, name, value): From scipy-svn at scipy.org Sat Jan 12 06:20:33 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 05:20:33 -0600 (CST) Subject: [Scipy-svn] r3824 - trunk/scipy/misc Message-ID: <20080112112033.23DFF39C019@new.scipy.org> Author: wnbell Date: 2008-01-12 05:20:31 -0600 (Sat, 12 Jan 2008) New Revision: 3824 Modified: trunk/scipy/misc/ppimport.py Log: refix syntax error Modified: trunk/scipy/misc/ppimport.py =================================================================== --- trunk/scipy/misc/ppimport.py 2008-01-12 11:17:53 UTC (rev 3823) +++ trunk/scipy/misc/ppimport.py 2008-01-12 11:20:31 UTC (rev 3824) @@ -284,7 +284,7 @@ # XXX: Should we check the existence of module.test? Warn? from scipy.testing.pkgtester import Tester - test = Tester(os.path.dirname(module).test) + test = Tester(os.path.dirname(module)).test return module def __setattr__(self, name, value): From scipy-svn at scipy.org Sat Jan 12 06:23:23 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 05:23:23 -0600 (CST) Subject: [Scipy-svn] r3825 - in trunk/scipy/sandbox/multigrid: . tests Message-ID: <20080112112323.6B1B839C019@new.scipy.org> Author: wnbell Date: 2008-01-12 05:23:18 -0600 (Sat, 12 Jan 2008) New Revision: 3825 Added: trunk/scipy/sandbox/multigrid/dec_example.py trunk/scipy/sandbox/multigrid/simple_example.py Removed: trunk/scipy/sandbox/multigrid/dec_test.py trunk/scipy/sandbox/multigrid/simple_test.py Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py Log: change names of example scripts Copied: trunk/scipy/sandbox/multigrid/dec_example.py (from rev 3822, trunk/scipy/sandbox/multigrid/dec_test.py) Deleted: trunk/scipy/sandbox/multigrid/dec_test.py =================================================================== --- trunk/scipy/sandbox/multigrid/dec_test.py 2008-01-12 11:20:31 UTC (rev 3824) +++ trunk/scipy/sandbox/multigrid/dec_test.py 2008-01-12 11:23:18 UTC (rev 3825) @@ -1,241 +0,0 @@ - -from scipy import * -from scipy.sparse import * -from pydec import * -from pydec.multigrid.discrete_laplacian import boundary_hierarchy, discrete_laplacian_solver, hodge_solver - -from scipy.sandbox.multigrid import smoothed_aggregation_solver,multigridtools,multilevel_solver -from scipy.sandbox.multigrid.adaptive import adaptive_sa_solver -from scipy.sandbox.multigrid.sa import sa_smoothed_prolongator -from scipy.sandbox.multigrid.utils import expand_into_blocks - - -## Load mesh from file -mesh_path = '../../../../../hirani_group/wnbell/meshes/' -#mesh = read_mesh(mesh_path + 'rocket/rocket.xml') -#mesh = read_mesh(mesh_path + 'genus3/genus3_168k.xml') -#mesh = read_mesh(mesh_path + 'genus3/genus3_455k.xml') -#mesh = read_mesh(mesh_path + '/torus/torus.xml') -mesh = read_mesh(mesh_path + '/sq14tri/sq14tri.xml') -for i in range(5): - mesh['vertices'],mesh['elements'] = loop_subdivision(mesh['vertices'],mesh['elements']) -cmplx = simplicial_complex(mesh['vertices'],mesh['elements']) - -## Construct mesh manually -#bitmap = ones((60,60),dtype='bool') -#bitmap[1::10,1::10] = False -#bitmap[100:150,100:400] = False -#cmplx = regular_cube_complex(regular_cube_mesh(bitmap)) - -def curl_curl_prolongator(D_nodal,vertices): - if not isspmatrix_csr(D_nodal): - raise TypeError('expected csr_matrix') - - A = D_nodal.T.tocsr() * D_nodal - aggs = multigridtools.sa_get_aggregates(A.shape[0],A.indptr,A.indices) - - num_edges = D_nodal.shape[0] - num_basis = vertices.shape[1] - num_aggs = aggs.max() + 1 - - # replace with CSR + eliminate duplicates - #indptr = (2*num_basis) * arange(num_edges+1) - ## same same - #csr_matrix((data,indices,indptr),shape=(num_edges,num_aggs)) - - row = arange(num_edges).repeat(2*num_basis) - col = (num_basis*aggs[D_nodal.indices]).repeat(num_basis) - col = col.reshape(-1,num_basis) + arange(num_basis) - col = col.reshape(-1) - data = tile(0.5 * (D_nodal*vertices),(1,2)).reshape(-1) - - return coo_matrix((data,(row,col)),shape=(num_edges,num_basis*num_aggs)).tocsr() - - - - - -def whitney_innerproduct_cache(cmplx,k): - h = hash(cmplx.vertices.tostring()) ^ hash(cmplx.simplices.tostring()) ^ hash(k) - - filename = "/home/nathan/.pydec/cache/whitney_" + str(h) + ".mtx" - - try: - import pydec - M = pydec.io.read_array(filename) - except: - import pydec - M = whitney_innerproduct(cmplx,k) - pydec.io.write_array(filename,M) - - return M - - - -def cube_innerproduct_cache(cmplx,k): - h = hash(cmplx.mesh.bitmap.tostring()) ^ hash(cmplx.mesh.bitmap.shape) ^ hash(k) - - filename = "/home/nathan/.pydec/cache/cube_" + str(h) + ".mtx" - - try: - import pydec - M = pydec.io.read_array(filename) - except: - import pydec - M = regular_cube_innerproduct(cmplx,k) - pydec.io.write_array(filename,M) - - return M - - - -#solve d_k d_k problem for all reasonable k -#from pylab import semilogy,show,xlabel,ylabel,legend,ylim,xlim -#from matplotlib.font_manager import fontManager, FontProperties - -cochain_complex = cmplx.cochain_complex() - -for i in [1]: #range(len(cochain_complex)-1): - print "computing mass matrix" - - if isinstance(cmplx,simplicial_complex): - Mi = whitney_innerproduct_cache(cmplx,i+1) - else: - Mi = regular_cube_innerproduct(cmplx,i+1) - - - dimension = mesh['vertices'].shape[1] - - if True: - - d0 = cmplx[0].d - d1 = cmplx[1].d - - #A = (d1.T.tocsr() * d1 + d0 * d0.T.tocsr()).astype('d') - A = (d1.T.tocsr() * d1).astype('d') - - P = curl_curl_prolongator(d0,mesh['vertices']) - - num_blocks = P.shape[1]/dimension - blocks = arange(num_blocks).repeat(dimension) - - P = sa_smoothed_prolongator(A,P,epsilon=0,omega=4.0/3.0) - - PAP = P.T.tocsr() * A * P - - candidates = None - candidates = zeros((num_blocks,dimension,dimension)) - for n in range(dimension): - candidates[:,n,n] = 1.0 - candidates = candidates.reshape(-1,dimension) - - ml = smoothed_aggregation_solver(PAP,epsilon=0.0,candidates=candidates,blocks=blocks) - #A = PAP - ml = multilevel_solver([A] + ml.As, [P] + ml.Ps) - else: - - bh = boundary_hierarchy(cochain_complex) - while len(bh) < 3: - bh.coarsen() - print repr(bh) - - N = len(cochain_complex) - 1 - - B = bh[0][N - i].B - - A = (B.T.tocsr() * B).astype('d') - #A = B.T.tocsr() * Mi * B - - constant_prolongators = [lvl[N - i].I for lvl in bh[:-1]] - - method = 'aSA' - - if method == 'RS': - As = [A] - Ps = [] - for T in constant_prolongators: - Ps.append( sa_smoothed_prolongator(As[-1],T,epsilon=0.0,omega=4.0/3.0) ) - As.append(Ps[-1].T.tocsr() * As[-1] * Ps[-1]) - ml = multilevel_solver(As,Ps) - - else: - if method == 'BSA': - if i == 0: - candidates = None - else: - candidates = cmplx[0].d * mesh['vertices'] - K = candidates.shape[1] - - constant_prolongators = [constant_prolongators[0]] + \ - [expand_into_blocks(T,K,1).tocsr() for T in constant_prolongators[1:] ] - - ml = smoothed_aggregation_solver(A,candidates,aggregation=constant_prolongators) - elif method == 'aSA': - asa = adaptive_sa_solver(A,aggregation=constant_prolongators,max_candidates=dimension,epsilon=0.0) - ml = asa.solver - else: - raise ValuerError,'unknown method' - - #ml = smoothed_aggregation_solver(A,candidates) - - #x = d0 * mesh['vertices'][:,0] - x = rand(A.shape[0]) - b = zeros_like(x) - #b = A*rand(A.shape[0]) - - if True: - x_sol,residuals = ml.solve(b,x0=x,maxiter=50,tol=1e-12,return_residuals=True) - else: - residuals = [] - def add_resid(x): - residuals.append(linalg.norm(b - A*x)) - A.psolve = ml.psolve - - from pydec import cg - x_sol = cg(A,b,x0=x,maxiter=40,tol=1e-8,callback=add_resid)[0] - - - residuals = array(residuals)/residuals[0] - avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) - print "average convergence ratio",avg_convergence_ratio - print "last convergence ratio",residuals[-1]/residuals[-2] - - print residuals - - - - -##candidates = None -##blocks = None -## -## -## -##A = io.mmread('tests/sample_data/elas30_A.mtx').tocsr() -##candidates = io.mmread('tests/sample_data/elas30_nullspace.mtx') -##candidates = [ array(candidates[:,x]) for x in range(candidates.shape[1]) ] -##blocks = arange(A.shape[0]/2).repeat(2) -## -##ml = smoothed_aggregation_solver(A,candidates,blocks=blocks,epsilon=0,max_coarse=10,max_levels=10) -###ml = ruge_stuben_solver(A) -## -##x = rand(A.shape[0]) -###b = zeros_like(x) -##b = A*rand(A.shape[0]) -## -##if True: -## x_sol,residuals = ml.solve(b,x0=x,maxiter=30,tol=1e-12,return_residuals=True) -##else: -## residuals = [] -## def add_resid(x): -## residuals.append(linalg.norm(b - A*x)) -## A.psolve = ml.psolve -## x_sol = linalg.cg(A,b,x0=x,maxiter=25,tol=1e-12,callback=add_resid)[0] -## -## -##residuals = array(residuals)/residuals[0] -##avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) -##print "average convergence ratio",avg_convergence_ratio -##print "last convergence ratio",residuals[-1]/residuals[-2] -## -##print residuals -## Copied: trunk/scipy/sandbox/multigrid/simple_example.py (from rev 3822, trunk/scipy/sandbox/multigrid/simple_test.py) Deleted: trunk/scipy/sandbox/multigrid/simple_test.py =================================================================== --- trunk/scipy/sandbox/multigrid/simple_test.py 2008-01-12 11:20:31 UTC (rev 3824) +++ trunk/scipy/sandbox/multigrid/simple_test.py 2008-01-12 11:23:18 UTC (rev 3825) @@ -1,22 +0,0 @@ -from scipy import rand -from scipy.sandbox.multigrid.sa import * -from scipy.sandbox.multigrid import * -from scipy.sandbox.multigrid.utils import * -from time import clock - -mats = io.loadmat('/home/nathan/Work/ogroup/matrices/elasticity/simple_grid_2d/elasticity_50x50.mat') -A = mats['A'].tobsr(blocksize=(2,2)) -B = mats['B'] - -#A = poisson_problem2D(500) -#B = None - -start = clock() -sa = smoothed_aggregation_solver(A,B=B) -print "constructed solver in %s seconds" % (clock() - start) - -b = rand(A.shape[0]) -start = clock() -x,residuals = sa.solve(b,return_residuals=True) -print "solved in %s seconds" % (clock() - start) -print 'residuals',residuals Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-12 11:20:31 UTC (rev 3824) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-12 11:23:18 UTC (rev 3825) @@ -179,21 +179,7 @@ assert_almost_equal(fine_candidates,Q*coarse_candidates) assert_almost_equal(Q*(Q.T*fine_candidates),fine_candidates) -## #aggregate one more level (to a single aggregate) -## K = coarse_candidates.shape[1] -## N = K*AggOp.shape[1] -## AggOp = csr_matrix((ones(N),zeros(N),arange(N + 1)),shape=(N,1)) #aggregate to a single point -## fine_candidates = coarse_candidates -## -## #mask_candidate(AggOp,fine_candidates) #not needed -## -## #now check the coarser problem -## Q,coarse_candidates = sa_fit_candidates(AggOp,fine_candidates) -## -## assert_almost_equal(fine_candidates,Q*coarse_candidates) -## assert_almost_equal(Q*(Q.T*fine_candidates),fine_candidates) - class TestSASolverPerformance(TestCase): def setUp(self): self.cases = [] From scipy-svn at scipy.org Sat Jan 12 10:41:35 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 09:41:35 -0600 (CST) Subject: [Scipy-svn] r3826 - in trunk/scipy: sandbox/multigrid sparse sparse/benchmarks sparse/tests Message-ID: <20080112154135.75EA939C264@new.scipy.org> Author: wnbell Date: 2008-01-12 09:41:27 -0600 (Sat, 12 Jan 2008) New Revision: 3826 Added: trunk/scipy/sparse/benchmarks/ trunk/scipy/sparse/benchmarks/test_sparse.py Removed: trunk/scipy/sparse/tests/test_sparse.py Modified: trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sandbox/multigrid/sa.py trunk/scipy/sandbox/multigrid/simple_example.py Log: updated example fixed SA BSR usage Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-12 11:23:18 UTC (rev 3825) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-12 15:41:27 UTC (rev 3826) @@ -155,7 +155,7 @@ while len(As) < max_levels and A.shape[0] > max_coarse: P,B = sa_interpolation(A,B,epsilon*0.5**(len(As)-1),omega=omega) - A = (P.T.tocsr() * A) * P #galerkin operator + A = (P.T.asformat(P.format) * A) * P #galerkin operator As.append(A) Ps.append(P) @@ -276,45 +276,3 @@ gauss_seidel(A,x,b,iterations=1,sweep="symmetric") - -if __name__ == '__main__': - from scipy import * - from scipy.sandbox.multigrid import * - candidates = None - A = poisson_problem2D(40,1e-2) - #A = io.mmread("rocker_arm_surface.mtx").tocsr() - #A = io.mmread("9pt-100x100.mtx").tocsr() - #A = io.mmread("/home/nathan/Desktop/9pt/9pt-100x100.mtx").tocsr() - #A = io.mmread("/home/nathan/Desktop/BasisShift_W_EnergyMin_Luke/9pt-5x5.mtx").tocsr() - - #A = io.mmread('tests/sample_data/elas30_A.mtx').tocsr() - #candidates = io.mmread('tests/sample_data/elas30_nullspace.mtx') - #blocks = arange(A.shape[0]/2).repeat(2) - - mats = io.loadmat('/home/nathan/Work/ogroup/matrices/elasticity/simple_grid_2d/elasticity_50x50.mat') - A = mats['A'] - candidates = mats['B'] - - ml = smoothed_aggregation_solver(A,candidates,epsilon=0.08,max_coarse=100,max_levels=10) - #ml = ruge_stuben_solver(A) - - x = rand(A.shape[0]) - b = zeros_like(x) - #b = A*rand(A.shape[0]) - - if True: - x_sol,residuals = ml.solve(b,x0=x,maxiter=30,tol=1e-8,return_residuals=True) - else: - residuals = [] - def add_resid(x): - residuals.append(linalg.norm(b - A*x)) - A.psolve = ml.psolve - x_sol = linalg.cg(A,b,x0=x,maxiter=25,tol=1e-12,callback=add_resid)[0] - - - residuals = array(residuals)/residuals[0] - avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) - print "average convergence ratio",avg_convergence_ratio - print "last convergence ratio",residuals[-1]/residuals[-2] - - print residuals Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-12 11:23:18 UTC (rev 3825) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-12 15:41:27 UTC (rev 3826) @@ -170,6 +170,7 @@ A_filtered = sa_filtered_matrix(A,epsilon) #use filtered matrix for anisotropic problems + # TODO use scale_rows() D_inv = diag_sparse(1.0/diag_sparse(A_filtered)) D_inv_A = D_inv * A_filtered D_inv_A *= omega/approximate_spectral_radius(D_inv_A) Modified: trunk/scipy/sandbox/multigrid/simple_example.py =================================================================== --- trunk/scipy/sandbox/multigrid/simple_example.py 2008-01-12 11:23:18 UTC (rev 3825) +++ trunk/scipy/sandbox/multigrid/simple_example.py 2008-01-12 15:41:27 UTC (rev 3826) @@ -1,22 +1,28 @@ -from scipy import rand +from scipy import * from scipy.sandbox.multigrid.sa import * from scipy.sandbox.multigrid import * from scipy.sandbox.multigrid.utils import * from time import clock -mats = io.loadmat('/home/nathan/Work/ogroup/matrices/elasticity/simple_grid_2d/elasticity_50x50.mat') +mats = io.loadmat('/home/nathan/Work/ogroup/matrices/elasticity/simple_grid_2d/elasticity_500x500.mat') A = mats['A'].tobsr(blocksize=(2,2)) B = mats['B'] -#A = poisson_problem2D(500) +#A = poisson_problem2D(50) #B = None start = clock() sa = smoothed_aggregation_solver(A,B=B) print "constructed solver in %s seconds" % (clock() - start) -b = rand(A.shape[0]) +x0 = rand(A.shape[0]) +b = zeros_like(x0) start = clock() -x,residuals = sa.solve(b,return_residuals=True) +x,residuals = sa.solve(b,x0=x0,return_residuals=True) print "solved in %s seconds" % (clock() - start) + +residuals = array(residuals)/residuals[0] +avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) +print "average convergence ratio",avg_convergence_ratio +print "last convergence ratio",residuals[-1]/residuals[-2] print 'residuals',residuals Copied: trunk/scipy/sparse/benchmarks/test_sparse.py (from rev 3822, trunk/scipy/sparse/tests/test_sparse.py) Deleted: trunk/scipy/sparse/tests/test_sparse.py =================================================================== --- trunk/scipy/sparse/tests/test_sparse.py 2008-01-12 11:23:18 UTC (rev 3825) +++ trunk/scipy/sparse/tests/test_sparse.py 2008-01-12 15:41:27 UTC (rev 3826) @@ -1,286 +0,0 @@ -"""general tests and simple benchmarks for the sparse module""" - -import numpy -from numpy import ones, array, asarray, empty - -import random -from scipy.testing import * - -from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ - coo_matrix, lil_matrix, dia_matrix, spidentity, spdiags, \ - spkron -from scipy.linsolve import splu - - -def random_sparse(m,n,nnz_per_row): - rows = numpy.arange(m).repeat(nnz_per_row) - cols = numpy.random.random_integers(low=0,high=n-1,size=nnz_per_row*m) - vals = numpy.random.random_sample(m*nnz_per_row) - return coo_matrix((vals,(rows,cols)),(m,n)).tocsr() - - -#TODO move this to a matrix gallery and add unittests -def poisson2d(N,dtype='d',format=None): - """ - Return a sparse matrix for the 2d poisson problem - with standard 5-point finite difference stencil on a - square N-by-N grid. - """ - if N == 1: - diags = asarray( [[4]],dtype=dtype) - return dia_matrix((diags,[0]), shape=(1,1)).asformat(format) - - offsets = array([0,-N,N,-1,1]) - - diags = empty((5,N**2),dtype=dtype) - - diags[0] = 4 #main diagonal - diags[1:] = -1 #all offdiagonals - - diags[3,N-1::N] = 0 #first lower diagonal - diags[4,N::N] = 0 #first upper diagonal - - return dia_matrix((diags,offsets),shape=(N**2,N**2)).asformat(format) - -import time -class TestSparseTools(TestCase): - """Simple benchmarks for sparse matrix module""" - - @dec.bench - def test_arithmetic(self): - matrices = [] - #matrices.append( ('A','Identity', spidentity(500**2,format='csr')) ) - matrices.append( ('A','Poisson5pt', poisson2d(500,format='csr')) ) - matrices.append( ('B','Poisson5pt^2', poisson2d(500,format='csr')**2) ) - - print - print ' Sparse Matrix Arithmetic' - print '====================================================================' - print ' var | name | shape | dtype | nnz ' - print '--------------------------------------------------------------------' - fmt = ' %1s | %14s | %20s | %9s | %8d ' - - for var,name,mat in matrices: - name = name.center(14) - shape = ("%s" % (mat.shape,)).center(20) - dtype = mat.dtype.name.center(9) - print fmt % (var,name,shape,dtype,mat.nnz) - - space = ' ' * 10 - print - print space+' Timings' - print space+'==========================================' - print space+' format | operation | time (msec) ' - print space+'------------------------------------------' - fmt = space+' %3s | %17s | %7.1f ' - - for format in ['csr']: - vars = dict( [(var,mat.asformat(format)) for (var,name,mat) in matrices ] ) - for X,Y in [ ('A','A'),('A','B'),('B','A'),('B','B') ]: - x,y = vars[X],vars[Y] - for op in ['__add__','__sub__','multiply','__div__','__mul__']: - fn = getattr(x,op) - fn(y) #warmup - - start = time.clock() - iter = 0 - while iter < 5 or time.clock() < start + 1: - fn(y) - iter += 1 - end = time.clock() - - msec_per_it = 1000*(end - start)/float(iter) - operation = (X + '.' + op + '(' + Y + ')').center(17) - print fmt % (format,operation,msec_per_it) - - - @dec.bench - def test_sort(self): - """sort CSR column indices""" - matrices = [] - matrices.append( ('Rand10', 1e4, 10) ) - matrices.append( ('Rand25', 1e4, 25) ) - matrices.append( ('Rand50', 1e4, 50) ) - matrices.append( ('Rand100', 1e4, 100) ) - matrices.append( ('Rand200', 1e4, 200) ) - - print - print ' Sparse Matrix Index Sorting' - print '=====================================================================' - print ' type | name | shape | nnz | time (msec) ' - print '---------------------------------------------------------------------' - fmt = ' %3s | %12s | %20s | %8d | %6.2f ' - - for name,N,K in matrices: - N = int(N) - A = random_sparse(N,N,K) - - start = time.clock() - iter = 0 - while iter < 5 and time.clock() - start < 1: - A._has_sorted_indices = False - A.sort_indices() - iter += 1 - end = time.clock() - - name = name.center(12) - shape = ("%s" % (A.shape,)).center(20) - - print fmt % (A.format,name,shape,A.nnz,1e3*(end-start)/float(iter) ) - - @dec.bench - def test_matvec(self): - matrices = [] - matrices.append(('Identity', spidentity(10**4,format='dia'))) - matrices.append(('Identity', spidentity(10**4,format='csr'))) - matrices.append(('Poisson5pt', poisson2d(300,format='dia'))) - matrices.append(('Poisson5pt', poisson2d(300,format='csr'))) - matrices.append(('Poisson5pt', poisson2d(300,format='bsr'))) - - A = spkron(poisson2d(150),ones((2,2))).tobsr(blocksize=(2,2)) - matrices.append( ('Block2x2', A.tocsr()) ) - matrices.append( ('Block2x2', A) ) - - A = spkron(poisson2d(100),ones((3,3))).tobsr(blocksize=(3,3)) - matrices.append( ('Block3x3', A.tocsr()) ) - matrices.append( ('Block3x3', A) ) - - print - print ' Sparse Matrix Vector Product' - print '==================================================================' - print ' type | name | shape | nnz | MFLOPs ' - print '------------------------------------------------------------------' - fmt = ' %3s | %12s | %20s | %8d | %6.1f ' - - for name,A in matrices: - x = ones(A.shape[1],dtype=A.dtype) - - y = A*x #warmup - - start = time.clock() - iter = 0 - while iter < 5 or time.clock() < start + 1: - try: - #avoid creating y if possible - A.matvec(x,y) - except: - y = A*x - iter += 1 - end = time.clock() - - del y - - name = name.center(12) - shape = ("%s" % (A.shape,)).center(20) - MFLOPs = (2*A.nnz*iter/(end-start))/float(1e6) - - print fmt % (A.format,name,shape,A.nnz,MFLOPs) - - @dec.bench - def test_construction(self): - """build matrices by inserting single values""" - matrices = [] - matrices.append( ('Empty',csr_matrix((10000,10000))) ) - matrices.append( ('Identity',spidentity(10000)) ) - matrices.append( ('Poisson5pt', poisson2d(100)) ) - - print - print ' Sparse Matrix Construction' - print '====================================================================' - print ' type | name | shape | nnz | time (sec) ' - print '--------------------------------------------------------------------' - fmt = ' %3s | %12s | %20s | %8d | %6.4f ' - - for name,A in matrices: - A = A.tocoo() - - for format in ['lil','dok']: - - start = time.clock() - - iter = 0 - while time.clock() < start + 0.5: - T = eval(format + '_matrix')(A.shape) - for i,j,v in zip(A.row,A.col,A.data): - T[i,j] = v - iter += 1 - end = time.clock() - - del T - name = name.center(12) - shape = ("%s" % (A.shape,)).center(20) - - print fmt % (format,name,shape,A.nnz,(end-start)/float(iter)) - - @dec.bench - def test_conversion(self): - A = poisson2d(100) - - formats = ['csr','csc','coo','lil','dok'] - - print - print ' Sparse Matrix Conversion' - print '==========================================================' - print ' format | tocsr() | tocsc() | tocoo() | tolil() | todok() ' - print '----------------------------------------------------------' - - for fromfmt in formats: - base = getattr(A,'to' + fromfmt)() - - times = [] - - for tofmt in formats: - try: - fn = getattr(base,'to' + tofmt) - except: - times.append(None) - else: - x = fn() #warmup - start = time.clock() - iter = 0 - while time.clock() < start + 0.2: - x = fn() - iter += 1 - end = time.clock() - del x - times.append( (end - start)/float(iter)) - - output = " %3s " % fromfmt - for t in times: - if t is None: - output += '| n/a ' - else: - output += '| %5.1fms ' % (1000*t) - print output - - -class TestLarge(TestCase): - def test_large(self): - # Create a 100x100 matrix with 100 non-zero elements - # and play around with it - #TODO move this out of Common since it doesn't use spmatrix - random.seed(0) - A = dok_matrix((100,100)) - for k in range(100): - i = random.randrange(100) - j = random.randrange(100) - A[i,j] = 1. - csr = A.tocsr() - csc = A.tocsc() - csc2 = csr.tocsc() - coo = A.tocoo() - csr2 = coo.tocsr() - assert_array_equal(A.transpose().todense(), csr.transpose().todense()) - assert_array_equal(csc.todense(), csr.todense()) - assert_array_equal(csr.todense(), csr2.todense()) - assert_array_equal(csr2.todense().transpose(), coo.transpose().todense()) - assert_array_equal(csr2.todense(), csc2.todense()) - csr_plus_csc = csr + csc - csc_plus_csr = csc + csr - assert_array_equal(csr_plus_csc.todense(), (2*A).todense()) - assert_array_equal(csr_plus_csc.todense(), csc_plus_csr.todense()) - - -if __name__ == "__main__": - unittest.main() - From scipy-svn at scipy.org Sat Jan 12 16:04:59 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 12 Jan 2008 15:04:59 -0600 (CST) Subject: [Scipy-svn] r3827 - trunk/scipy/testing Message-ID: <20080112210459.3746FC7C00A@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-12 15:04:55 -0600 (Sat, 12 Jan 2008) New Revision: 3827 Modified: trunk/scipy/testing/__init__.py trunk/scipy/testing/nosetester.py trunk/scipy/testing/nulltester.py trunk/scipy/testing/pkgtester.py Log: nose testing docstrings, enabled scipy import without nose Modified: trunk/scipy/testing/__init__.py =================================================================== --- trunk/scipy/testing/__init__.py 2008-01-12 15:41:27 UTC (rev 3826) +++ trunk/scipy/testing/__init__.py 2008-01-12 21:04:55 UTC (rev 3827) @@ -11,8 +11,7 @@ try: import nose except ImportError: - print 'Need nose testing framework installed for scipy tests' - raise + pass import decorators as dec from numpy.testing.utils import * Modified: trunk/scipy/testing/nosetester.py =================================================================== --- trunk/scipy/testing/nosetester.py 2008-01-12 15:41:27 UTC (rev 3826) +++ trunk/scipy/testing/nosetester.py 2008-01-12 21:04:55 UTC (rev 3827) @@ -1,17 +1,46 @@ -''' Nose tester object ''' +''' Nose test running + +Implements .test functions for modules. + +''' import os import sys import nose class NoseTester(object): - """ Scipy nose test runner. + """ Nose test runner. Usage: NoseTester().test() + + is package path or module Default for package is None. A + value of None finds calling module path. - is package path or module - None finds calling module path + Typical call is from module __init__, and corresponds to this: + + >>> test = NoseTester().test + + In practice, because nose may not be importable, the __init__ + files actually have: + + >>> from scipy.testing.pkgtester import Tester + >>> test = Tester().test + + The pkgtester module checks for the presence of nose on the path, + returning this class if nose is present, and a null class + otherwise. """ def __init__(self, package=None): + ''' Test class init + + Parameters + ---------- + package : string or module + If string, gives full path to package + If None, extract calling module path + Default is None + + ''' if package is None: f = sys._getframe(1) package = f.f_locals.get('__file__', None) @@ -21,31 +50,40 @@ package = os.path.dirname(package.__file__) self.package_path = package - def test(self, labels='fast', verbose=1, doctests=False, extra_argv=None): + def test(self, label='fast', verbose=1, doctests=False, extra_argv=None): ''' Module testing function - labels - identifies tests to run. This can be a string to - pass to the nosetests executable with the '-A' - option, or one of several special values. - Special values are: - 'fast' - the default - which corresponds to - nosetests -A option of - 'not slow and not bench and not willfail'. - 'full' - fast (as above) and slow tests as in - nosetests -A option of 'not bench and not willfail'. - None or '' - run all tests and benchmarks - - verbose - verbosity value 1-10 - doctests - if True, run doctests in module - extra_argv - list with any extra args to pass to nosetest + Parameters + ---------- + label : {'fast', 'full', '', attribute identifer} + Identifies tests to run. This can be a string to pass to + the nosetests executable with the'-A' option, or one of + several special values. + Special values are: + 'fast' - the default - which corresponds to + nosetests -A option of + 'not slow and not bench and not willfail'. + 'full' - fast (as above) and slow tests as in + nosetests -A option of 'not bench and not willfail'. + None or '' - run all tests and benchmarks + attribute_identifier - string passed directly to + nosetests as '-A' + verbose : integer + verbosity value for test outputs, 1-10 + doctests : boolean + If True, run doctests in module, default False + extra_argv : list + List with any extra args to pass to nosetests ''' argv = ['scipy module test', self.package_path, '-s'] - if labels: - if labels == 'fast': - labels = 'not slow and not bench and not willfail' - elif labels == 'full': - labels = 'not bench and not willfail' - argv += ['-A', labels] + if label: + if not isinstance(label, basestring): + raise TypeError, 'Test selection label should be a string' + if label == 'fast': + label = 'not slow and not bench and not willfail' + elif label == 'full': + label = 'not bench and not willfail' + argv += ['-A', label] argv += ['--verbosity', str(verbose)] if doctests: argv+=['--with-doctest'] Modified: trunk/scipy/testing/nulltester.py =================================================================== --- trunk/scipy/testing/nulltester.py 2008-01-12 15:41:27 UTC (rev 3826) +++ trunk/scipy/testing/nulltester.py 2008-01-12 21:04:55 UTC (rev 3827) @@ -1,8 +1,16 @@ -''' Null tester (when nose not importable ''' +''' Null tester (when nose not importable) +Merely returns error reporting lack of nose package + +See pkgtester, nosetester modules + +''' + +nose_url = 'http://somethingaboutorange.com/mrl/projects/nose' + class NullTester(object): def __init__(self, *args, **kwargs): pass def test(self, labels=None, *args, **kwargs): - raise ImportError, 'Need nose testing on path for tests' + raise ImportError, 'Need nose for tests - see %s' % nose_url Modified: trunk/scipy/testing/pkgtester.py =================================================================== --- trunk/scipy/testing/pkgtester.py 2008-01-12 15:41:27 UTC (rev 3826) +++ trunk/scipy/testing/pkgtester.py 2008-01-12 21:04:55 UTC (rev 3827) @@ -1,4 +1,15 @@ -''' Define test function for scipy package ''' +''' Define test function for scipy package + +Module tests for presence of nose. If present returns NoseTester, +otherwise returns a placeholder test routine reporting lack of nose +and inability to run tests. Typical use is in module __init__: + +from scipy.testing.pkgtester import Tester +test = Tester().test + +See nosetester module for test implementation + +''' try: import nose except ImportError: From scipy-svn at scipy.org Mon Jan 14 03:33:54 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 14 Jan 2008 02:33:54 -0600 (CST) Subject: [Scipy-svn] r3828 - trunk/scipy/sparse Message-ID: <20080114083354.4C36D39C0F2@new.scipy.org> Author: wnbell Date: 2008-01-14 02:33:50 -0600 (Mon, 14 Jan 2008) New Revision: 3828 Modified: trunk/scipy/sparse/bsr.py Log: small error in BSR Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-12 21:04:55 UTC (rev 3827) +++ trunk/scipy/sparse/bsr.py 2008-01-14 08:33:50 UTC (rev 3828) @@ -220,7 +220,7 @@ if self.nnz > 0: if self.indices.max() >= N/C: print "max index",self.indices.max() - raise ValueError, "column index values must be < %d" % N/C + raise ValueError, "column index values must be < %d" % (N/C) if self.indices.min() < 0: raise ValueError, "column index values must be >= 0" if diff(self.indptr).min() < 0: From scipy-svn at scipy.org Mon Jan 14 07:58:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 14 Jan 2008 06:58:20 -0600 (CST) Subject: [Scipy-svn] r3829 - in trunk/scipy/sandbox/multigrid: . gallery gallery/tests tests Message-ID: <20080114125820.68A2339C083@new.scipy.org> Author: wnbell Date: 2008-01-14 06:58:10 -0600 (Mon, 14 Jan 2008) New Revision: 3829 Added: trunk/scipy/sandbox/multigrid/gallery/ trunk/scipy/sandbox/multigrid/gallery/__init__.py trunk/scipy/sandbox/multigrid/gallery/elasticity.py trunk/scipy/sandbox/multigrid/gallery/info.py trunk/scipy/sandbox/multigrid/gallery/poisson.py trunk/scipy/sandbox/multigrid/gallery/setup.py trunk/scipy/sandbox/multigrid/gallery/tests/ trunk/scipy/sandbox/multigrid/gallery/tests/test_elasticity.py trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py Modified: trunk/scipy/sandbox/multigrid/__init__.py trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sandbox/multigrid/setup.py trunk/scipy/sandbox/multigrid/tests/test_sa.py Log: added matrix example gallery added linear elasticity examples moved poisson examples Modified: trunk/scipy/sandbox/multigrid/__init__.py =================================================================== --- trunk/scipy/sandbox/multigrid/__init__.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/__init__.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -3,6 +3,7 @@ from info import __doc__ from multilevel import * +from gallery import * __all__ = filter(lambda s:not s.startswith('_'),dir()) from scipy.testing.pkgtester import Tester Added: trunk/scipy/sandbox/multigrid/gallery/__init__.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/__init__.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/gallery/__init__.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -0,0 +1,10 @@ +"Matrix Gallery for Multigrid Solvers" + +from info import __doc__ + +from poisson import * +from elasticity import * + +__all__ = filter(lambda s:not s.startswith('_'),dir()) +from scipy.testing.pkgtester import Tester +test = Tester().test Added: trunk/scipy/sandbox/multigrid/gallery/elasticity.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/elasticity.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/gallery/elasticity.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -0,0 +1,144 @@ +"""Linear Elasticity Examples""" + +__all__ = [ 'linear_elasticity' ] + +from scipy import array, matrix, ones, zeros, arange, empty, \ + hstack, vstack, tile, ravel, mgrid, concatenate, \ + cumsum +from scipy.linalg import inv, det +from scipy.sparse import coo_matrix, bsr_matrix + + +def linear_elasticity( grid, spacing=None, E=1e5, nu=0.3, format=None): + if len(grid) == 2: + return q12d( grid, spacing=spacing, E=E, nu=nu, format=format ) + else: + raise NotImplemented,'no support for grid=%s' % str(grid) + +def q12d( grid, spacing=None, E = 1e5, nu = 0.3, dirichlet_boundary = True, format=None): + """ Q1 elements in 2 dimensions """ + X,Y = grid + + if X < 1 or Y < 1: + raise ValueError,'invalid grid shape' + + if dirichlet_boundary: + X += 1 + Y += 1 + + pts = mgrid[0:X+1,0:Y+1] + pts = hstack((pts[0].T.reshape(-1,1) - X/2.0, pts[1].T.reshape(-1,1) - Y/2.0)) + + if spacing is None: + DX,DY = 1,1 + else: + DX,DY = spacing + pts = [DX,DY] + + #compute local stiffness matrix + lame = E * nu / ((1 + nu) * (1 - 2*nu)) # Lame's first parameter + mu = E / (2 + 2*nu) # shear modulus + vertices = array([[0,0],[DX,0],[DX,DY],[0,DY]]) + K = stima4(vertices, lame, mu ) + + nodes = arange( (X+1)*(Y+1) ).reshape(X+1,Y+1) + LL = nodes[:-1,:-1] + I = (2*LL).repeat( K.size ).reshape(-1,8,8) + J = I.copy() + I += tile( [0,1,2,3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8,1) ) + J += tile( [0,1,2,3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8,1) ).T + V = tile( K, (X*Y,1) ) + + I = ravel(I) + J = ravel(J) + V = ravel(V) + + A = coo_matrix( (V,(I,J)), shape=(pts.size,pts.size) ).tocsr() #sum duplicates + A = A.tobsr(blocksize=(2,2)) + + del I,J,V,LL,nodes + + B = zeros(( 2 * (X+1)*(Y+1), 3)) + B[0::2,0] = 1 + B[1::2,1] = 1 + B[0::2,2] = -pts[:,1] + B[1::2,2] = pts[:,0] + + if dirichlet_boundary: + mask = zeros((X+1, Y+1),dtype='bool') + mask[1:-1,1:-1] = True + mask = ravel(mask) + data = zeros( ((X-1)*(Y-1),2,2) ) + data[:,0,0] = 1 + data[:,1,1] = 1 + indices = arange( (X-1)*(Y-1) ) + indptr = concatenate((array([0]),cumsum(mask))) + P = bsr_matrix((data,indices,indptr),shape=(2*(X+1)*(Y+1),2*(X-1)*(Y-1))) + Pt = P.T + A = P.T * A * P + + B = Pt * B + + return A.asformat(format),B + +def stima4(vertices, lame, mu): + """local stiffness matrix for two dimensional elasticity on a square element + + Material Parameters: + - lame : Lame's first parameter + - mu : shear modulus + + Note: + Vertices should be listed in counter-clockwise order: + [3]----[2] + | | + | | + [0]----[1] + + Degrees of freedom are enumerated as follows: + [x=6,y=7]----[x=4,y=5] + | | + | | + [x=0,y=1]----[x=2,y=3] + """ + + M = lame + 2*mu # P-wave modulus + + R_11 = matrix([[ 2, -2, -1, 1], + [ -2, 2, 1, -1], + [ -1, 1, 2, -2], + [ 1, -1, -2, 2]]) / 6.0 + + R_12 = matrix([[ 1, 1, -1, -1], + [ -1, -1, 1, 1], + [ -1, -1, 1, 1], + [ 1, 1, -1, -1]]) / 4.0 + + R_22 = matrix([[ 2, 1, -1, -2], + [ 1, 2, -2, -1], + [ -1, -2, 2, 1], + [ -2, -1, 1, 2]]) / 6.0 + + F = inv( vstack( (vertices[1] - vertices[0], vertices[3] - vertices[0]) ) ) + + K = zeros((8,8)) # stiffness matrix + + E = F.T * matrix([[M, 0],[0, mu]]) * F + K[0::2,0::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22 + + E = F.T * matrix([[mu, 0],[0, M]]) * F + K[1::2,1::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22 + + E = F.T * matrix([[0, mu],[lame, 0]]) * F; + K[1::2,0::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22 + + K[0::2,1::2] = K[1::2,0::2].T + + K /= det(F) + + return K + + + + + Added: trunk/scipy/sandbox/multigrid/gallery/info.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/info.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/gallery/info.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -0,0 +1,12 @@ +"""Matrix Gallery for Multigrid Solvers + +Functions +========= + + - poisson() : Poisson problem using Finite Differences + - linear_elasticity() : Linear Elasticity using Finite Elements + +""" + +postpone_import = 1 + Added: trunk/scipy/sandbox/multigrid/gallery/poisson.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/poisson.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/gallery/poisson.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -0,0 +1,55 @@ +__all__ = ['poisson'] + +from scipy import array, empty +from scipy.sparse import dia_matrix + +def poisson(N, stencil='5pt', dtype=float, format=None): + """Finite Difference approximations to the Poisson problem + + TheDirichlet boundary conditions are + + + Parameters + ========== + - N : integer + - grid size + - stencil : one of the following strings + - '3pt' : 3-point Finite Difference stencil in 1 dimension + - '5pt' : 5-point Finite Difference stencil in 2 dimensions + - '8pt' : NotImplemented + - '27pt' : NotImplemented + + """ + if N < 1: + raise ValueError,'invalid grid size %s' % N + + if stencil == '3pt': + if N == 1: + diags = array( [[2]], dtype=dtype) + return dia_matrix((diags,[0]), shape=(1,1)).asformat(format) + else: + data = empty((3,N),dtype=dtype) + data[0,:] = 2 #main diagonal + data[1,:] = -1 + data[2,:] = -1 + + return dia_matrix((data,[0,-1,1]),shape=(N,N)).asformat(format) + elif stencil == '5pt': + if N == 1: + data = array( [[4]], dtype=dtype) + return dia_matrix((diags,[0]), shape=(1,1)).asformat(format) + else: + diags = array([0,-N,N,-1,1]) + + data = empty((5,N**2),dtype=dtype) + + data[0] = 4 #main diagonal + data[1::,:] = -1 + data[3,N-1::N] = 0 + data[4,N::N] = 0 + + return dia_matrix((data,diags),shape=(N**2,N**2)).asformat(format) + else: + raise NotImplementedError,'unsupported stencil=%s' % stencil + + Added: trunk/scipy/sandbox/multigrid/gallery/setup.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/setup.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/gallery/setup.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -0,0 +1,17 @@ +#!/usr/bin/env python + +import sys + +def configuration(parent_package='',top_path=None): + import numpy + from numpy.distutils.misc_util import Configuration + + config = Configuration('gallery',parent_package,top_path) + + config.add_data_dir('tests') + + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) Property changes on: trunk/scipy/sandbox/multigrid/gallery/setup.py ___________________________________________________________________ Name: svn:executable + * Added: trunk/scipy/sandbox/multigrid/gallery/tests/test_elasticity.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/tests/test_elasticity.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/gallery/tests/test_elasticity.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -0,0 +1,115 @@ +from scipy.testing import * + +from scipy import matrix, array +from scipy.sparse import coo_matrix + +from scipy.sandbox.multigrid.gallery.elasticity import linear_elasticity, \ + stima4 + +class TestLinearElasticity(TestCase): + def test_1x1(self): + A_expected = matrix ([[ 230769.23076923, 0. ], + [ 0. , 230769.23076923]]) + B_expected = array([[1, 0, 0], + [0, 1, 0]]) + + A,B = linear_elasticity( (1,1), E=1e5, nu=0.3 ) + + assert_almost_equal(A.todense(),A_expected) + assert_almost_equal(B,B_expected) + + def test_1x1(self): + + data = array([ 230769.23076923, -76923.07692308, 19230.76923077, + -28846.15384615, -24038.46153846, 230769.23076923, + 19230.76923077, -76923.07692308, -24038.46153846, + -28846.15384615, -76923.07692308, 230769.23076923, + -28846.15384615, 24038.46153846, 19230.76923077, + 19230.76923077, 230769.23076923, 24038.46153846, + -28846.15384615, -76923.07692308, 19230.76923077, + -28846.15384615, 24038.46153846, 230769.23076923, + -76923.07692308, -76923.07692308, 24038.46153846, + -28846.15384615, 230769.23076923, 19230.76923077, + -28846.15384615, -24038.46153846, 19230.76923077, + -76923.07692308, 230769.23076923, -24038.46153846, + -28846.15384615, -76923.07692308, 19230.76923077, + 230769.23076923]) + row = array([0, 2, 4, 6, 7, 1, 3, 5, 6, 7, 0, 2, 4, 5, 6, 1, 3, 4, 5, 7, 0, 2, 3, 4, 6, 1, 2, 3, 5, 7, 0, 1, 2, 4, 6, 0, 1, 3, 5, 7]) + col = array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7]) + + A_expected = coo_matrix((data,(row,col)), shape=(8,8)).todense() + B_expected = array([[ 1. , 0. , 0.5], + [ 0. , 1. , -0.5], + [ 1. , 0. , 0.5], + [ 0. , 1. , 0.5], + [ 1. , 0. , -0.5], + [ 0. , 1. , -0.5], + [ 1. , 0. , -0.5], + [ 0. , 1. , 0.5]]) + + A,B = linear_elasticity( (2,2), E=1e5, nu=0.3 ) + + assert_almost_equal(A.todense(),A_expected) + assert_almost_equal(B,B_expected) + +class TestLocalStiffnessMatrix(TestCase): + def test_stima4(self): + L = matrix([[ 4, 3, -4, 3, -2, -3, 2, -3], + [ 3, 4, -3, 2, -3, -2, 3, -4], + [ -4, -3, 4, -3, 2, 3, -2, 3], + [ 3, 2, -3, 4, -3, -4, 3, -2], + [ -2, -3, 2, -3, 4, 3, -4, 3], + [ -3, -2, 3, -4, 3, 4, -3, 2], + [ 2, 3, -2, 3, -4, -3, 4, -3], + [ -3, -4, 3, -2, 3, 2, -3, 4]]) / 12.0 + + M = matrix([[ 4, 1, -2, -1, -2, -1, 0, 1], + [ 1, 4, 1, 0, -1, -2, -1, -2], + [ -2, 1, 4, -1, 0, -1, -2, 1], + [ -1, 0, -1, 4, 1, -2, 1, -2], + [ -2, -1, 0, 1, 4, 1, -2, -1], + [ -1, -2, -1, -2, 1, 4, 1, 0], + [ 0, -1, -2, 1, -2, 1, 4, -1], + [ 1, -2, 1, -2, -1, 0, -1, 4]]) / 4.0 + + vertices = matrix([[ 0, 0], + [ 1, 0], + [ 1, 1], + [ 0, 1]]) + + assert_almost_equal( stima4(vertices, 1, 0) , L) + assert_almost_equal( stima4(vertices, 0, 1) , M) + assert_almost_equal( stima4(vertices, 1, 1) , L + M) + + + + L = matrix([[ 2, 3, -2, 3, -1, -3, 1, -3], + [ 3, 8, -3, 4, -3, -4, 3, -8], + [-2, -3, 2, -3, 1, 3, -1, 3], + [ 3, 4, -3, 8, -3, -8, 3, -4], + [-1, -3, 1, -3, 2, 3, -2, 3], + [-3, -4, 3, -8, 3, 8, -3, 4], + [ 1, 3, -1, 3, -2, -3, 2, -3], + [-3, -8, 3, -4, 3, 4, -3, 8]]) / 12.0 + + M = matrix([[ 4, 1, 0, -1, -2, -1, -2, 1], + [ 1, 6, 1, 2, -1, -3, -1, -5], + [ 0, 1, 4, -1, -2, -1, -2, 1], + [-1, 2, -1, 6, 1, -5, 1, -3], + [-2, -1, -2, 1, 4, 1, 0, -1], + [-1, -3, -1, -5, 1, 6, 1, 2], + [-2, -1, -2, 1, 0, 1, 4, -1], + [ 1, -5, 1, -3, -1, 2, -1, 6]]) / 4.0 + + vertices = matrix([[ 0, 0], + [ 2, 0], + [ 2, 1], + [ 0, 1]]) + + assert_almost_equal( stima4(vertices, 1, 0) , L) + assert_almost_equal( stima4(vertices, 0, 1) , M) + assert_almost_equal( stima4(vertices, 1, 1) , L + M) + + +if __name__ == '__main__': + unittest.main() Added: trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -0,0 +1,26 @@ +from scipy.testing import * + +from scipy import matrix + +from scipy.sandbox.multigrid.gallery.poisson import * + +class TestPoisson(TestCase): + def test_3pt(self): + cases = [] + + cases.append( (1,matrix([[2]])) ) + cases.append( (2,matrix([[ 2,-1], + [-1, 2]])) ) + cases.append( (4,matrix([[ 2,-1, 0, 0], + [-1, 2,-1, 0], + [ 0,-1, 2,-1], + [ 0, 0,-1, 2]])) ) + + + for N,expected in cases: + assert_equal( poisson(N,stencil='3pt').todense(), expected ) + + + +if __name__ == '__main__': + unittest.main() Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -1,5 +1,4 @@ -__all__ = ['poisson_problem1D','poisson_problem2D', - 'ruge_stuben_solver','smoothed_aggregation_solver', +__all__ = ['ruge_stuben_solver','smoothed_aggregation_solver', 'multilevel_solver'] import scipy @@ -15,43 +14,7 @@ from utils import symmetric_rescaling, diag_sparse -def poisson_problem1D(N): - """ - Return a sparse CSR matrix for the 1d poisson problem - with standard 3-point finite difference stencil on a - grid with N points. - """ - D = 2*ones(N) - O = -ones(N) - return scipy.sparse.spdiags([D,O,O],[0,-1,1],N,N).tocoo().tocsr() #eliminate explicit zeros -def poisson_problem2D(N, epsilon=1.0, dtype='d', format=None): - """ - Return a sparse matrix for the 2d poisson problem - with standard 5-point finite difference stencil on a - square N-by-N grid. - """ - if N == 1: - diags = asarray( [[4]],dtype=dtype) - return dia_matrix((diags,[0]), shape=(1,1)).asformat(format) - - offsets = array([0,-N,N,-1,1]) - - diags = empty((5,N**2),dtype=dtype) - - diags[0] = (2 + 2*epsilon) #main diagonal - diags[1,:] = -1 - diags[2,:] = -1 - - diags[3,:] = -epsilon #first lower diagonal - diags[4,:] = -epsilon #first upper diagonal - diags[3,N-1::N] = 0 - diags[4,N::N] = 0 - - return dia_matrix((diags,offsets),shape=(N**2,N**2)).tocoo().tocsr() #eliminate explicit zeros - #return dia_matrix((diags,offsets),shape=(N**2,N**2)).asformat(format) - - def ruge_stuben_solver(A,max_levels=10,max_coarse=500): """ Create a multilevel solver using Ruge-Stuben coarsening (Classical AMG) Modified: trunk/scipy/sandbox/multigrid/setup.py =================================================================== --- trunk/scipy/sandbox/multigrid/setup.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/setup.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -9,6 +9,8 @@ config = Configuration('multigrid',parent_package,top_path) + config.add_subpackage('gallery') + config.add_data_dir('tests') config.add_data_dir(join('tests','sample_data')) Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-14 08:33:50 UTC (rev 3828) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-14 12:58:10 UTC (rev 3829) @@ -19,12 +19,11 @@ from scipy.sandbox.multigrid.sa import sa_strong_connections, sa_constant_interpolation, \ sa_interpolation, sa_fit_candidates, \ sa_smoothed_prolongator -from scipy.sandbox.multigrid.multilevel import poisson_problem1D,poisson_problem2D, \ - smoothed_aggregation_solver +from scipy.sandbox.multigrid.multilevel import smoothed_aggregation_solver from scipy.sandbox.multigrid.utils import diag_sparse +from scipy.sandbox.multigrid.gallery import poisson - #def sparsity(A): # A = A.copy() # @@ -49,9 +48,9 @@ # poisson problems in 1D and 2D for N in [2,3,5,7,10,11,19]: - self.cases.append( poisson_problem1D(N) ) + self.cases.append( poisson(N,stencil='3pt',format='csr') ) for N in [2,3,5,7,10,11]: - self.cases.append( poisson_problem2D(N) ) + self.cases.append( poisson(N,stencil='5pt',format='csr') ) def test_sa_strong_connections(self): @@ -75,7 +74,7 @@ #assert_array_equal(S_result.todense(),S_expected.todense()) # two aggregates in 1D - A = poisson_problem1D(6) + A = poisson(6,stencil='3pt') AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) candidates = ones((6,1)) @@ -107,13 +106,13 @@ user_cases = [] #simple 1d example w/ two aggregates - A = poisson_problem1D(6) + A = poisson(6, stencil='3pt', format='csr') AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) candidates = ones((6,1)) user_cases.append((A,AggOp,candidates)) #simple 1d example w/ two aggregates (not all nodes are aggregated) - A = poisson_problem1D(6) + A = poisson(6, stencil='3pt', format='csr') AggOp = csr_matrix((ones(4),array([0,0,1,1]),array([0,1,1,2,3,3,4])),shape=(6,2)) candidates = ones((6,1)) user_cases.append((A,AggOp,candidates)) @@ -184,8 +183,8 @@ def setUp(self): self.cases = [] - self.cases.append((poisson_problem1D(100),None)) - self.cases.append((poisson_problem2D(50),None)) + self.cases.append(( poisson(100, stencil='3pt', format='csr'), None)) + self.cases.append(( poisson(100, stencil='5pt', format='csr'), None)) # TODO add unstructured tests From scipy-svn at scipy.org Mon Jan 14 14:29:19 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 14 Jan 2008 13:29:19 -0600 (CST) Subject: [Scipy-svn] r3830 - trunk/scipy/sparse Message-ID: <20080114192919.3C73939C04B@new.scipy.org> Author: wnbell Date: 2008-01-14 13:29:12 -0600 (Mon, 14 Jan 2008) New Revision: 3830 Modified: trunk/scipy/sparse/bsr.py trunk/scipy/sparse/construct.py trunk/scipy/sparse/coo.py trunk/scipy/sparse/csc.py trunk/scipy/sparse/csr.py trunk/scipy/sparse/dia.py trunk/scipy/sparse/info.py Log: fixed docstrings to pass doctests Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-14 12:58:10 UTC (rev 3829) +++ trunk/scipy/sparse/bsr.py 2008-01-14 19:29:12 UTC (rev 3830) @@ -62,22 +62,22 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> bsr_matrix( (3,4), dtype='i' ).todense() + >>> bsr_matrix( (3,4), dtype='int32' ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]]) + [0, 0, 0, 0]], dtype=int32) - >>> row = array([0,0,1,2,2,2]) - >>> col = array([0,2,2,0,1,2]) - >>> data = kron([1,2,3,4,5,6]) + >>> row = array([0,0,1,2,2,2]) + >>> col = array([0,2,2,0,1,2]) + >>> data = array([1,2,3,4,5,6]) >>> bsr_matrix( (data,(row,col)), shape=(3,3) ).todense() matrix([[1, 0, 2], [0, 0, 3], [4, 5, 6]]) - >>> indptr = array([0,2,3,6]) + >>> indptr = array([0,2,3,6]) >>> indices = array([0,2,2,0,1,2]) - >>> data = array([1,2,3,4,5,6]).repeat(4).reshape(6,2,2) + >>> data = array([1,2,3,4,5,6]).repeat(4).reshape(6,2,2) >>> bsr_matrix( (data,indices,indptr), shape=(6,6) ).todense() matrix([[1, 1, 0, 0, 2, 2], [1, 1, 0, 0, 2, 2], @@ -121,6 +121,7 @@ elif len(arg1) == 2: # (data,(row,col)) format + from coo import coo_matrix self._set_self( coo_matrix(arg1).tobsr(blocksize=blocksize) ) elif len(arg1) == 3: Modified: trunk/scipy/sparse/construct.py =================================================================== --- trunk/scipy/sparse/construct.py 2008-01-14 12:58:10 UTC (rev 3829) +++ trunk/scipy/sparse/construct.py 2008-01-14 19:29:12 UTC (rev 3830) @@ -98,21 +98,19 @@ >>> A = csr_matrix(array([[0,2],[5,0]])) >>> B = csr_matrix(array([[1,2],[3,4]])) >>> spkron(A,B).todense() - matrix([[ 0., 0., 2., 4.], - [ 0., 0., 6., 8.], - [ 5., 10., 0., 0.], - [ 15., 20., 0., 0.]]) + matrix([[ 0, 0, 2, 4], + [ 0, 0, 6, 8], + [ 5, 10, 0, 0], + [15, 20, 0, 0]]) >>> spkron(A,[[1,2],[3,4]]).todense() - matrix([[ 0., 0., 2., 4.], - [ 0., 0., 6., 8.], - [ 5., 10., 0., 0.], - [ 15., 20., 0., 0.]]) + matrix([[ 0, 0, 2, 4], + [ 0, 0, 6, 8], + [ 5, 10, 0, 0], + [15, 20, 0, 0]]) """ - #TODO optimize for small dense B and CSR A -> BSR B = coo_matrix(B) - if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: #B is fairly dense, use BSR Modified: trunk/scipy/sparse/coo.py =================================================================== --- trunk/scipy/sparse/coo.py 2008-01-14 12:58:10 UTC (rev 3829) +++ trunk/scipy/sparse/coo.py 2008-01-14 19:29:12 UTC (rev 3830) @@ -70,10 +70,10 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> coo_matrix( (3,4), dtype='i' ).todense() + >>> coo_matrix( (3,4), dtype='int32' ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]]) + [0, 0, 0, 0]], dtype=int32) >>> row = array([0,3,1,0]) >>> col = array([0,3,1,2]) @@ -84,7 +84,7 @@ [0, 0, 0, 0], [0, 0, 0, 5]]) - >>> print "example with duplicates" + >>> # example with duplicates >>> row = array([0,0,1,3,1,0,0]) >>> col = array([0,2,1,3,1,0,0]) >>> data = array([1,1,1,1,1,1,1]) Modified: trunk/scipy/sparse/csc.py =================================================================== --- trunk/scipy/sparse/csc.py 2008-01-14 12:58:10 UTC (rev 3829) +++ trunk/scipy/sparse/csc.py 2008-01-14 19:29:12 UTC (rev 3830) @@ -63,26 +63,26 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> csc_matrix( (3,4), dtype='i' ).todense() + >>> csc_matrix( (3,4), dtype='int32' ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]]) + [0, 0, 0, 0]], dtype=int32) - >>> row = array([0,0,1,2,2,2]) - >>> col = array([0,2,2,0,1,2]) + >>> row = array([0,2,2,0,1,2]) + >>> col = array([0,0,1,2,2,2]) >>> data = array([1,2,3,4,5,6]) >>> csc_matrix( (data,(row,col)), shape=(3,3) ).todense() - matrix([[1, 0, 2], - [0, 0, 3], - [4, 5, 6]]) + matrix([[1, 0, 4], + [0, 0, 5], + [2, 3, 6]]) >>> indptr = array([0,2,3,6]) >>> indices = array([0,2,2,0,1,2]) - >>> data = array([1,4,6,2,3,5]) + >>> data = array([1,2,3,4,5,6]) >>> csc_matrix( (data,indices,indptr), shape=(3,3) ).todense() - matrix([[1, 0, 2], - [0, 0, 3], - [4, 5, 6]]) + matrix([[1, 0, 4], + [0, 0, 5], + [2, 3, 6]]) """ Modified: trunk/scipy/sparse/csr.py =================================================================== --- trunk/scipy/sparse/csr.py 2008-01-14 12:58:10 UTC (rev 3829) +++ trunk/scipy/sparse/csr.py 2008-01-14 19:29:12 UTC (rev 3830) @@ -65,10 +65,10 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> csr_matrix( (3,4), dtype='i' ).todense() + >>> csr_matrix( (3,4), dtype='int32' ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]]) + [0, 0, 0, 0]], dtype=int32) >>> row = array([0,0,1,2,2,2]) >>> col = array([0,2,2,0,1,2]) Modified: trunk/scipy/sparse/dia.py =================================================================== --- trunk/scipy/sparse/dia.py 2008-01-14 12:58:10 UTC (rev 3829) +++ trunk/scipy/sparse/dia.py 2008-01-14 19:29:12 UTC (rev 3830) @@ -32,13 +32,12 @@ Examples ======== - >>> from scipy.sparse import * >>> from scipy import * - >>> dia_matrix( (3,4), dtype='i').todense() + >>> dia_matrix( (3,4), dtype='int32').todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]]) + [0, 0, 0, 0]], dtype=int32) >>> data = array([[1,2,3,4]]).repeat(3,axis=0) >>> diags = array([0,-1,2]) Modified: trunk/scipy/sparse/info.py =================================================================== --- trunk/scipy/sparse/info.py 2008-01-14 12:58:10 UTC (rev 3829) +++ trunk/scipy/sparse/info.py 2008-01-14 19:29:12 UTC (rev 3830) @@ -41,22 +41,22 @@ >>> A[1, 100:200] = A[0, :100] >>> A.setdiag(rand(1000)) - Now convert it to CSR format and solve (A A^T) x = b for x: + Now convert it to CSR format and solve A x = b for x: >>> A = A.tocsr() >>> b = rand(1000) - >>> x = linsolve.spsolve(A * A.T, b) + >>> x = linsolve.spsolve(A, b) Convert it to a dense matrix and solve, and check that the result is the same: - >>> A_ = A.todense() - >>> x_ = linalg.solve(A_ * A_.T, b) - >>> err = linalg.norm(x-x_) + >>> x_ = linalg.solve(A.todense(), b) - Now we can print the error norm with: + Now we can compute norm of the error with: - >>> print "Norm error =", err + >>> err = linalg.norm(x-x_) + >>> err < 1e-10 + True It should be small :) From scipy-svn at scipy.org Mon Jan 14 14:54:52 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 14 Jan 2008 13:54:52 -0600 (CST) Subject: [Scipy-svn] r3831 - in trunk/scipy/sandbox/multigrid: . gallery gallery/tests tests Message-ID: <20080114195452.B30B439C3BC@new.scipy.org> Author: wnbell Date: 2008-01-14 13:54:37 -0600 (Mon, 14 Jan 2008) New Revision: 3831 Removed: trunk/scipy/sandbox/multigrid/dec_example.py trunk/scipy/sandbox/multigrid/simple_example.py Modified: trunk/scipy/sandbox/multigrid/adaptive.py trunk/scipy/sandbox/multigrid/gallery/poisson.py trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py trunk/scipy/sandbox/multigrid/sa.py trunk/scipy/sandbox/multigrid/tests/test_adaptive.py trunk/scipy/sandbox/multigrid/tests/test_sa.py trunk/scipy/sandbox/multigrid/tests/test_utils.py trunk/scipy/sandbox/multigrid/utils.py Log: updated poisson() gallery function Modified: trunk/scipy/sandbox/multigrid/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -7,7 +7,7 @@ from relaxation import gauss_seidel from multilevel import multilevel_solver from sa import sa_constant_interpolation,sa_fit_candidates -from utils import approximate_spectral_radius,hstack_csr,vstack_csr,expand_into_blocks,diag_sparse +from utils import approximate_spectral_radius,hstack_csr,vstack_csr,diag_sparse Deleted: trunk/scipy/sandbox/multigrid/dec_example.py =================================================================== --- trunk/scipy/sandbox/multigrid/dec_example.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/dec_example.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -1,241 +0,0 @@ - -from scipy import * -from scipy.sparse import * -from pydec import * -from pydec.multigrid.discrete_laplacian import boundary_hierarchy, discrete_laplacian_solver, hodge_solver - -from scipy.sandbox.multigrid import smoothed_aggregation_solver,multigridtools,multilevel_solver -from scipy.sandbox.multigrid.adaptive import adaptive_sa_solver -from scipy.sandbox.multigrid.sa import sa_smoothed_prolongator -from scipy.sandbox.multigrid.utils import expand_into_blocks - - -## Load mesh from file -mesh_path = '../../../../../hirani_group/wnbell/meshes/' -#mesh = read_mesh(mesh_path + 'rocket/rocket.xml') -#mesh = read_mesh(mesh_path + 'genus3/genus3_168k.xml') -#mesh = read_mesh(mesh_path + 'genus3/genus3_455k.xml') -#mesh = read_mesh(mesh_path + '/torus/torus.xml') -mesh = read_mesh(mesh_path + '/sq14tri/sq14tri.xml') -for i in range(5): - mesh['vertices'],mesh['elements'] = loop_subdivision(mesh['vertices'],mesh['elements']) -cmplx = simplicial_complex(mesh['vertices'],mesh['elements']) - -## Construct mesh manually -#bitmap = ones((60,60),dtype='bool') -#bitmap[1::10,1::10] = False -#bitmap[100:150,100:400] = False -#cmplx = regular_cube_complex(regular_cube_mesh(bitmap)) - -def curl_curl_prolongator(D_nodal,vertices): - if not isspmatrix_csr(D_nodal): - raise TypeError('expected csr_matrix') - - A = D_nodal.T.tocsr() * D_nodal - aggs = multigridtools.sa_get_aggregates(A.shape[0],A.indptr,A.indices) - - num_edges = D_nodal.shape[0] - num_basis = vertices.shape[1] - num_aggs = aggs.max() + 1 - - # replace with CSR + eliminate duplicates - #indptr = (2*num_basis) * arange(num_edges+1) - ## same same - #csr_matrix((data,indices,indptr),shape=(num_edges,num_aggs)) - - row = arange(num_edges).repeat(2*num_basis) - col = (num_basis*aggs[D_nodal.indices]).repeat(num_basis) - col = col.reshape(-1,num_basis) + arange(num_basis) - col = col.reshape(-1) - data = tile(0.5 * (D_nodal*vertices),(1,2)).reshape(-1) - - return coo_matrix((data,(row,col)),shape=(num_edges,num_basis*num_aggs)).tocsr() - - - - - -def whitney_innerproduct_cache(cmplx,k): - h = hash(cmplx.vertices.tostring()) ^ hash(cmplx.simplices.tostring()) ^ hash(k) - - filename = "/home/nathan/.pydec/cache/whitney_" + str(h) + ".mtx" - - try: - import pydec - M = pydec.io.read_array(filename) - except: - import pydec - M = whitney_innerproduct(cmplx,k) - pydec.io.write_array(filename,M) - - return M - - - -def cube_innerproduct_cache(cmplx,k): - h = hash(cmplx.mesh.bitmap.tostring()) ^ hash(cmplx.mesh.bitmap.shape) ^ hash(k) - - filename = "/home/nathan/.pydec/cache/cube_" + str(h) + ".mtx" - - try: - import pydec - M = pydec.io.read_array(filename) - except: - import pydec - M = regular_cube_innerproduct(cmplx,k) - pydec.io.write_array(filename,M) - - return M - - - -#solve d_k d_k problem for all reasonable k -#from pylab import semilogy,show,xlabel,ylabel,legend,ylim,xlim -#from matplotlib.font_manager import fontManager, FontProperties - -cochain_complex = cmplx.cochain_complex() - -for i in [1]: #range(len(cochain_complex)-1): - print "computing mass matrix" - - if isinstance(cmplx,simplicial_complex): - Mi = whitney_innerproduct_cache(cmplx,i+1) - else: - Mi = regular_cube_innerproduct(cmplx,i+1) - - - dimension = mesh['vertices'].shape[1] - - if True: - - d0 = cmplx[0].d - d1 = cmplx[1].d - - #A = (d1.T.tocsr() * d1 + d0 * d0.T.tocsr()).astype('d') - A = (d1.T.tocsr() * d1).astype('d') - - P = curl_curl_prolongator(d0,mesh['vertices']) - - num_blocks = P.shape[1]/dimension - blocks = arange(num_blocks).repeat(dimension) - - P = sa_smoothed_prolongator(A,P,epsilon=0,omega=4.0/3.0) - - PAP = P.T.tocsr() * A * P - - candidates = None - candidates = zeros((num_blocks,dimension,dimension)) - for n in range(dimension): - candidates[:,n,n] = 1.0 - candidates = candidates.reshape(-1,dimension) - - ml = smoothed_aggregation_solver(PAP,epsilon=0.0,candidates=candidates,blocks=blocks) - #A = PAP - ml = multilevel_solver([A] + ml.As, [P] + ml.Ps) - else: - - bh = boundary_hierarchy(cochain_complex) - while len(bh) < 3: - bh.coarsen() - print repr(bh) - - N = len(cochain_complex) - 1 - - B = bh[0][N - i].B - - A = (B.T.tocsr() * B).astype('d') - #A = B.T.tocsr() * Mi * B - - constant_prolongators = [lvl[N - i].I for lvl in bh[:-1]] - - method = 'aSA' - - if method == 'RS': - As = [A] - Ps = [] - for T in constant_prolongators: - Ps.append( sa_smoothed_prolongator(As[-1],T,epsilon=0.0,omega=4.0/3.0) ) - As.append(Ps[-1].T.tocsr() * As[-1] * Ps[-1]) - ml = multilevel_solver(As,Ps) - - else: - if method == 'BSA': - if i == 0: - candidates = None - else: - candidates = cmplx[0].d * mesh['vertices'] - K = candidates.shape[1] - - constant_prolongators = [constant_prolongators[0]] + \ - [expand_into_blocks(T,K,1).tocsr() for T in constant_prolongators[1:] ] - - ml = smoothed_aggregation_solver(A,candidates,aggregation=constant_prolongators) - elif method == 'aSA': - asa = adaptive_sa_solver(A,aggregation=constant_prolongators,max_candidates=dimension,epsilon=0.0) - ml = asa.solver - else: - raise ValuerError,'unknown method' - - #ml = smoothed_aggregation_solver(A,candidates) - - #x = d0 * mesh['vertices'][:,0] - x = rand(A.shape[0]) - b = zeros_like(x) - #b = A*rand(A.shape[0]) - - if True: - x_sol,residuals = ml.solve(b,x0=x,maxiter=50,tol=1e-12,return_residuals=True) - else: - residuals = [] - def add_resid(x): - residuals.append(linalg.norm(b - A*x)) - A.psolve = ml.psolve - - from pydec import cg - x_sol = cg(A,b,x0=x,maxiter=40,tol=1e-8,callback=add_resid)[0] - - - residuals = array(residuals)/residuals[0] - avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) - print "average convergence ratio",avg_convergence_ratio - print "last convergence ratio",residuals[-1]/residuals[-2] - - print residuals - - - - -##candidates = None -##blocks = None -## -## -## -##A = io.mmread('tests/sample_data/elas30_A.mtx').tocsr() -##candidates = io.mmread('tests/sample_data/elas30_nullspace.mtx') -##candidates = [ array(candidates[:,x]) for x in range(candidates.shape[1]) ] -##blocks = arange(A.shape[0]/2).repeat(2) -## -##ml = smoothed_aggregation_solver(A,candidates,blocks=blocks,epsilon=0,max_coarse=10,max_levels=10) -###ml = ruge_stuben_solver(A) -## -##x = rand(A.shape[0]) -###b = zeros_like(x) -##b = A*rand(A.shape[0]) -## -##if True: -## x_sol,residuals = ml.solve(b,x0=x,maxiter=30,tol=1e-12,return_residuals=True) -##else: -## residuals = [] -## def add_resid(x): -## residuals.append(linalg.norm(b - A*x)) -## A.psolve = ml.psolve -## x_sol = linalg.cg(A,b,x0=x,maxiter=25,tol=1e-12,callback=add_resid)[0] -## -## -##residuals = array(residuals)/residuals[0] -##avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) -##print "average convergence ratio",avg_convergence_ratio -##print "last convergence ratio",residuals[-1]/residuals[-2] -## -##print residuals -## Modified: trunk/scipy/sandbox/multigrid/gallery/poisson.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/poisson.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/gallery/poisson.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -1,55 +1,84 @@ __all__ = ['poisson'] -from scipy import array, empty -from scipy.sparse import dia_matrix +from scipy import arange, empty, intc, ravel, prod +from scipy.sparse import coo_matrix -def poisson(N, stencil='5pt', dtype=float, format=None): - """Finite Difference approximations to the Poisson problem - TheDirichlet boundary conditions are +def poisson( grid, spacing=None, dtype=float, format=None): + """Finite Difference approximation to the Poisson problem on a + regular n-dimensional grid with Dirichlet boundary conditions. Parameters ========== - - N : integer - - grid size - - stencil : one of the following strings - - '3pt' : 3-point Finite Difference stencil in 1 dimension - - '5pt' : 5-point Finite Difference stencil in 2 dimensions - - '8pt' : NotImplemented - - '27pt' : NotImplemented + - grid : tuple + - grid dimensions e.g. (100,100) + + Examples + ======== + + >>> # 4 nodes in one dimension + >>> poisson( (4,) ).todense() + matrix([[ 2., -1., 0., 0.], + [-1., 2., -1., 0.], + [ 0., -1., 2., -1.], + [ 0., 0., -1., 2.]]) + + >>> # rectangular two dimensional grid + >>> poisson( (2,3) ).todense() + matrix([[ 4., -1., 0., -1., 0., 0.], + [-1., 4., -1., 0., -1., 0.], + [ 0., -1., 4., 0., 0., -1.], + [-1., 0., 0., 4., -1., 0.], + [ 0., -1., 0., -1., 4., -1.], + [ 0., 0., -1., 0., -1., 4.]]) + """ - if N < 1: - raise ValueError,'invalid grid size %s' % N + grid = tuple(grid) - if stencil == '3pt': - if N == 1: - diags = array( [[2]], dtype=dtype) - return dia_matrix((diags,[0]), shape=(1,1)).asformat(format) - else: - data = empty((3,N),dtype=dtype) - data[0,:] = 2 #main diagonal - data[1,:] = -1 - data[2,:] = -1 - - return dia_matrix((data,[0,-1,1]),shape=(N,N)).asformat(format) - elif stencil == '5pt': - if N == 1: - data = array( [[4]], dtype=dtype) - return dia_matrix((diags,[0]), shape=(1,1)).asformat(format) - else: - diags = array([0,-N,N,-1,1]) + D = len(grid) # grid dimension - data = empty((5,N**2),dtype=dtype) + if D < 1 or min(grid) < 1: + raise ValueError,'invalid grid shape: %s' % str(grid) - data[0] = 4 #main diagonal - data[1::,:] = -1 - data[3,N-1::N] = 0 - data[4,N::N] = 0 - - return dia_matrix((data,diags),shape=(N**2,N**2)).asformat(format) - else: - raise NotImplementedError,'unsupported stencil=%s' % stencil + nodes = arange(prod(grid)).reshape(*grid) + nnz = nodes.size + for i in range(D): + nnz += 2 * prod( grid[:i] + grid[i+1:] ) * (grid[i] - 1) + + row = empty(nnz, dtype=intc) + col = empty(nnz, dtype=intc) + data = empty(nnz, dtype=dtype) + + row[:nodes.size] = ravel(nodes) + col[:nodes.size] = ravel(nodes) + data[:nodes.size] = 2*D + data[nodes.size:] = -1 + + ptr = nodes.size + + for i in range(D): + s0 = [slice(None)] * i + [slice(0,-1) ] + [slice(None)] * (D - i - 1) + s1 = [slice(None)] * i + [slice(1,None)] + [slice(None)] * (D - i - 1) + + n0 = nodes[s0] + n1 = nodes[s1] + + row0 = row[ ptr:ptr + n0.size].reshape(n0.shape) + col0 = col[ ptr:ptr + n0.size].reshape(n0.shape) + ptr += n0.size + + row1 = row[ ptr:ptr + n0.size].reshape(n0.shape) + col1 = col[ ptr:ptr + n0.size].reshape(n0.shape) + ptr += n0.size + + row0[:] = n0 + col0[:] = n1 + + row1[:] = n1 + col1[:] = n0 + + return coo_matrix((data,(row,col)),shape=(nodes.size,nodes.size)).asformat(format) Modified: trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -5,22 +5,21 @@ from scipy.sandbox.multigrid.gallery.poisson import * class TestPoisson(TestCase): - def test_3pt(self): + def test_poisson(self): cases = [] - cases.append( (1,matrix([[2]])) ) - cases.append( (2,matrix([[ 2,-1], - [-1, 2]])) ) - cases.append( (4,matrix([[ 2,-1, 0, 0], - [-1, 2,-1, 0], - [ 0,-1, 2,-1], - [ 0, 0,-1, 2]])) ) + cases.append( ((1,),matrix([[2]])) ) + cases.append( ((2,),matrix([[ 2,-1], + [-1, 2]])) ) + cases.append( ((4,),matrix([[ 2,-1, 0, 0], + [-1, 2,-1, 0], + [ 0,-1, 2,-1], + [ 0, 0,-1, 2]])) ) + + for grid,expected in cases: + assert_equal( poisson(grid).todense(), expected ) - for N,expected in cases: - assert_equal( poisson(N,stencil='3pt').todense(), expected ) - - if __name__ == '__main__': unittest.main() Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -5,7 +5,7 @@ from scipy.sparse import csr_matrix, isspmatrix_csr, bsr_matrix, isspmatrix_bsr from utils import diag_sparse, approximate_spectral_radius, \ - symmetric_rescaling, expand_into_blocks, scale_columns + symmetric_rescaling, scale_columns import multigridtools __all__ = ['sa_filtered_matrix','sa_strong_connections','sa_constant_interpolation', @@ -105,10 +105,6 @@ N_fine,N_coarse = AggOp.shape - #if blocksize > 1: - # #see if fine space has been expanded (all levels except for first) - # AggOp = expand_into_blocks(AggOp,blocksize,1).tocsr() - R = zeros((N_coarse,K,K),dtype=candidates.dtype) #storage for coarse candidates candidate_matrices = [] @@ -124,7 +120,6 @@ #orthogonalize X against previous for j,A in enumerate(candidate_matrices): - #import pdb; pdb.set_trace() D_AtX = bsr_matrix((A.data*X.data,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of A.T * X R[:,j,i] = D_AtX X.data -= scale_columns(A,D_AtX).data @@ -141,7 +136,6 @@ candidate_matrices.append(X) - # expand AggOp blocks horizontally Q_indptr = AggOp.indptr Q_indices = AggOp.indices Q_data = empty((AggOp.nnz,blocksize,K)) #if AggOp includes all nodes, then this is (N_fine * K) Deleted: trunk/scipy/sandbox/multigrid/simple_example.py =================================================================== --- trunk/scipy/sandbox/multigrid/simple_example.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/simple_example.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -1,28 +0,0 @@ -from scipy import * -from scipy.sandbox.multigrid.sa import * -from scipy.sandbox.multigrid import * -from scipy.sandbox.multigrid.utils import * -from time import clock - -mats = io.loadmat('/home/nathan/Work/ogroup/matrices/elasticity/simple_grid_2d/elasticity_500x500.mat') -A = mats['A'].tobsr(blocksize=(2,2)) -B = mats['B'] - -#A = poisson_problem2D(50) -#B = None - -start = clock() -sa = smoothed_aggregation_solver(A,B=B) -print "constructed solver in %s seconds" % (clock() - start) - -x0 = rand(A.shape[0]) -b = zeros_like(x0) -start = clock() -x,residuals = sa.solve(b,x0=x0,return_residuals=True) -print "solved in %s seconds" % (clock() - start) - -residuals = array(residuals)/residuals[0] -avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) -print "average convergence ratio",avg_convergence_ratio -print "last convergence ratio",residuals[-1]/residuals[-2] -print 'residuals',residuals Modified: trunk/scipy/sandbox/multigrid/tests/test_adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -8,62 +8,59 @@ from scipy.sandbox.multigrid.adaptive import augment_candidates -#import pdb; pdb.set_trace() class TestAdaptiveSA(TestCase): def setUp(self): pass -class TestAugmentCandidates(TestCase): - def setUp(self): - self.cases = [] +#class TestAugmentCandidates(TestCase): +# def setUp(self): +# self.cases = [] +# +# #two candidates +# +# ##block candidates +# ##self.cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), vstack((array([1]*9 + [0]*9),arange(2*9))).T )) +# +# def test_first_level(self): +# cases = [] +# +# ## tests where AggOp includes all DOFs +# cases.append((csr_matrix((ones(4),array([0,0,1,1]),arange(5)),shape=(4,2)), vstack((ones(4),arange(4))).T )) +# cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), vstack((ones(9),arange(9))).T )) +# cases.append((csr_matrix((ones(9),array([0,0,1,1,2,2,3,3,3]),arange(10)),shape=(9,4)), vstack((ones(9),arange(9))).T )) +# +# ## tests where AggOp excludes some DOFs +# cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), vstack((ones(5),arange(5))).T )) +# +# # overdetermined blocks +# cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), vstack((ones(5),arange(5),arange(5)**2)).T )) +# cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9),arange(9)**2)).T )) +# cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9))).T )) +# +# def mask_candidate(AggOp,candidates): +# #mask out all DOFs that are not included in the aggregation +# candidates[diff(AggOp.indptr) == 0,:] = 0 +# +# for AggOp,fine_candidates in cases: +# +# mask_candidate(AggOp,fine_candidates) +# +# for i in range(1,fine_candidates.shape[1]): +# Q_expected,R_expected = sa_fit_candidates(AggOp,fine_candidates[:,:i+1]) +# +# old_Q, old_R = sa_fit_candidates(AggOp,fine_candidates[:,:i]) +# +# Q_result,R_result = augment_candidates(AggOp, old_Q, old_R, fine_candidates[:,[i]]) +# +# # compare against SA method (which is assumed to be correct) +# assert_almost_equal(Q_expected.todense(),Q_result.todense()) +# assert_almost_equal(R_expected,R_result) +# +# #each fine level candidate should be fit exactly +# assert_almost_equal(fine_candidates[:,:i+1],Q_result*R_result) +# assert_almost_equal(Q_result*(Q_result.T*fine_candidates[:,:i+1]),fine_candidates[:,:i+1]) +# - #two candidates - - ##block candidates - ##self.cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), vstack((array([1]*9 + [0]*9),arange(2*9))).T )) - - - - def test_first_level(self): - cases = [] - - ## tests where AggOp includes all DOFs - cases.append((csr_matrix((ones(4),array([0,0,1,1]),arange(5)),shape=(4,2)), vstack((ones(4),arange(4))).T )) - cases.append((csr_matrix((ones(9),array([0,0,0,1,1,1,2,2,2]),arange(10)),shape=(9,3)), vstack((ones(9),arange(9))).T )) - cases.append((csr_matrix((ones(9),array([0,0,1,1,2,2,3,3,3]),arange(10)),shape=(9,4)), vstack((ones(9),arange(9))).T )) - - ## tests where AggOp excludes some DOFs - cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), vstack((ones(5),arange(5))).T )) - - # overdetermined blocks - cases.append((csr_matrix((ones(4),array([0,0,1,1]),array([0,1,2,2,3,4])),shape=(5,2)), vstack((ones(5),arange(5),arange(5)**2)).T )) - cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9),arange(9)**2)).T )) - cases.append((csr_matrix((ones(6),array([1,3,0,2,1,0]),array([0,0,1,2,2,3,4,5,5,6])),shape=(9,4)), vstack((ones(9),arange(9))).T )) - - def mask_candidate(AggOp,candidates): - #mask out all DOFs that are not included in the aggregation - candidates[diff(AggOp.indptr) == 0,:] = 0 - - for AggOp,fine_candidates in cases: - - mask_candidate(AggOp,fine_candidates) - - for i in range(1,fine_candidates.shape[1]): - Q_expected,R_expected = sa_fit_candidates(AggOp,fine_candidates[:,:i+1]) - - old_Q, old_R = sa_fit_candidates(AggOp,fine_candidates[:,:i]) - - Q_result,R_result = augment_candidates(AggOp, old_Q, old_R, fine_candidates[:,[i]]) - - # compare against SA method (which is assumed to be correct) - assert_almost_equal(Q_expected.todense(),Q_result.todense()) - assert_almost_equal(R_expected,R_result) - - #each fine level candidate should be fit exactly - assert_almost_equal(fine_candidates[:,:i+1],Q_result*R_result) - assert_almost_equal(Q_result*(Q_result.T*fine_candidates[:,:i+1]),fine_candidates[:,:i+1]) - - if __name__ == '__main__': unittest.main() Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -22,7 +22,7 @@ from scipy.sandbox.multigrid.multilevel import smoothed_aggregation_solver from scipy.sandbox.multigrid.utils import diag_sparse -from scipy.sandbox.multigrid.gallery import poisson +from scipy.sandbox.multigrid.gallery.poisson import poisson #def sparsity(A): # A = A.copy() @@ -48,9 +48,9 @@ # poisson problems in 1D and 2D for N in [2,3,5,7,10,11,19]: - self.cases.append( poisson(N,stencil='3pt',format='csr') ) + self.cases.append( poisson( (N,), format='csr') ) for N in [2,3,5,7,10,11]: - self.cases.append( poisson(N,stencil='5pt',format='csr') ) + self.cases.append( poisson( (N,N), format='csr') ) def test_sa_strong_connections(self): @@ -74,7 +74,7 @@ #assert_array_equal(S_result.todense(),S_expected.todense()) # two aggregates in 1D - A = poisson(6,stencil='3pt') + A = poisson( (6,), format='csr') AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) candidates = ones((6,1)) @@ -106,13 +106,13 @@ user_cases = [] #simple 1d example w/ two aggregates - A = poisson(6, stencil='3pt', format='csr') + A = poisson( (6,), format='csr') AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) candidates = ones((6,1)) user_cases.append((A,AggOp,candidates)) #simple 1d example w/ two aggregates (not all nodes are aggregated) - A = poisson(6, stencil='3pt', format='csr') + A = poisson( (6,), format='csr') AggOp = csr_matrix((ones(4),array([0,0,1,1]),array([0,1,1,2,3,3,4])),shape=(6,2)) candidates = ones((6,1)) user_cases.append((A,AggOp,candidates)) @@ -183,8 +183,8 @@ def setUp(self): self.cases = [] - self.cases.append(( poisson(100, stencil='3pt', format='csr'), None)) - self.cases.append(( poisson(100, stencil='5pt', format='csr'), None)) + self.cases.append(( poisson( (100,), format='csr'), None)) + self.cases.append(( poisson( (100,100), format='csr'), None)) # TODO add unstructured tests Modified: trunk/scipy/sandbox/multigrid/tests/test_utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -8,13 +8,9 @@ from scipy.linalg import norm -from scipy.sandbox.multigrid.utils import approximate_spectral_radius, \ - infinity_norm, diag_sparse, \ - symmetric_rescaling, \ - expand_into_blocks +from scipy.sandbox.multigrid.utils import * +from scipy.sandbox.multigrid.utils import symmetric_rescaling - - class TestUtils(TestCase): def test_approximate_spectral_radius(self): cases = [] @@ -105,28 +101,7 @@ D_sqrt,D_sqrt_inv = diag_sparse(D_sqrt),diag_sparse(D_sqrt_inv) assert_almost_equal((D_sqrt_inv*A*D_sqrt_inv).todense(), DAD.todense()) - def test_expand_into_blocks(self): - cases = [] - cases.append( ( matrix([[1]]), (1,2) ) ) - cases.append( ( matrix([[1]]), (2,1) ) ) - cases.append( ( matrix([[1]]), (2,2) ) ) - cases.append( ( matrix([[1,2]]), (1,2) ) ) - cases.append( ( matrix([[1,2],[3,4]]), (2,2) ) ) - cases.append( ( matrix([[0,0],[0,0]]), (3,1) ) ) - cases.append( ( matrix([[0,1,0],[0,2,3]]), (3,2) ) ) - cases.append( ( matrix([[1,0,0],[2,0,3]]), (2,5) ) ) - for A,shape in cases: - m,n = shape - result = expand_into_blocks(csr_matrix(A),m,n).todense() - expected = zeros((m*A.shape[0],n*A.shape[1])) - for i in range(m): - for j in range(n): - expected[i::m,j::n] = A - - assert_equal(expected,result) - - if __name__ == '__main__': unittest.main() Modified: trunk/scipy/sandbox/multigrid/utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/utils.py 2008-01-14 19:29:12 UTC (rev 3830) +++ trunk/scipy/sandbox/multigrid/utils.py 2008-01-14 19:54:37 UTC (rev 3831) @@ -1,5 +1,5 @@ __all__ =['approximate_spectral_radius','infinity_norm','diag_sparse', - 'hstack_csr','vstack_csr','expand_into_blocks'] + 'hstack_csr','vstack_csr'] import numpy import scipy @@ -238,41 +238,41 @@ return coo_matrix((V,(I,J)),shape=(A.shape[0]+B.shape[0],A.shape[1])).tocsr() -def expand_into_blocks(A,m,n): - """Expand each element in a sparse matrix A into an m-by-n block. - Example: - >>> A.todense() - matrix([[ 1., 2.], - [ 4., 5.]]) - >>> expand_into_blocks(A,2,2).todense() - matrix([[ 1., 1., 2., 2.], - [ 1., 1., 2., 2.], - [ 4., 4., 5., 5.], - [ 4., 4., 5., 5.]]) - """ - #TODO EXPLAIN MORE - #TODO use spkron instead, time for compairson - if m == 1 and n == 1: - return A #nothing to do - A = A.tocoo() - # expand 1x1 -> mxn - row = ( m*A.row ).repeat(m*n).reshape(-1,m,n) - col = ( n*A.col ).repeat(m*n).reshape(-1,m,n) - # increment indices - row += tile(arange(m).reshape(-1,1),(1,n)) - col += tile(arange(n).reshape(1,-1),(m,1)) - # flatten - row = row.reshape(-1) - col = col.reshape(-1) - data = A.data.repeat(m*n) - return coo_matrix((data,(row,col)),shape=(m*A.shape[0],n*A.shape[1])) + + + + + + + + + + + + + + + + + + + + + + + + + + + + From scipy-svn at scipy.org Mon Jan 14 15:01:34 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 14 Jan 2008 14:01:34 -0600 (CST) Subject: [Scipy-svn] r3832 - in trunk/scipy/sandbox/multigrid: gallery gallery/tests tests Message-ID: <20080114200134.C6F1339C093@new.scipy.org> Author: wnbell Date: 2008-01-14 14:01:29 -0600 (Mon, 14 Jan 2008) New Revision: 3832 Added: trunk/scipy/sandbox/multigrid/gallery/laplacian.py trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py Removed: trunk/scipy/sandbox/multigrid/gallery/poisson.py trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py Modified: trunk/scipy/sandbox/multigrid/gallery/__init__.py trunk/scipy/sandbox/multigrid/tests/test_sa.py Log: moved poisson.py to laplacian.py Modified: trunk/scipy/sandbox/multigrid/gallery/__init__.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/__init__.py 2008-01-14 19:54:37 UTC (rev 3831) +++ trunk/scipy/sandbox/multigrid/gallery/__init__.py 2008-01-14 20:01:29 UTC (rev 3832) @@ -2,7 +2,7 @@ from info import __doc__ -from poisson import * +from laplacian import * from elasticity import * __all__ = filter(lambda s:not s.startswith('_'),dir()) Copied: trunk/scipy/sandbox/multigrid/gallery/laplacian.py (from rev 3831, trunk/scipy/sandbox/multigrid/gallery/poisson.py) Deleted: trunk/scipy/sandbox/multigrid/gallery/poisson.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/poisson.py 2008-01-14 19:54:37 UTC (rev 3831) +++ trunk/scipy/sandbox/multigrid/gallery/poisson.py 2008-01-14 20:01:29 UTC (rev 3832) @@ -1,84 +0,0 @@ -__all__ = ['poisson'] - -from scipy import arange, empty, intc, ravel, prod -from scipy.sparse import coo_matrix - - -def poisson( grid, spacing=None, dtype=float, format=None): - """Finite Difference approximation to the Poisson problem on a - regular n-dimensional grid with Dirichlet boundary conditions. - - - Parameters - ========== - - grid : tuple - - grid dimensions e.g. (100,100) - - - Examples - ======== - - >>> # 4 nodes in one dimension - >>> poisson( (4,) ).todense() - matrix([[ 2., -1., 0., 0.], - [-1., 2., -1., 0.], - [ 0., -1., 2., -1.], - [ 0., 0., -1., 2.]]) - - >>> # rectangular two dimensional grid - >>> poisson( (2,3) ).todense() - matrix([[ 4., -1., 0., -1., 0., 0.], - [-1., 4., -1., 0., -1., 0.], - [ 0., -1., 4., 0., 0., -1.], - [-1., 0., 0., 4., -1., 0.], - [ 0., -1., 0., -1., 4., -1.], - [ 0., 0., -1., 0., -1., 4.]]) - - """ - grid = tuple(grid) - - D = len(grid) # grid dimension - - if D < 1 or min(grid) < 1: - raise ValueError,'invalid grid shape: %s' % str(grid) - - nodes = arange(prod(grid)).reshape(*grid) - - nnz = nodes.size - for i in range(D): - nnz += 2 * prod( grid[:i] + grid[i+1:] ) * (grid[i] - 1) - - row = empty(nnz, dtype=intc) - col = empty(nnz, dtype=intc) - data = empty(nnz, dtype=dtype) - - row[:nodes.size] = ravel(nodes) - col[:nodes.size] = ravel(nodes) - data[:nodes.size] = 2*D - data[nodes.size:] = -1 - - ptr = nodes.size - - for i in range(D): - s0 = [slice(None)] * i + [slice(0,-1) ] + [slice(None)] * (D - i - 1) - s1 = [slice(None)] * i + [slice(1,None)] + [slice(None)] * (D - i - 1) - - n0 = nodes[s0] - n1 = nodes[s1] - - row0 = row[ ptr:ptr + n0.size].reshape(n0.shape) - col0 = col[ ptr:ptr + n0.size].reshape(n0.shape) - ptr += n0.size - - row1 = row[ ptr:ptr + n0.size].reshape(n0.shape) - col1 = col[ ptr:ptr + n0.size].reshape(n0.shape) - ptr += n0.size - - row0[:] = n0 - col0[:] = n1 - - row1[:] = n1 - col1[:] = n0 - - return coo_matrix((data,(row,col)),shape=(nodes.size,nodes.size)).asformat(format) - Copied: trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py (from rev 3831, trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py) =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py 2008-01-14 19:54:37 UTC (rev 3831) +++ trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py 2008-01-14 20:01:29 UTC (rev 3832) @@ -0,0 +1,25 @@ +from scipy.testing import * + +from scipy import matrix + +from scipy.sandbox.multigrid.gallery.laplacian import * + +class TestPoisson(TestCase): + def test_poisson(self): + cases = [] + + cases.append( ((1,),matrix([[2]])) ) + cases.append( ((2,),matrix([[ 2,-1], + [-1, 2]])) ) + cases.append( ((4,),matrix([[ 2,-1, 0, 0], + [-1, 2,-1, 0], + [ 0,-1, 2,-1], + [ 0, 0,-1, 2]])) ) + + for grid,expected in cases: + assert_equal( poisson(grid).todense(), expected ) + + + +if __name__ == '__main__': + unittest.main() Deleted: trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py 2008-01-14 19:54:37 UTC (rev 3831) +++ trunk/scipy/sandbox/multigrid/gallery/tests/test_poisson.py 2008-01-14 20:01:29 UTC (rev 3832) @@ -1,25 +0,0 @@ -from scipy.testing import * - -from scipy import matrix - -from scipy.sandbox.multigrid.gallery.poisson import * - -class TestPoisson(TestCase): - def test_poisson(self): - cases = [] - - cases.append( ((1,),matrix([[2]])) ) - cases.append( ((2,),matrix([[ 2,-1], - [-1, 2]])) ) - cases.append( ((4,),matrix([[ 2,-1, 0, 0], - [-1, 2,-1, 0], - [ 0,-1, 2,-1], - [ 0, 0,-1, 2]])) ) - - for grid,expected in cases: - assert_equal( poisson(grid).todense(), expected ) - - - -if __name__ == '__main__': - unittest.main() Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-14 19:54:37 UTC (rev 3831) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-14 20:01:29 UTC (rev 3832) @@ -22,7 +22,7 @@ from scipy.sandbox.multigrid.multilevel import smoothed_aggregation_solver from scipy.sandbox.multigrid.utils import diag_sparse -from scipy.sandbox.multigrid.gallery.poisson import poisson +from scipy.sandbox.multigrid.gallery import poisson #def sparsity(A): # A = A.copy() From scipy-svn at scipy.org Mon Jan 14 15:27:15 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 14 Jan 2008 14:27:15 -0600 (CST) Subject: [Scipy-svn] r3833 - trunk/scipy/sparse Message-ID: <20080114202715.A597D39C1A3@new.scipy.org> Author: wnbell Date: 2008-01-14 14:27:02 -0600 (Mon, 14 Jan 2008) New Revision: 3833 Modified: trunk/scipy/sparse/bsr.py trunk/scipy/sparse/coo.py trunk/scipy/sparse/csc.py trunk/scipy/sparse/csr.py trunk/scipy/sparse/dia.py Log: make doctests work the same on 32/64-bit platforms Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-14 20:01:29 UTC (rev 3832) +++ trunk/scipy/sparse/bsr.py 2008-01-14 20:27:02 UTC (rev 3833) @@ -62,10 +62,10 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> bsr_matrix( (3,4), dtype='int32' ).todense() + >>> bsr_matrix( (3,4), dtype=int8 ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]], dtype=int32) + [0, 0, 0, 0]], dtype=int8) >>> row = array([0,0,1,2,2,2]) >>> col = array([0,2,2,0,1,2]) Modified: trunk/scipy/sparse/coo.py =================================================================== --- trunk/scipy/sparse/coo.py 2008-01-14 20:01:29 UTC (rev 3832) +++ trunk/scipy/sparse/coo.py 2008-01-14 20:27:02 UTC (rev 3833) @@ -70,10 +70,10 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> coo_matrix( (3,4), dtype='int32' ).todense() + >>> coo_matrix( (3,4), dtype=int8 ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]], dtype=int32) + [0, 0, 0, 0]], dtype=int8) >>> row = array([0,3,1,0]) >>> col = array([0,3,1,2]) Modified: trunk/scipy/sparse/csc.py =================================================================== --- trunk/scipy/sparse/csc.py 2008-01-14 20:01:29 UTC (rev 3832) +++ trunk/scipy/sparse/csc.py 2008-01-14 20:27:02 UTC (rev 3833) @@ -63,10 +63,10 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> csc_matrix( (3,4), dtype='int32' ).todense() + >>> csc_matrix( (3,4), dtype=int8 ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]], dtype=int32) + [0, 0, 0, 0]], dtype=int8) >>> row = array([0,2,2,0,1,2]) >>> col = array([0,0,1,2,2,2]) Modified: trunk/scipy/sparse/csr.py =================================================================== --- trunk/scipy/sparse/csr.py 2008-01-14 20:01:29 UTC (rev 3832) +++ trunk/scipy/sparse/csr.py 2008-01-14 20:27:02 UTC (rev 3833) @@ -65,10 +65,10 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> csr_matrix( (3,4), dtype='int32' ).todense() + >>> csr_matrix( (3,4), dtype=int8 ).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]], dtype=int32) + [0, 0, 0, 0]], dtype=int8) >>> row = array([0,0,1,2,2,2]) >>> col = array([0,2,2,0,1,2]) Modified: trunk/scipy/sparse/dia.py =================================================================== --- trunk/scipy/sparse/dia.py 2008-01-14 20:01:29 UTC (rev 3832) +++ trunk/scipy/sparse/dia.py 2008-01-14 20:27:02 UTC (rev 3833) @@ -34,10 +34,10 @@ >>> from scipy.sparse import * >>> from scipy import * - >>> dia_matrix( (3,4), dtype='int32').todense() + >>> dia_matrix( (3,4), dtype=int8).todense() matrix([[0, 0, 0, 0], [0, 0, 0, 0], - [0, 0, 0, 0]], dtype=int32) + [0, 0, 0, 0]], dtype=int8) >>> data = array([[1,2,3,4]]).repeat(3,axis=0) >>> diags = array([0,-1,2]) From scipy-svn at scipy.org Mon Jan 14 16:31:17 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 14 Jan 2008 15:31:17 -0600 (CST) Subject: [Scipy-svn] r3834 - trunk/scipy/sandbox/multigrid/gallery/tests Message-ID: <20080114213117.2729F39C3C1@new.scipy.org> Author: wnbell Date: 2008-01-14 15:31:13 -0600 (Mon, 14 Jan 2008) New Revision: 3834 Modified: trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py Log: expanded poisson() unittest Modified: trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py 2008-01-14 20:27:02 UTC (rev 3833) +++ trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py 2008-01-14 21:31:13 UTC (rev 3834) @@ -8,6 +8,7 @@ def test_poisson(self): cases = [] + # 1D cases.append( ((1,),matrix([[2]])) ) cases.append( ((2,),matrix([[ 2,-1], [-1, 2]])) ) @@ -16,10 +17,35 @@ [ 0,-1, 2,-1], [ 0, 0,-1, 2]])) ) + # 2D + cases.append( ((1,1), matrix([[4]])) ) + cases.append( ((2,1), matrix([[ 4,-1], + [-1, 4]])) ) + cases.append( ((1,2), matrix([[ 4,-1], + [-1, 4]])) ) + cases.append( ((1,3), matrix([[ 4,-1, 0], + [-1, 4,-1], + [ 0,-1, 4]])) ) + cases.append( ((2,2), matrix([[ 4,-1,-1, 0], + [-1, 4, 0,-1], + [-1, 0, 4,-1], + [ 0,-1,-1, 4]])) ) + # 3D + cases.append( ((2,2,1), matrix([[ 6,-1,-1, 0], + [-1, 6, 0,-1], + [-1, 0, 6,-1], + [ 0,-1,-1, 6]])) ) + cases.append( ((2,2,2), matrix([[ 6,-1,-1, 0,-1, 0, 0, 0], + [-1, 6, 0,-1, 0,-1, 0, 0], + [-1, 0, 6,-1, 0, 0,-1, 0], + [ 0,-1,-1, 6, 0, 0, 0,-1], + [-1, 0, 0, 0, 6,-1,-1, 0], + [ 0,-1, 0, 0,-1, 6, 0,-1], + [ 0, 0,-1, 0,-1, 0, 6,-1], + [ 0, 0, 0,-1, 0,-1,-1, 6]])) ) + for grid,expected in cases: assert_equal( poisson(grid).todense(), expected ) - - if __name__ == '__main__': unittest.main() From scipy-svn at scipy.org Tue Jan 15 06:51:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 15 Jan 2008 05:51:12 -0600 (CST) Subject: [Scipy-svn] r3835 - trunk/scipy/sparse Message-ID: <20080115115112.DCDCE39C19F@new.scipy.org> Author: wnbell Date: 2008-01-15 05:51:10 -0600 (Tue, 15 Jan 2008) New Revision: 3835 Modified: trunk/scipy/sparse/bsr.py Log: use CSR matmat for 1x1 BSR Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-14 21:31:13 UTC (rev 3834) +++ trunk/scipy/sparse/bsr.py 2008-01-15 11:51:10 UTC (rev 3835) @@ -7,13 +7,14 @@ from numpy import zeros, intc, array, asarray, arange, diff, tile, rank, \ prod, ravel, empty, matrix, asmatrix, empty_like, hstack -import sparsetools -from sparsetools import bsr_matvec, csr_matmat_pass1, bsr_matmat_pass2 from data import _data_matrix from compressed import _cs_matrix from base import isspmatrix, _formats from sputils import isshape, getdtype, to_native, isscalarlike, isdense, \ upcast +import sparsetools +from sparsetools import bsr_matvec, csr_matmat_pass1, csr_matmat_pass2, \ + bsr_matmat_pass2 class bsr_matrix(_cs_matrix): """Block Sparse Row matrix @@ -329,13 +330,21 @@ indptr = empty_like( self.indptr ) R,n = self.blocksize - + + #convert to this format if isspmatrix_bsr(other): C = other.blocksize[1] else: C = 1 - other = other.tobsr(blocksize=(n,C)) #convert to this format + from csr import isspmatrix_csr + + if isspmatrix_csr(other) and n == 1: + other = other.tobsr(blocksize=(n,C),copy=False) #convert to this format + else: + other = other.tobsr(blocksize=(n,C)) + + csr_matmat_pass1( M/R, N/C, \ self.indptr, self.indices, \ other.indptr, other.indices, \ @@ -345,10 +354,17 @@ indices = empty( bnnz, dtype=intc) data = empty( R*C*bnnz, dtype=upcast(self.dtype,other.dtype)) - bsr_matmat_pass2( M/R, N/C, R, C, n, \ - self.indptr, self.indices, ravel(self.data), \ - other.indptr, other.indices, ravel(other.data), \ - indptr, indices, data) + if (R,C,n) == (1,1,1): + #use CSR * CSR when possible + csr_matmat_pass2( M, N, \ + self.indptr, self.indices, ravel(self.data), \ + other.indptr, other.indices, ravel(other.data), \ + indptr, indices, data) + else: + bsr_matmat_pass2( M/R, N/C, R, C, n, \ + self.indptr, self.indices, ravel(self.data), \ + other.indptr, other.indices, ravel(other.data), \ + indptr, indices, data) data = data.reshape(-1,R,C) #TODO eliminate zeros From scipy-svn at scipy.org Tue Jan 15 08:10:49 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 15 Jan 2008 07:10:49 -0600 (CST) Subject: [Scipy-svn] r3836 - in trunk/scipy: cluster/tests fftpack/tests integrate/tests interpolate/tests io/tests lib/blas/tests linalg/tests linsolve/umfpack/tests maxentropy/tests misc/tests ndimage/tests odr/tests optimize/tests sandbox/arpack/tests sandbox/delaunay/tests sandbox/dhuard/tests sandbox/exmplpackage/tests sandbox/fdfpack/tests sandbox/maskedarray/tests sandbox/montecarlo/tests sandbox/multigrid/gallery/tests sandbox/multigrid/tests sandbox/numexpr/tests sandbox/pyloess/tests sandbox/rbf/tests sandbox/spline/tests sandbox/timeseries/lib/tests sandbox/timeseries/tests signal/tests sparse/tests special/tests stats/models/tests stats/tests weave/tests Message-ID: <20080115131049.DC24739C0E0@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-15 07:09:03 -0600 (Tue, 15 Jan 2008) New Revision: 3836 Modified: trunk/scipy/cluster/tests/test_vq.py trunk/scipy/fftpack/tests/test_basic.py trunk/scipy/fftpack/tests/test_helper.py trunk/scipy/fftpack/tests/test_pseudo_diffs.py trunk/scipy/integrate/tests/test_integrate.py trunk/scipy/integrate/tests/test_quadpack.py trunk/scipy/integrate/tests/test_quadrature.py trunk/scipy/interpolate/tests/test_fitpack.py trunk/scipy/interpolate/tests/test_interpolate.py trunk/scipy/io/tests/test_array_import.py trunk/scipy/io/tests/test_mmio.py trunk/scipy/io/tests/test_npfile.py trunk/scipy/io/tests/test_recaster.py trunk/scipy/lib/blas/tests/test_blas.py trunk/scipy/lib/blas/tests/test_fblas.py trunk/scipy/linalg/tests/test_basic.py trunk/scipy/linalg/tests/test_blas.py trunk/scipy/linalg/tests/test_decomp.py trunk/scipy/linalg/tests/test_fblas.py trunk/scipy/linalg/tests/test_iterative.py trunk/scipy/linalg/tests/test_lapack.py trunk/scipy/linalg/tests/test_matfuncs.py trunk/scipy/linsolve/umfpack/tests/test_umfpack.py trunk/scipy/maxentropy/tests/test_maxentropy.py trunk/scipy/misc/tests/test_pilutil.py trunk/scipy/ndimage/tests/test_ndimage.py trunk/scipy/odr/tests/test_odr.py trunk/scipy/optimize/tests/test_cobyla.py trunk/scipy/optimize/tests/test_nonlin.py trunk/scipy/optimize/tests/test_optimize.py trunk/scipy/optimize/tests/test_slsqp.py trunk/scipy/optimize/tests/test_zeros.py trunk/scipy/sandbox/arpack/tests/test_arpack.py trunk/scipy/sandbox/arpack/tests/test_speigs.py trunk/scipy/sandbox/delaunay/tests/test_triangulate.py trunk/scipy/sandbox/dhuard/tests/test_histogram.py trunk/scipy/sandbox/dhuard/tests/test_stats.py trunk/scipy/sandbox/exmplpackage/tests/test_foo.py trunk/scipy/sandbox/fdfpack/tests/test_fdf.py trunk/scipy/sandbox/maskedarray/tests/test_core.py trunk/scipy/sandbox/maskedarray/tests/test_extras.py trunk/scipy/sandbox/maskedarray/tests/test_morestats.py trunk/scipy/sandbox/maskedarray/tests/test_mrecords.py trunk/scipy/sandbox/maskedarray/tests/test_mstats.py trunk/scipy/sandbox/maskedarray/tests/test_subclassing.py trunk/scipy/sandbox/montecarlo/tests/test_dictsampler.py trunk/scipy/sandbox/montecarlo/tests/test_intsampler.py trunk/scipy/sandbox/multigrid/gallery/tests/test_elasticity.py trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py trunk/scipy/sandbox/multigrid/tests/test_adaptive.py trunk/scipy/sandbox/multigrid/tests/test_relaxation.py trunk/scipy/sandbox/multigrid/tests/test_sa.py trunk/scipy/sandbox/multigrid/tests/test_utils.py trunk/scipy/sandbox/numexpr/tests/test_numexpr.py trunk/scipy/sandbox/pyloess/tests/test_mpyloess.py trunk/scipy/sandbox/pyloess/tests/test_pyloess.py trunk/scipy/sandbox/rbf/tests/test_rbf.py trunk/scipy/sandbox/spline/tests/test_fitpack.py trunk/scipy/sandbox/spline/tests/test_spline.py trunk/scipy/sandbox/timeseries/lib/tests/test_interpolate.py trunk/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py trunk/scipy/sandbox/timeseries/tests/test_dates.py trunk/scipy/sandbox/timeseries/tests/test_extras.py trunk/scipy/sandbox/timeseries/tests/test_timeseries.py trunk/scipy/sandbox/timeseries/tests/test_trecords.py trunk/scipy/signal/tests/test_signaltools.py trunk/scipy/signal/tests/test_wavelets.py trunk/scipy/sparse/tests/test_base.py trunk/scipy/sparse/tests/test_construct.py trunk/scipy/sparse/tests/test_sputils.py trunk/scipy/special/tests/test_basic.py trunk/scipy/special/tests/test_spfun_stats.py trunk/scipy/stats/models/tests/test_bspline.py trunk/scipy/stats/models/tests/test_formula.py trunk/scipy/stats/models/tests/test_glm.py trunk/scipy/stats/models/tests/test_regression.py trunk/scipy/stats/models/tests/test_rlm.py trunk/scipy/stats/models/tests/test_scale.py trunk/scipy/stats/models/tests/test_utils.py trunk/scipy/stats/tests/test_distributions.py trunk/scipy/stats/tests/test_morestats.py trunk/scipy/stats/tests/test_stats.py trunk/scipy/weave/tests/test_ast_tools.py trunk/scipy/weave/tests/test_blitz_tools.py trunk/scipy/weave/tests/test_build_tools.py trunk/scipy/weave/tests/test_c_spec.py trunk/scipy/weave/tests/test_catalog.py trunk/scipy/weave/tests/test_ext_tools.py trunk/scipy/weave/tests/test_inline_tools.py trunk/scipy/weave/tests/test_numpy_scalar_spec.py trunk/scipy/weave/tests/test_scxx.py trunk/scipy/weave/tests/test_scxx_dict.py trunk/scipy/weave/tests/test_scxx_object.py trunk/scipy/weave/tests/test_scxx_sequence.py trunk/scipy/weave/tests/test_size_check.py trunk/scipy/weave/tests/test_slice_handler.py trunk/scipy/weave/tests/test_standard_array_spec.py trunk/scipy/weave/tests/test_wx_spec.py Log: nose running for individual test file exexecution Modified: trunk/scipy/cluster/tests/test_vq.py =================================================================== --- trunk/scipy/cluster/tests/test_vq.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/cluster/tests/test_vq.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -145,4 +145,4 @@ kmeans2(data, 3, minit = 'points') if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/fftpack/tests/test_basic.py =================================================================== --- trunk/scipy/fftpack/tests/test_basic.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/fftpack/tests/test_basic.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -550,4 +550,4 @@ assert_array_almost_equal (fftn(ifftn(x)),x) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/fftpack/tests/test_helper.py =================================================================== --- trunk/scipy/fftpack/tests/test_helper.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/fftpack/tests/test_helper.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -58,4 +58,4 @@ assert_array_almost_equal(10*pi*rfftfreq(10,pi),x) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/fftpack/tests/test_pseudo_diffs.py =================================================================== --- trunk/scipy/fftpack/tests/test_pseudo_diffs.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/fftpack/tests/test_pseudo_diffs.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -432,4 +432,4 @@ print ' (secs for %s calls)' % (repeat) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/integrate/tests/test_integrate.py =================================================================== --- trunk/scipy/integrate/tests/test_integrate.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/integrate/tests/test_integrate.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -49,4 +49,4 @@ assert res < 1.0e-6 if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/integrate/tests/test_quadpack.py =================================================================== --- trunk/scipy/integrate/tests/test_quadpack.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/integrate/tests/test_quadpack.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -104,4 +104,4 @@ 8/3.0 * (b**4.0 - a**4.0)) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/integrate/tests/test_quadrature.py =================================================================== --- trunk/scipy/integrate/tests/test_quadrature.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/integrate/tests/test_quadrature.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -29,4 +29,4 @@ assert_equal(romb(numpy.arange(17)),128) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/interpolate/tests/test_fitpack.py =================================================================== --- trunk/scipy/interpolate/tests/test_fitpack.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/interpolate/tests/test_fitpack.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -82,4 +82,4 @@ assert_array_almost_equal(lut(x,y),z) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -200,4 +200,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/io/tests/test_array_import.py =================================================================== --- trunk/scipy/io/tests/test_array_import.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/io/tests/test_array_import.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -58,4 +58,4 @@ os.remove(fname) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/io/tests/test_mmio.py =================================================================== --- trunk/scipy/io/tests/test_mmio.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/io/tests/test_mmio.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -292,4 +292,4 @@ assert_array_almost_equal(a,b) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/io/tests/test_npfile.py =================================================================== --- trunk/scipy/io/tests/test_npfile.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/io/tests/test_npfile.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -102,4 +102,4 @@ assert_array_equal(npf.read_array(adt, shp, order='C'), cf_arr) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/io/tests/test_recaster.py =================================================================== --- trunk/scipy/io/tests/test_recaster.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/io/tests/test_recaster.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -173,5 +173,5 @@ 'Expected %s from %s, got %s' % (outp, inp, dtt) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/lib/blas/tests/test_blas.py =================================================================== --- trunk/scipy/lib/blas/tests/test_blas.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/lib/blas/tests/test_blas.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -223,4 +223,4 @@ """ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/lib/blas/tests/test_fblas.py =================================================================== --- trunk/scipy/lib/blas/tests/test_fblas.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/lib/blas/tests/test_fblas.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -522,4 +522,4 @@ """ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/linalg/tests/test_basic.py =================================================================== --- trunk/scipy/linalg/tests/test_basic.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/linalg/tests/test_basic.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -539,4 +539,4 @@ assert_array_almost_equal(a_pinv,a_pinv2) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/linalg/tests/test_blas.py =================================================================== --- trunk/scipy/linalg/tests/test_blas.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/linalg/tests/test_blas.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -213,4 +213,4 @@ """ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/linalg/tests/test_decomp.py =================================================================== --- trunk/scipy/linalg/tests/test_decomp.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/linalg/tests/test_decomp.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -929,4 +929,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/linalg/tests/test_fblas.py =================================================================== --- trunk/scipy/linalg/tests/test_fblas.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/linalg/tests/test_fblas.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -525,4 +525,4 @@ """ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/linalg/tests/test_iterative.py =================================================================== --- trunk/scipy/linalg/tests/test_iterative.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/linalg/tests/test_iterative.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -80,4 +80,4 @@ assert norm(dot(self.A, x) - self.b) < 5*self.tol if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/linalg/tests/test_lapack.py =================================================================== --- trunk/scipy/linalg/tests/test_lapack.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/linalg/tests/test_lapack.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -68,4 +68,4 @@ """ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/linalg/tests/test_matfuncs.py =================================================================== --- trunk/scipy/linalg/tests/test_matfuncs.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/linalg/tests/test_matfuncs.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -98,4 +98,4 @@ assert_array_almost_equal(expm3(a),[[1,0],[0,1]]) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/linsolve/umfpack/tests/test_umfpack.py =================================================================== --- trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -171,4 +171,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/maxentropy/tests/test_maxentropy.py =================================================================== --- trunk/scipy/maxentropy/tests/test_maxentropy.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/maxentropy/tests/test_maxentropy.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -36,4 +36,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/misc/tests/test_pilutil.py =================================================================== --- trunk/scipy/misc/tests/test_pilutil.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/misc/tests/test_pilutil.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -38,4 +38,4 @@ yield tst_fromimage, os.path.join(datapath,'data',fn), irange if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/ndimage/tests/test_ndimage.py =================================================================== --- trunk/scipy/ndimage/tests/test_ndimage.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/ndimage/tests/test_ndimage.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -5513,4 +5513,4 @@ # return len(result.failures), result.testsRun if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/odr/tests/test_odr.py =================================================================== --- trunk/scipy/odr/tests/test_odr.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/odr/tests/test_odr.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -311,5 +311,5 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) #### EOF ####################################################################### Modified: trunk/scipy/optimize/tests/test_cobyla.py =================================================================== --- trunk/scipy/optimize/tests/test_cobyla.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/optimize/tests/test_cobyla.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -18,4 +18,4 @@ assert_almost_equal(x, [x0, x1], decimal=5) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/optimize/tests/test_nonlin.py =================================================================== --- trunk/scipy/optimize/tests/test_nonlin.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/optimize/tests/test_nonlin.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -91,4 +91,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/optimize/tests/test_optimize.py =================================================================== --- trunk/scipy/optimize/tests/test_optimize.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/optimize/tests/test_optimize.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -243,4 +243,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/optimize/tests/test_slsqp.py =================================================================== --- trunk/scipy/optimize/tests/test_slsqp.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/optimize/tests/test_slsqp.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -86,4 +86,4 @@ assert_array_almost_equal(x,[2,1],decimal=3) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/optimize/tests/test_zeros.py =================================================================== --- trunk/scipy/optimize/tests/test_zeros.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/optimize/tests/test_zeros.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -93,4 +93,4 @@ print '\n\n' if __name__ == '__main__' : - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/arpack/tests/test_arpack.py =================================================================== --- trunk/scipy/sandbox/arpack/tests/test_arpack.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/arpack/tests/test_arpack.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -349,4 +349,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/arpack/tests/test_speigs.py =================================================================== --- trunk/scipy/sandbox/arpack/tests/test_speigs.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/arpack/tests/test_speigs.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -48,4 +48,4 @@ # 94.646308846854879, 95.30841709116271], decimal=11) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/delaunay/tests/test_triangulate.py =================================================================== --- trunk/scipy/sandbox/delaunay/tests/test_triangulate.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/delaunay/tests/test_triangulate.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -68,5 +68,5 @@ if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/dhuard/tests/test_histogram.py =================================================================== --- trunk/scipy/sandbox/dhuard/tests/test_histogram.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/dhuard/tests/test_histogram.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -96,4 +96,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/dhuard/tests/test_stats.py =================================================================== --- trunk/scipy/sandbox/dhuard/tests/test_stats.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/dhuard/tests/test_stats.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -41,4 +41,4 @@ if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/exmplpackage/tests/test_foo.py =================================================================== --- trunk/scipy/sandbox/exmplpackage/tests/test_foo.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/exmplpackage/tests/test_foo.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -16,21 +16,19 @@ """ import sys -from numpy.test.testing import * +from scipy.testing import * -set_package_path() -from exmplpackage.foo import * -del sys.path[0] +from scipy.sandbox.exmplpackage.foo import * -class TestFooBar(NumpyTestCase): +class TestFooBar(TestCase): def check_simple(self, level=1): assert exmplpackage_foo_bar()=='Hello from exmplpackage_foo_bar' -class TestFooGun(NumpyTestCase): +class TestFooGun(TestCase): def check_simple(self, level=1): assert foo_gun()=='Hello from foo_gun' if __name__ == "__main__": - NumpyTest().run() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/fdfpack/tests/test_fdf.py =================================================================== --- trunk/scipy/sandbox/fdfpack/tests/test_fdf.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/fdfpack/tests/test_fdf.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -29,4 +29,4 @@ assert_array_almost_equal(diff(sin(x),k=4,m=m)/n,sin(x)/n) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/maskedarray/tests/test_core.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_core.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/maskedarray/tests/test_core.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -1313,4 +1313,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/maskedarray/tests/test_extras.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_extras.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/maskedarray/tests/test_extras.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -325,4 +325,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/maskedarray/tests/test_morestats.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_morestats.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/maskedarray/tests/test_morestats.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -106,4 +106,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/maskedarray/tests/test_mrecords.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_mrecords.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/maskedarray/tests/test_mrecords.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -173,4 +173,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/maskedarray/tests/test_mstats.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_mstats.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/maskedarray/tests/test_mstats.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -170,4 +170,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/maskedarray/tests/test_subclassing.py =================================================================== --- trunk/scipy/sandbox/maskedarray/tests/test_subclassing.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/maskedarray/tests/test_subclassing.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -157,7 +157,7 @@ ################################################################################ if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) # if 0: x = array(arange(5), mask=[0]+[1]*4) Modified: trunk/scipy/sandbox/montecarlo/tests/test_dictsampler.py =================================================================== --- trunk/scipy/sandbox/montecarlo/tests/test_dictsampler.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/montecarlo/tests/test_dictsampler.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -73,4 +73,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/montecarlo/tests/test_intsampler.py =================================================================== --- trunk/scipy/sandbox/montecarlo/tests/test_intsampler.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/montecarlo/tests/test_intsampler.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -65,4 +65,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/multigrid/gallery/tests/test_elasticity.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/tests/test_elasticity.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/multigrid/gallery/tests/test_elasticity.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -112,4 +112,4 @@ if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py =================================================================== --- trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/multigrid/gallery/tests/test_laplacian.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -48,4 +48,4 @@ assert_equal( poisson(grid).todense(), expected ) if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/multigrid/tests/test_adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -63,4 +63,4 @@ # if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/multigrid/tests/test_relaxation.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -158,4 +158,4 @@ self.assert_(allclose(resid1,resid2)) if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -311,4 +311,4 @@ if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/multigrid/tests/test_utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -104,4 +104,4 @@ if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/numexpr/tests/test_numexpr.py =================================================================== --- trunk/scipy/sandbox/numexpr/tests/test_numexpr.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/numexpr/tests/test_numexpr.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -448,4 +448,4 @@ if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/pyloess/tests/test_mpyloess.py =================================================================== --- trunk/scipy/sandbox/pyloess/tests/test_mpyloess.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/pyloess/tests/test_mpyloess.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -430,4 +430,4 @@ ######################################################################## if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/pyloess/tests/test_pyloess.py =================================================================== --- trunk/scipy/sandbox/pyloess/tests/test_pyloess.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/pyloess/tests/test_pyloess.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -383,4 +383,4 @@ ######################################################################## if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/rbf/tests/test_rbf.py =================================================================== --- trunk/scipy/sandbox/rbf/tests/test_rbf.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/rbf/tests/test_rbf.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -39,4 +39,4 @@ assert_array_almost_equal(di, d) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/spline/tests/test_fitpack.py =================================================================== --- trunk/scipy/sandbox/spline/tests/test_fitpack.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/spline/tests/test_fitpack.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -239,4 +239,4 @@ around(abs(splev(uv[0],tck)-f(uv[0])),2),decimal=1) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/spline/tests/test_spline.py =================================================================== --- trunk/scipy/sandbox/spline/tests/test_spline.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/spline/tests/test_spline.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -162,4 +162,4 @@ assert_array_almost_equal(lut(x,y),z) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/timeseries/lib/tests/test_interpolate.py =================================================================== --- trunk/scipy/sandbox/timeseries/lib/tests/test_interpolate.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/timeseries/lib/tests/test_interpolate.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -61,4 +61,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py =================================================================== --- trunk/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/timeseries/lib/tests/test_moving_funcs.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -149,4 +149,4 @@ #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/timeseries/tests/test_dates.py =================================================================== --- trunk/scipy/sandbox/timeseries/tests/test_dates.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/timeseries/tests/test_dates.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -882,4 +882,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/timeseries/tests/test_extras.py =================================================================== --- trunk/scipy/sandbox/timeseries/tests/test_extras.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/timeseries/tests/test_extras.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -80,4 +80,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/timeseries/tests/test_timeseries.py =================================================================== --- trunk/scipy/sandbox/timeseries/tests/test_timeseries.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/timeseries/tests/test_timeseries.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -632,4 +632,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/timeseries/tests/test_trecords.py =================================================================== --- trunk/scipy/sandbox/timeseries/tests/test_trecords.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sandbox/timeseries/tests/test_trecords.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -184,4 +184,4 @@ ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -46,4 +46,4 @@ [2,3,2]) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/signal/tests/test_wavelets.py =================================================================== --- trunk/scipy/signal/tests/test_wavelets.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/signal/tests/test_wavelets.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -31,4 +31,4 @@ assert_equal(x,y) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sparse/tests/test_base.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -1295,4 +1295,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sparse/tests/test_construct.py =================================================================== --- trunk/scipy/sparse/tests/test_construct.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sparse/tests/test_construct.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -133,5 +133,5 @@ [6,5,0]]) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/sparse/tests/test_sputils.py =================================================================== --- trunk/scipy/sparse/tests/test_sputils.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/sparse/tests/test_sputils.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -67,6 +67,6 @@ assert_equal(isdense( np.matrix([1]) ),True) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/special/tests/test_basic.py =================================================================== --- trunk/scipy/special/tests/test_basic.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/special/tests/test_basic.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -1887,4 +1887,4 @@ assert_almost_equal(sy3,sphpy,4) #compare correct derivative val. (correct =-system val). if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/special/tests/test_spfun_stats.py =================================================================== --- trunk/scipy/special/tests/test_spfun_stats.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/special/tests/test_spfun_stats.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -35,4 +35,4 @@ pass if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/models/tests/test_bspline.py =================================================================== --- trunk/scipy/stats/models/tests/test_bspline.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/models/tests/test_bspline.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -20,4 +20,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/models/tests/test_formula.py =================================================================== --- trunk/scipy/stats/models/tests/test_formula.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/models/tests/test_formula.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -227,4 +227,4 @@ self.assertEquals(estimable, False) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/models/tests/test_glm.py =================================================================== --- trunk/scipy/stats/models/tests/test_glm.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/models/tests/test_glm.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -31,4 +31,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/models/tests/test_regression.py =================================================================== --- trunk/scipy/stats/models/tests/test_regression.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/models/tests/test_regression.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -42,4 +42,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/models/tests/test_rlm.py =================================================================== --- trunk/scipy/stats/models/tests/test_rlm.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/models/tests/test_rlm.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -27,4 +27,4 @@ self.assertEquals(results.df_resid, 31) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/models/tests/test_scale.py =================================================================== --- trunk/scipy/stats/models/tests/test_scale.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/models/tests/test_scale.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -50,4 +50,4 @@ self.assertEquals(m.shape, (40,10)) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/models/tests/test_utils.py =================================================================== --- trunk/scipy/stats/models/tests/test_utils.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/models/tests/test_utils.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -55,4 +55,4 @@ self.assertRaises(ValueError, utils.StepFunction, x, y) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/tests/test_distributions.py =================================================================== --- trunk/scipy/stats/tests/test_distributions.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/tests/test_distributions.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -213,4 +213,4 @@ assert_equal(stats.expon.pdf(0),1) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/tests/test_morestats.py =================================================================== --- trunk/scipy/stats/tests/test_morestats.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/tests/test_morestats.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -111,4 +111,4 @@ assert_array_equal(nums,[3,3,2,2]) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/stats/tests/test_stats.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -845,4 +845,4 @@ [0,2,3,4,0,0,0]) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_ast_tools.py =================================================================== --- trunk/scipy/weave/tests/test_ast_tools.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_ast_tools.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -26,4 +26,4 @@ self.generic_check(expr,desired) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_blitz_tools.py =================================================================== --- trunk/scipy/weave/tests/test_blitz_tools.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_blitz_tools.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -181,4 +181,4 @@ self.generic_2d(expr,complex128) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_build_tools.py =================================================================== --- trunk/scipy/weave/tests/test_build_tools.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_build_tools.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -62,4 +62,4 @@ assert(pre_argv == sys.argv[:]) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_c_spec.py =================================================================== --- trunk/scipy/weave/tests/test_c_spec.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_c_spec.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -757,4 +757,4 @@ # if _n[:7]=='TestGcc': exec 'del '+_n # if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_catalog.py =================================================================== --- trunk/scipy/weave/tests/test_catalog.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_catalog.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -331,4 +331,4 @@ if __name__ == '__main__': - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_ext_tools.py =================================================================== --- trunk/scipy/weave/tests/test_ext_tools.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_ext_tools.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -141,4 +141,4 @@ print_assert_equal(expr,actual,desired) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_inline_tools.py =================================================================== --- trunk/scipy/weave/tests/test_inline_tools.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_inline_tools.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -44,4 +44,4 @@ pass if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_numpy_scalar_spec.py =================================================================== --- trunk/scipy/weave/tests/test_numpy_scalar_spec.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_numpy_scalar_spec.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -168,4 +168,4 @@ if _n[:7]=='TestGcc': exec 'del '+_n if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_scxx.py =================================================================== --- trunk/scipy/weave/tests/test_scxx.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_scxx.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -12,4 +12,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_scxx_dict.py =================================================================== --- trunk/scipy/weave/tests/test_scxx_dict.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_scxx_dict.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -298,4 +298,4 @@ assert a == b if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_scxx_object.py =================================================================== --- trunk/scipy/weave/tests/test_scxx_object.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_scxx_object.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -900,4 +900,4 @@ assert_equal(a['first'],a['second']) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_scxx_sequence.py =================================================================== --- trunk/scipy/weave/tests/test_scxx_sequence.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_scxx_sequence.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -452,4 +452,4 @@ assert b == desired if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_size_check.py =================================================================== --- trunk/scipy/weave/tests/test_size_check.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_size_check.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -370,4 +370,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_slice_handler.py =================================================================== --- trunk/scipy/weave/tests/test_slice_handler.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_slice_handler.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -162,4 +162,4 @@ if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_standard_array_spec.py =================================================================== --- trunk/scipy/weave/tests/test_standard_array_spec.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_standard_array_spec.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -38,4 +38,4 @@ assert(s.type_match(arange(4))) if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) Modified: trunk/scipy/weave/tests/test_wx_spec.py =================================================================== --- trunk/scipy/weave/tests/test_wx_spec.py 2008-01-15 11:51:10 UTC (rev 3835) +++ trunk/scipy/weave/tests/test_wx_spec.py 2008-01-15 13:09:03 UTC (rev 3836) @@ -108,4 +108,4 @@ assert(c == 'hello') if __name__ == "__main__": - unittest.main() + nose.run(argv=['', __file__]) From scipy-svn at scipy.org Tue Jan 15 08:54:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 15 Jan 2008 07:54:57 -0600 (CST) Subject: [Scipy-svn] r3837 - in trunk/scipy/sandbox/multigrid: . examples Message-ID: <20080115135457.8517639C19E@new.scipy.org> Author: wnbell Date: 2008-01-15 07:54:53 -0600 (Tue, 15 Jan 2008) New Revision: 3837 Added: trunk/scipy/sandbox/multigrid/examples/ trunk/scipy/sandbox/multigrid/examples/adaptive.py trunk/scipy/sandbox/multigrid/examples/dec_example.py trunk/scipy/sandbox/multigrid/examples/simple_example.py Modified: trunk/scipy/sandbox/multigrid/adaptive.py Log: updating adaptive SA code to use BSR Modified: trunk/scipy/sandbox/multigrid/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-15 13:09:03 UTC (rev 3836) +++ trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-15 13:54:53 UTC (rev 3837) @@ -1,4 +1,5 @@ import numpy,scipy,scipy.sparse + from numpy import sqrt, ravel, diff, zeros, zeros_like, inner, concatenate, \ asarray, hstack, ascontiguousarray, isinf, dot from numpy.random import randn @@ -11,89 +12,8 @@ -def augment_candidates(AggOp, old_Q, old_R, new_candidate): - #TODO update P and A also - K = old_R.shape[1] - #determine blocksizes - if new_candidate.shape[0] == old_Q.shape[0]: - #then this is the first prolongator - old_bs = (1,K) - new_bs = (1,K+1) - else: - old_bs = (K,K) - new_bs = (K+1,K+1) - - AggOp = expand_into_blocks(AggOp,new_bs[0],1).tocsr() #TODO switch to block matrix - - - # tentative prolongator - #TODO USE BSR - Q_indptr = (K+1)*AggOp.indptr - Q_indices = ((K+1)*AggOp.indices).repeat(K+1) - for i in range(K+1): - Q_indices[i::K+1] += i - Q_data = zeros((AggOp.indptr[-1]/new_bs[0],) + new_bs) - Q_data[:,:old_bs[0],:old_bs[1]] = old_Q.data.reshape((-1,) + old_bs) #TODO BSR change - - # coarse candidates - R = zeros((AggOp.shape[1],K+1,K+1)) - R[:,:K,:K] = old_R.reshape(-1,K,K) - - c = new_candidate.reshape(-1)[diff(AggOp.indptr) == 1] #eliminate DOFs that aggregation misses - threshold = 1e-10 * abs(c).max() # cutoff for small basis functions - - X = csr_matrix((c,AggOp.indices,AggOp.indptr),shape=AggOp.shape) - - #orthogonalize X against previous - for i in range(K): - old_c = ascontiguousarray(Q_data[:,:,i].reshape(-1)) - D_AtX = csr_matrix((old_c*X.data,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of A.T * X - R[:,i,K] = D_AtX - X.data -= D_AtX[X.indices] * old_c - - #normalize X - D_XtX = csr_matrix((X.data**2,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of X.T * X - col_norms = sqrt(D_XtX) - mask = col_norms < threshold # find small basis functions - col_norms[mask] = 0 # and set them to zero - - R[:,K,K] = col_norms # store diagonal entry into R - - col_norms = 1.0/col_norms - col_norms[mask] = 0 - X.data *= col_norms[X.indices] - Q_data[:,:,-1] = X.data.reshape(-1,new_bs[0]) - - Q_data = Q_data.reshape(-1) #TODO BSR change - R = R.reshape(-1,K+1) - - Q = csr_matrix((Q_data,Q_indices,Q_indptr),shape=(AggOp.shape[0],(K+1)*AggOp.shape[1])) - - return Q,R - - - - - - -def smoothed_prolongator(P,A): - #just use Richardson for now - #omega = 4.0/(3.0*approximate_spectral_radius(A)) - #return P - omega*(A*P) - #return P #TEST - - D = diag_sparse(A) - D_inv_A = diag_sparse(1.0/D)*A - omega = 4.0/(3.0*approximate_spectral_radius(D_inv_A)) - print "spectral radius",approximate_spectral_radius(D_inv_A) #TODO remove this - D_inv_A *= omega - - return P - D_inv_A*P - - - def sa_hierarchy(A,B,AggOps): """ Construct multilevel hierarchy using Smoothed Aggregation @@ -114,7 +34,7 @@ for AggOp in AggOps: P,B = sa_fit_candidates(AggOp,B) - I = smoothed_prolongator(P,A) + I = sa_smoothed_prolongator(P,A) A = I.T.tocsr() * A * I As.append(A) Ts.append(P) @@ -148,13 +68,13 @@ x = self.__develop_new_candidate(As,Ps,Ts,Bs,AggOps,mu=mu) #TODO which is faster? - As,Ps,Ts,Bs = self.__augment_cycle(As,Ps,Ts,Bs,AggOps,x) + #As,Ps,Ts,Bs = self.__augment_cycle(As,Ps,Ts,Bs,AggOps,x) - #B = hstack((Bs[0],x)) - #As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) + B = hstack((Bs[0],x)) + As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) #improve candidates? - if True: + if False: print "improving candidates" B = Bs[0] for i in range(max_candidates): @@ -199,7 +119,7 @@ else: W_l = aggregation[len(AggOps)] P_l,x = sa_fit_candidates(W_l,x) #step 4c - I_l = smoothed_prolongator(P_l,A_l) #step 4d + I_l = sa_smoothed_prolongator(P_l,A_l) #step 4d A_l = I_l.T.tocsr() * A_l * I_l #step 4e blocks = None #not needed on subsequent levels @@ -244,24 +164,25 @@ temp_Ps = [] temp_As = [A] - def make_bridge(P,K): - indptr = P.indptr[:-1].reshape(-1,K-1) - indptr = hstack((indptr,indptr[:,-1].reshape(-1,1))) - indptr = indptr.reshape(-1) - indptr = hstack((indptr,indptr[-1:])) #duplicate last element - return csr_matrix((P.data,P.indices,indptr),shape=(K*P.shape[0]/(K-1),P.shape[1])) + def make_bridge(P): + M,N = P.shape + K = P.blocksize[0] + bnnz = P.indptr[-1] + data = zeros( (bnnz, K+1, K), dtype=P.dtype ) + data[:,:-1,:-1] = P.data + return bsr_matrix( (data, P.indices, P.indptr), shape=( (K+1)*(M/K), N) ) for i in range(len(As) - 2): - T,R = augment_candidates(AggOps[i], Ts[i], Bs[i+1], x) + B = zeros( (x.shape[0], Bs[i+1].shape[1] + 1), dtype=x.dtype) + T,R = sa_fit_candidates(AggOp,B) - P = smoothed_prolongator(T,A) + P = sa_smoothed_prolongator(T,A) A = P.T.tocsr() * A * P temp_Ps.append(P) temp_As.append(A) - #TODO USE BSR (K,K) -> (K,K-1) - bridge = make_bridge(Ps[i+1],R.shape[1]) + bridge = make_bridge(Ps[i+1]) solver = multilevel_solver( [A] + As[i+2:], [bridge] + Ps[i+2:] ) @@ -274,111 +195,87 @@ return x - def __augment_cycle(self,As,Ps,Ts,Bs,AggOps,x): - A = As[0] +# def __augment_cycle(self,As,Ps,Ts,Bs,AggOps,x): +# A = As[0] +# +# new_As = [A] +# new_Ps = [] +# new_Ts = [] +# new_Bs = [ hstack((Bs[0],x)) ] +# +# for i in range(len(As) - 1): +# T,R = augment_candidates(AggOps[i], Ts[i], Bs[i+1], x) +# +# P = sa_smoothed_prolongator(T,A) +# A = P.T.tocsr() * A * P +# +# new_As.append(A) +# new_Ps.append(P) +# new_Ts.append(T) +# new_Bs.append(R) +# +# x = R[:,-1].reshape(-1,1) +# +# return new_As,new_Ps,new_Ts,new_Bs - new_As = [A] - new_Ps = [] - new_Ts = [] - new_Bs = [ hstack((Bs[0],x)) ] - for i in range(len(As) - 1): - T,R = augment_candidates(AggOps[i], Ts[i], Bs[i+1], x) - P = smoothed_prolongator(T,A) - A = P.T.tocsr() * A * P - new_As.append(A) - new_Ps.append(P) - new_Ts.append(T) - new_Bs.append(R) - x = R[:,-1].reshape(-1,1) +#def augment_candidates(AggOp, old_Q, old_R, new_candidate): +# #TODO update P and A also +# +# K = old_R.shape[1] +# +# #determine blocksizes +# if new_candidate.shape[0] == old_Q.shape[0]: +# #then this is the first prolongator +# old_bs = (1,K) +# new_bs = (1,K+1) +# else: +# old_bs = (K,K) +# new_bs = (K+1,K+1) +# +# #AggOp = expand_into_blocks(AggOp,new_bs[0],1).tocsr() #TODO switch to block matrix +# +# # tentative prolongator +# Q_data = zeros( (AggOp.indptr[-1],) + new_bs) +# Q_data[:,:old_bs[0],:old_bs[1]] = old_Q.data.reshape((-1,) + old_bs) +# +# # coarse candidates +# R = zeros((AggOp.shape[1],K+1,K+1)) +# R[:,:K,:K] = old_R.reshape(-1,K,K) +# +# c = new_candidate.reshape(-1)[diff(AggOp.indptr) == 1] #eliminate DOFs that aggregation misses +# threshold = 1e-10 * abs(c).max() # cutoff for small basis functions +# +# X = bsr_matrix((c,AggOp.indices,AggOp.indptr),shape=AggOp.shape) +# +# #orthogonalize X against previous +# for i in range(K): +# old_c = ascontiguousarray(Q_data[:,:,i].reshape(-1)) +# D_AtX = csr_matrix((old_c*X.data,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of A.T * X +# R[:,i,K] = D_AtX +# X.data -= D_AtX[X.indices] * old_c +# +# #normalize X +# D_XtX = csr_matrix((X.data**2,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of X.T * X +# col_norms = sqrt(D_XtX) +# mask = col_norms < threshold # find small basis functions +# col_norms[mask] = 0 # and set them to zero +# +# R[:,K,K] = col_norms # store diagonal entry into R +# +# col_norms = 1.0/col_norms +# col_norms[mask] = 0 +# X.data *= col_norms[X.indices] +# Q_data[:,:,-1] = X.data.reshape(-1,new_bs[0]) +# +# Q_data = Q_data.reshape(-1) #TODO BSR change +# R = R.reshape(-1,K+1) +# +# Q = csr_matrix((Q_data,Q_indices,Q_indptr),shape=(AggOp.shape[0],(K+1)*AggOp.shape[1])) +# +# return Q,R - return new_As,new_Ps,new_Ts,new_Bs - -if __name__ == '__main__': - from scipy import * - from utils import diag_sparse - from multilevel import poisson_problem1D,poisson_problem2D - - blocks = None - aggregation = None - - #A = poisson_problem2D(200,1e-2) - #aggregation = [ sa_constant_interpolation(A*A*A,epsilon=0.0) ] - - #A = io.mmread("tests/sample_data/laplacian_41_3dcube.mtx").tocsr() - #A = io.mmread("laplacian_40_3dcube.mtx").tocsr() - #A = io.mmread("/home/nathan/Desktop/9pt/9pt-100x100.mtx").tocsr() - #A = io.mmread("/home/nathan/Desktop/BasisShift_W_EnergyMin_Luke/9pt-5x5.mtx").tocsr() - - - #D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() - #A = D * A * D - - A = io.mmread("tests/sample_data/elas30_A.mtx").tocsr() - blocks = arange(A.shape[0]/2).repeat(2) - - from time import clock; start = clock() - asa = adaptive_sa_solver(A,max_candidates=3,mu=5,blocks=blocks,aggregation=aggregation) - print "Adaptive Solver Construction: %s seconds" % (clock() - start); del start - - scipy.random.seed(0) #make tests repeatable - x = randn(A.shape[0]) - b = A*randn(A.shape[0]) - #b = zeros(A.shape[0]) - - - print "solving" - if False: - x_sol,residuals = asa.solver.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) - else: - residuals = [] - def add_resid(x): - residuals.append(linalg.norm(b - A*x)) - A.psolve = asa.solver.psolve - x_sol = linalg.cg(A,b,x0=x,maxiter=30,tol=1e-12,callback=add_resid)[0] - - residuals = array(residuals)/residuals[0] - - print "residuals ",residuals - print "mean convergence factor",(residuals[-1]/residuals[0])**(1.0/len(residuals)) - print "last convergence factor",residuals[-1]/residuals[-2] - - print - print asa.solver - - print "constant Rayleigh quotient",dot(ones(A.shape[0]),A*ones(A.shape[0]))/float(A.shape[0]) - - def plot2d_arrows(x): - from pylab import figure,quiver,show - x = x.reshape(-1) - N = (len(x)/2)**0.5 - assert(2 * N * N == len(x)) - X = linspace(-1,1,N).reshape(1,N).repeat(N,0).reshape(-1) - Y = linspace(-1,1,N).reshape(1,N).repeat(N,0).T.reshape(-1) - - dX = x[0::2] - dY = x[1::2] - - figure() - quiver(X,Y,dX,dY) - show() - - def plot2d(x): - from pylab import pcolor,figure,show - figure() - pcolor(x.reshape(sqrt(len(x)),sqrt(len(x)))) - show() - - - for c in asa.Bs[0].T: - #plot2d(c) - plot2d_arrows(c) - print "candidate Rayleigh quotient",dot(c,A*c)/dot(c,c) - - - ##W = asa.AggOps[0]*asa.AggOps[1] - ##pcolor((W * rand(W.shape[1])).reshape((200,200))) Added: trunk/scipy/sandbox/multigrid/examples/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-15 13:09:03 UTC (rev 3836) +++ trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-15 13:54:53 UTC (rev 3837) @@ -0,0 +1,84 @@ + +from scipy import * +from scipy.sandbox.multigrid.utils import diag_sparse +from scipy.sandbox.multigrid.gallery import poisson, linear_elasticity + + +#A = poisson( (200,200), spacing=(1,1e-2) +#aggregation = [ sa_constant_interpolation(A*A*A,epsilon=0.0) ] + +#A = io.mmread("tests/sample_data/laplacian_41_3dcube.mtx").tocsr() +#A = io.mmread("laplacian_40_3dcube.mtx").tocsr() +#A = io.mmread("/home/nathan/Desktop/9pt/9pt-100x100.mtx").tocsr() +#A = io.mmread("/home/nathan/Desktop/BasisShift_W_EnergyMin_Luke/9pt-5x5.mtx").tocsr() + + +#D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() +#A = D * A * D + +#A = io.mmread("tests/sample_data/elas30_A.mtx").tocsr() + +A,B = linear_elasticity( (100,100) ) + +from time import clock; start = clock() +asa = adaptive_sa_solver(A,max_candidates=3,mu=5,blocks=blocks,aggregation=aggregation) +print "Adaptive Solver Construction: %s seconds" % (clock() - start); del start + +scipy.random.seed(0) #make tests repeatable +x = randn(A.shape[0]) +b = A*randn(A.shape[0]) +#b = zeros(A.shape[0]) + + +print "solving" +if False: + x_sol,residuals = asa.solver.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) +else: + residuals = [] + def add_resid(x): + residuals.append(linalg.norm(b - A*x)) + A.psolve = asa.solver.psolve + x_sol = linalg.cg(A,b,x0=x,maxiter=30,tol=1e-12,callback=add_resid)[0] + +residuals = array(residuals)/residuals[0] + +print "residuals ",residuals +print "mean convergence factor",(residuals[-1]/residuals[0])**(1.0/len(residuals)) +print "last convergence factor",residuals[-1]/residuals[-2] + +print +print asa.solver + +print "constant Rayleigh quotient",dot(ones(A.shape[0]),A*ones(A.shape[0]))/float(A.shape[0]) + +def plot2d_arrows(x): + from pylab import figure,quiver,show + x = x.reshape(-1) + N = (len(x)/2)**0.5 + assert(2 * N * N == len(x)) + X = linspace(-1,1,N).reshape(1,N).repeat(N,0).reshape(-1) + Y = linspace(-1,1,N).reshape(1,N).repeat(N,0).T.reshape(-1) + + dX = x[0::2] + dY = x[1::2] + + figure() + quiver(X,Y,dX,dY) + show() + +def plot2d(x): + from pylab import pcolor,figure,show + figure() + pcolor(x.reshape(sqrt(len(x)),sqrt(len(x)))) + show() + + +for c in asa.Bs[0].T: + #plot2d(c) + plot2d_arrows(c) + print "candidate Rayleigh quotient",dot(c,A*c)/dot(c,c) + + +##W = asa.AggOps[0]*asa.AggOps[1] +##pcolor((W * rand(W.shape[1])).reshape((200,200))) + Added: trunk/scipy/sandbox/multigrid/examples/dec_example.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/dec_example.py 2008-01-15 13:09:03 UTC (rev 3836) +++ trunk/scipy/sandbox/multigrid/examples/dec_example.py 2008-01-15 13:54:53 UTC (rev 3837) @@ -0,0 +1,241 @@ + +from scipy import * +from scipy.sparse import * +from pydec import * +from pydec.multigrid.discrete_laplacian import boundary_hierarchy, discrete_laplacian_solver, hodge_solver + +from scipy.sandbox.multigrid import smoothed_aggregation_solver,multigridtools,multilevel_solver +from scipy.sandbox.multigrid.adaptive import adaptive_sa_solver +from scipy.sandbox.multigrid.sa import sa_smoothed_prolongator +from scipy.sandbox.multigrid.utils import expand_into_blocks + + +## Load mesh from file +mesh_path = '../../../../../hirani_group/wnbell/meshes/' +#mesh = read_mesh(mesh_path + 'rocket/rocket.xml') +#mesh = read_mesh(mesh_path + 'genus3/genus3_168k.xml') +#mesh = read_mesh(mesh_path + 'genus3/genus3_455k.xml') +#mesh = read_mesh(mesh_path + '/torus/torus.xml') +mesh = read_mesh(mesh_path + '/sq14tri/sq14tri.xml') +for i in range(5): + mesh['vertices'],mesh['elements'] = loop_subdivision(mesh['vertices'],mesh['elements']) +cmplx = simplicial_complex(mesh['vertices'],mesh['elements']) + +## Construct mesh manually +#bitmap = ones((60,60),dtype='bool') +#bitmap[1::10,1::10] = False +#bitmap[100:150,100:400] = False +#cmplx = regular_cube_complex(regular_cube_mesh(bitmap)) + +def curl_curl_prolongator(D_nodal,vertices): + if not isspmatrix_csr(D_nodal): + raise TypeError('expected csr_matrix') + + A = D_nodal.T.tocsr() * D_nodal + aggs = multigridtools.sa_get_aggregates(A.shape[0],A.indptr,A.indices) + + num_edges = D_nodal.shape[0] + num_basis = vertices.shape[1] + num_aggs = aggs.max() + 1 + + # replace with CSR + eliminate duplicates + #indptr = (2*num_basis) * arange(num_edges+1) + ## same same + #csr_matrix((data,indices,indptr),shape=(num_edges,num_aggs)) + + row = arange(num_edges).repeat(2*num_basis) + col = (num_basis*aggs[D_nodal.indices]).repeat(num_basis) + col = col.reshape(-1,num_basis) + arange(num_basis) + col = col.reshape(-1) + data = tile(0.5 * (D_nodal*vertices),(1,2)).reshape(-1) + + return coo_matrix((data,(row,col)),shape=(num_edges,num_basis*num_aggs)).tocsr() + + + + + +def whitney_innerproduct_cache(cmplx,k): + h = hash(cmplx.vertices.tostring()) ^ hash(cmplx.simplices.tostring()) ^ hash(k) + + filename = "/home/nathan/.pydec/cache/whitney_" + str(h) + ".mtx" + + try: + import pydec + M = pydec.io.read_array(filename) + except: + import pydec + M = whitney_innerproduct(cmplx,k) + pydec.io.write_array(filename,M) + + return M + + + +def cube_innerproduct_cache(cmplx,k): + h = hash(cmplx.mesh.bitmap.tostring()) ^ hash(cmplx.mesh.bitmap.shape) ^ hash(k) + + filename = "/home/nathan/.pydec/cache/cube_" + str(h) + ".mtx" + + try: + import pydec + M = pydec.io.read_array(filename) + except: + import pydec + M = regular_cube_innerproduct(cmplx,k) + pydec.io.write_array(filename,M) + + return M + + + +#solve d_k d_k problem for all reasonable k +#from pylab import semilogy,show,xlabel,ylabel,legend,ylim,xlim +#from matplotlib.font_manager import fontManager, FontProperties + +cochain_complex = cmplx.cochain_complex() + +for i in [1]: #range(len(cochain_complex)-1): + print "computing mass matrix" + + if isinstance(cmplx,simplicial_complex): + Mi = whitney_innerproduct_cache(cmplx,i+1) + else: + Mi = regular_cube_innerproduct(cmplx,i+1) + + + dimension = mesh['vertices'].shape[1] + + if True: + + d0 = cmplx[0].d + d1 = cmplx[1].d + + #A = (d1.T.tocsr() * d1 + d0 * d0.T.tocsr()).astype('d') + A = (d1.T.tocsr() * d1).astype('d') + + P = curl_curl_prolongator(d0,mesh['vertices']) + + num_blocks = P.shape[1]/dimension + blocks = arange(num_blocks).repeat(dimension) + + P = sa_smoothed_prolongator(A,P,epsilon=0,omega=4.0/3.0) + + PAP = P.T.tocsr() * A * P + + candidates = None + candidates = zeros((num_blocks,dimension,dimension)) + for n in range(dimension): + candidates[:,n,n] = 1.0 + candidates = candidates.reshape(-1,dimension) + + ml = smoothed_aggregation_solver(PAP,epsilon=0.0,candidates=candidates,blocks=blocks) + #A = PAP + ml = multilevel_solver([A] + ml.As, [P] + ml.Ps) + else: + + bh = boundary_hierarchy(cochain_complex) + while len(bh) < 3: + bh.coarsen() + print repr(bh) + + N = len(cochain_complex) - 1 + + B = bh[0][N - i].B + + A = (B.T.tocsr() * B).astype('d') + #A = B.T.tocsr() * Mi * B + + constant_prolongators = [lvl[N - i].I for lvl in bh[:-1]] + + method = 'aSA' + + if method == 'RS': + As = [A] + Ps = [] + for T in constant_prolongators: + Ps.append( sa_smoothed_prolongator(As[-1],T,epsilon=0.0,omega=4.0/3.0) ) + As.append(Ps[-1].T.tocsr() * As[-1] * Ps[-1]) + ml = multilevel_solver(As,Ps) + + else: + if method == 'BSA': + if i == 0: + candidates = None + else: + candidates = cmplx[0].d * mesh['vertices'] + K = candidates.shape[1] + + constant_prolongators = [constant_prolongators[0]] + \ + [expand_into_blocks(T,K,1).tocsr() for T in constant_prolongators[1:] ] + + ml = smoothed_aggregation_solver(A,candidates,aggregation=constant_prolongators) + elif method == 'aSA': + asa = adaptive_sa_solver(A,aggregation=constant_prolongators,max_candidates=dimension,epsilon=0.0) + ml = asa.solver + else: + raise ValuerError,'unknown method' + + #ml = smoothed_aggregation_solver(A,candidates) + + #x = d0 * mesh['vertices'][:,0] + x = rand(A.shape[0]) + b = zeros_like(x) + #b = A*rand(A.shape[0]) + + if True: + x_sol,residuals = ml.solve(b,x0=x,maxiter=50,tol=1e-12,return_residuals=True) + else: + residuals = [] + def add_resid(x): + residuals.append(linalg.norm(b - A*x)) + A.psolve = ml.psolve + + from pydec import cg + x_sol = cg(A,b,x0=x,maxiter=40,tol=1e-8,callback=add_resid)[0] + + + residuals = array(residuals)/residuals[0] + avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) + print "average convergence ratio",avg_convergence_ratio + print "last convergence ratio",residuals[-1]/residuals[-2] + + print residuals + + + + +##candidates = None +##blocks = None +## +## +## +##A = io.mmread('tests/sample_data/elas30_A.mtx').tocsr() +##candidates = io.mmread('tests/sample_data/elas30_nullspace.mtx') +##candidates = [ array(candidates[:,x]) for x in range(candidates.shape[1]) ] +##blocks = arange(A.shape[0]/2).repeat(2) +## +##ml = smoothed_aggregation_solver(A,candidates,blocks=blocks,epsilon=0,max_coarse=10,max_levels=10) +###ml = ruge_stuben_solver(A) +## +##x = rand(A.shape[0]) +###b = zeros_like(x) +##b = A*rand(A.shape[0]) +## +##if True: +## x_sol,residuals = ml.solve(b,x0=x,maxiter=30,tol=1e-12,return_residuals=True) +##else: +## residuals = [] +## def add_resid(x): +## residuals.append(linalg.norm(b - A*x)) +## A.psolve = ml.psolve +## x_sol = linalg.cg(A,b,x0=x,maxiter=25,tol=1e-12,callback=add_resid)[0] +## +## +##residuals = array(residuals)/residuals[0] +##avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) +##print "average convergence ratio",avg_convergence_ratio +##print "last convergence ratio",residuals[-1]/residuals[-2] +## +##print residuals +## Added: trunk/scipy/sandbox/multigrid/examples/simple_example.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/simple_example.py 2008-01-15 13:09:03 UTC (rev 3836) +++ trunk/scipy/sandbox/multigrid/examples/simple_example.py 2008-01-15 13:54:53 UTC (rev 3837) @@ -0,0 +1,28 @@ +from scipy import * +from scipy.sandbox.multigrid.sa import * +from scipy.sandbox.multigrid import * +from scipy.sandbox.multigrid.utils import * +from time import clock + +mats = io.loadmat('/home/nathan/Work/ogroup/matrices/elasticity/simple_grid_2d/elasticity_500x500.mat') +A = mats['A'].tobsr(blocksize=(2,2)) +B = mats['B'] + +#A = poisson_problem2D(50) +#B = None + +start = clock() +sa = smoothed_aggregation_solver(A,B=B) +print "constructed solver in %s seconds" % (clock() - start) + +x0 = rand(A.shape[0]) +b = zeros_like(x0) +start = clock() +x,residuals = sa.solve(b,x0=x0,return_residuals=True) +print "solved in %s seconds" % (clock() - start) + +residuals = array(residuals)/residuals[0] +avg_convergence_ratio = residuals[-1]**(1.0/len(residuals)) +print "average convergence ratio",avg_convergence_ratio +print "last convergence ratio",residuals[-1]/residuals[-2] +print 'residuals',residuals From scipy-svn at scipy.org Tue Jan 15 11:15:17 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 15 Jan 2008 10:15:17 -0600 (CST) Subject: [Scipy-svn] r3838 - in trunk/scipy/sandbox/multigrid: . examples tests Message-ID: <20080115161517.5A7A739C01A@new.scipy.org> Author: wnbell Date: 2008-01-15 10:15:12 -0600 (Tue, 15 Jan 2008) New Revision: 3838 Modified: trunk/scipy/sandbox/multigrid/adaptive.py trunk/scipy/sandbox/multigrid/examples/adaptive.py trunk/scipy/sandbox/multigrid/sa.py trunk/scipy/sandbox/multigrid/tests/test_adaptive.py Log: updated adaptive SA to use BSR Modified: trunk/scipy/sandbox/multigrid/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-15 13:54:53 UTC (rev 3837) +++ trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-15 16:15:12 UTC (rev 3838) @@ -1,3 +1,6 @@ +__all__ = ['adaptive_sa_solver'] + + import numpy,scipy,scipy.sparse from numpy import sqrt, ravel, diff, zeros, zeros_like, inner, concatenate, \ @@ -2,9 +5,10 @@ asarray, hstack, ascontiguousarray, isinf, dot -from numpy.random import randn +from numpy.random import randn, rand from scipy.sparse import csr_matrix,coo_matrix from relaxation import gauss_seidel from multilevel import multilevel_solver -from sa import sa_constant_interpolation,sa_fit_candidates from utils import approximate_spectral_radius,hstack_csr,vstack_csr,diag_sparse +from sa import sa_constant_interpolation, sa_smoothed_prolongator, \ + sa_fit_candidates @@ -19,13 +23,14 @@ Construct multilevel hierarchy using Smoothed Aggregation Inputs: A - matrix - Ps - list of constant prolongators - B - "candidate" basis function to be approximated + B - fine-level near nullspace candidates be approximated + Ouputs: - (As,Ps,Ts) - tuple of lists - - As - [A, Ts[0].T*A*Ts[0], Ts[1].T*A*Ts[1], ... ] + (As,Ps,Ts,Bs) - tuple of lists + - As - - Ps - smoothed prolongators - Ts - tentative prolongators + - Bs - near nullspace candidates """ As = [A] Ps = [] @@ -34,7 +39,7 @@ for AggOp in AggOps: P,B = sa_fit_candidates(AggOp,B) - I = sa_smoothed_prolongator(P,A) + I = sa_smoothed_prolongator(A,P) A = I.T.tocsr() * A * I As.append(A) Ts.append(P) @@ -44,19 +49,17 @@ class adaptive_sa_solver: - def __init__(self, A, blocks=None, aggregation=None, max_levels=10, max_coarse=100,\ + def __init__(self, A, aggregation=None, max_levels=10, max_coarse=100,\ max_candidates=1, mu=5, epsilon=0.1): - - self.A = A - + + self.A = A self.Rs = [] if self.A.shape[0] <= max_coarse: raise ValueError,'small matrices not handled yet' #first candidate - x,AggOps = self.__initialization_stage(A, blocks = blocks, \ - max_levels = max_levels, \ + x,AggOps = self.__initialization_stage(A, max_levels = max_levels, \ max_coarse = max_coarse, \ mu = mu, epsilon = epsilon, \ aggregation = aggregation ) @@ -67,9 +70,6 @@ for i in range(max_candidates - 1): x = self.__develop_new_candidate(As,Ps,Ts,Bs,AggOps,mu=mu) - #TODO which is faster? - #As,Ps,Ts,Bs = self.__augment_cycle(As,Ps,Ts,Bs,AggOps,x) - B = hstack((Bs[0],x)) As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) @@ -89,7 +89,7 @@ self.AggOps = AggOps self.Bs = Bs - def __initialization_stage(self,A,blocks,max_levels,max_coarse,mu,epsilon,aggregation): + def __initialization_stage(self,A,max_levels,max_coarse,mu,epsilon,aggregation): if aggregation is not None: max_coarse = 0 max_levels = len(aggregation) + 1 @@ -100,31 +100,28 @@ #step 1 A_l = A - x = randn(A_l.shape[0],1) + x = rand(A_l.shape[0],1) # TODO see why randn() fails here skip_f_to_i = False #step 2 - gauss_seidel(A_l,x,zeros_like(x),iterations=mu,sweep='symmetric') + gauss_seidel(A_l, x, zeros_like(x), iterations=mu, sweep='symmetric') #step 3 #TODO test convergence rate here - As = [A] + As = [A] + Ps = [] AggOps = [] - Ps = [] while len(AggOps) + 1 < max_levels and A_l.shape[0] > max_coarse: if aggregation is None: - W_l = sa_constant_interpolation(A_l,epsilon=0,blocks=blocks) #step 4b + W_l = sa_constant_interpolation(A_l,epsilon=0) #step 4b else: - W_l = aggregation[len(AggOps)] - P_l,x = sa_fit_candidates(W_l,x) #step 4c - I_l = sa_smoothed_prolongator(P_l,A_l) #step 4d - A_l = I_l.T.tocsr() * A_l * I_l #step 4e + W_l = aggregation[len(AggOps)] + P_l,x = sa_fit_candidates(W_l,x) #step 4c + I_l = sa_smoothed_prolongator(A_l,P_l) #step 4d + A_l = I_l.T.tocsr() * A_l * I_l #step 4e - blocks = None #not needed on subsequent levels - - print 'A_l.shape',A_l.shape AggOps.append(W_l) Ps.append(I_l) As.append(A_l) @@ -132,7 +129,6 @@ if A_l.shape <= max_coarse: break if not skip_f_to_i: - print "." x_hat = x.copy() #step 4g gauss_seidel(A_l,x,zeros_like(x),iterations=mu,sweep='symmetric') #step 4h x_A_x = dot(x.T,A_l*x) @@ -176,7 +172,7 @@ B = zeros( (x.shape[0], Bs[i+1].shape[1] + 1), dtype=x.dtype) T,R = sa_fit_candidates(AggOp,B) - P = sa_smoothed_prolongator(T,A) + P = sa_smoothed_prolongator(A,T) A = P.T.tocsr() * A * P temp_Ps.append(P) @@ -206,7 +202,7 @@ # for i in range(len(As) - 1): # T,R = augment_candidates(AggOps[i], Ts[i], Bs[i+1], x) # -# P = sa_smoothed_prolongator(T,A) +# P = sa_smoothed_prolongator(A,T) # A = P.T.tocsr() * A * P # # new_As.append(A) @@ -219,9 +215,6 @@ # return new_As,new_Ps,new_Ts,new_Bs - - - #def augment_candidates(AggOp, old_Q, old_R, new_candidate): # #TODO update P and A also # Modified: trunk/scipy/sandbox/multigrid/examples/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-15 13:54:53 UTC (rev 3837) +++ trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-15 16:15:12 UTC (rev 3838) @@ -2,36 +2,32 @@ from scipy import * from scipy.sandbox.multigrid.utils import diag_sparse from scipy.sandbox.multigrid.gallery import poisson, linear_elasticity +from scipy.sandbox.multigrid.adaptive import adaptive_sa_solver +#A,B = linear_elasticity( (100,100) ) -#A = poisson( (200,200), spacing=(1,1e-2) -#aggregation = [ sa_constant_interpolation(A*A*A,epsilon=0.0) ] +A = poisson( (200,200), format='csr' ) -#A = io.mmread("tests/sample_data/laplacian_41_3dcube.mtx").tocsr() -#A = io.mmread("laplacian_40_3dcube.mtx").tocsr() -#A = io.mmread("/home/nathan/Desktop/9pt/9pt-100x100.mtx").tocsr() -#A = io.mmread("/home/nathan/Desktop/BasisShift_W_EnergyMin_Luke/9pt-5x5.mtx").tocsr() - - +#A = poisson( (200,200), spacing=(1,1e-2) ) #anisotropic #D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() #A = D * A * D -#A = io.mmread("tests/sample_data/elas30_A.mtx").tocsr() -A,B = linear_elasticity( (100,100) ) from time import clock; start = clock() -asa = adaptive_sa_solver(A,max_candidates=3,mu=5,blocks=blocks,aggregation=aggregation) + +asa = adaptive_sa_solver(A, max_levels=2, max_candidates=1, mu=10) + print "Adaptive Solver Construction: %s seconds" % (clock() - start); del start -scipy.random.seed(0) #make tests repeatable +random.seed(0) #make tests repeatable x = randn(A.shape[0]) -b = A*randn(A.shape[0]) -#b = zeros(A.shape[0]) +#b = A*randn(A.shape[0]) +b = zeros(A.shape[0]) print "solving" -if False: +if True: x_sol,residuals = asa.solver.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) else: residuals = [] @@ -74,10 +70,11 @@ for c in asa.Bs[0].T: - #plot2d(c) - plot2d_arrows(c) + plot2d(c) + #plot2d_arrows(c) print "candidate Rayleigh quotient",dot(c,A*c)/dot(c,c) +#plot2d(x_sol) ##W = asa.AggOps[0]*asa.AggOps[1] ##pcolor((W * rand(W.shape[1])).reshape((200,200))) Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-15 13:54:53 UTC (rev 3837) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-15 16:15:12 UTC (rev 3838) @@ -97,6 +97,9 @@ sa_constant_interpolation(csr_matrix(A),epsilon) def sa_fit_candidates(AggOp,candidates,tol=1e-10): + if not isspmatrix_csr(AggOp): + raise TypeError,'expected csr_matrix for argument AggOp' + if candidates.dtype != 'float32': candidates = asarray(candidates,dtype='float64') @@ -147,7 +150,7 @@ return Q,R -def sa_smoothed_prolongator(A,T,epsilon,omega): +def sa_smoothed_prolongator(A,T,epsilon=0.0,omega=4.0/3.0): """For a given matrix A and tentative prolongator T return the smoothed prolongator P @@ -161,7 +164,6 @@ A_filtered - sa_filtered_matrix(A,epsilon) """ - A_filtered = sa_filtered_matrix(A,epsilon) #use filtered matrix for anisotropic problems # TODO use scale_rows() Modified: trunk/scipy/sandbox/multigrid/tests/test_adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-15 13:54:53 UTC (rev 3837) +++ trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-15 16:15:12 UTC (rev 3838) @@ -5,7 +5,7 @@ from scipy.sandbox.multigrid.sa import sa_fit_candidates -from scipy.sandbox.multigrid.adaptive import augment_candidates +#from scipy.sandbox.multigrid.adaptive import augment_candidates From scipy-svn at scipy.org Tue Jan 15 14:32:25 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 15 Jan 2008 13:32:25 -0600 (CST) Subject: [Scipy-svn] r3839 - in trunk/scipy/sandbox/multigrid: . examples tests Message-ID: <20080115193225.4F32EC7C041@new.scipy.org> Author: wnbell Date: 2008-01-15 13:32:21 -0600 (Tue, 15 Jan 2008) New Revision: 3839 Modified: trunk/scipy/sandbox/multigrid/examples/adaptive.py trunk/scipy/sandbox/multigrid/relaxation.py trunk/scipy/sandbox/multigrid/tests/test_relaxation.py trunk/scipy/sandbox/multigrid/tests/test_sa.py trunk/scipy/sandbox/multigrid/tests/test_utils.py trunk/scipy/sandbox/multigrid/utils.py Log: updated aSA Modified: trunk/scipy/sandbox/multigrid/examples/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-15 16:15:12 UTC (rev 3838) +++ trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-15 19:32:21 UTC (rev 3839) @@ -9,8 +9,8 @@ A = poisson( (200,200), format='csr' ) #A = poisson( (200,200), spacing=(1,1e-2) ) #anisotropic -#D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() -#A = D * A * D +D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() +A = D * A * D Modified: trunk/scipy/sandbox/multigrid/relaxation.py =================================================================== --- trunk/scipy/sandbox/multigrid/relaxation.py 2008-01-15 16:15:12 UTC (rev 3838) +++ trunk/scipy/sandbox/multigrid/relaxation.py 2008-01-15 19:32:21 UTC (rev 3839) @@ -55,7 +55,7 @@ """ #TODO replace pointwise BSR with block BSR - x = x.reshape(-1) #TODO warn if not inplace + x = ravel(x) #TODO warn if not inplace b = ravel(b) if isspmatrix_csr(A): Modified: trunk/scipy/sandbox/multigrid/tests/test_relaxation.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-15 16:15:12 UTC (rev 3838) +++ trunk/scipy/sandbox/multigrid/tests/test_relaxation.py 2008-01-15 19:32:21 UTC (rev 3839) @@ -2,16 +2,20 @@ import numpy import scipy -from scipy import arange,ones,zeros,array,allclose,zeros_like -from scipy.sparse import spdiags +from scipy.sparse import spdiags, csr_matrix +from scipy import arange, ones, zeros, array, allclose, zeros_like, \ + tril, diag, triu, rand, asmatrix +from scipy.linalg import solve import scipy.sandbox.multigrid +from scipy.sandbox.multigrid.gallery import poisson from scipy.sandbox.multigrid.relaxation import polynomial_smoother,gauss_seidel,jacobi + class TestRelaxation(TestCase): def test_polynomial(self): N = 3 @@ -99,7 +103,54 @@ gauss_seidel(B,x_bsr,b) assert_almost_equal(x_bsr,x_csr) + def test_gauss_seidel_new(self): + scipy.random.seed(0) + cases = [] + cases.append( poisson( (4,), format='csr' ) ) + cases.append( poisson( (4,4), format='csr' ) ) + + temp = asmatrix( rand(4,4) ) + cases.append( csr_matrix( temp.T * temp) ) + + # reference implementation + def gold(A,x,b,iterations,sweep): + A = A.todense() + + L = tril(A,k=-1) + D = diag(diag(A)) + U = triu(A,k=1) + + for i in range(iterations): + if sweep == 'forward': + x = solve(L + D, (b - U*x) ) + elif sweep == 'backward': + x = solve(U + D, (b - L*x) ) + else: + x = solve(L + D, (b - U*x) ) + x = solve(U + D, (b - L*x) ) + return x + + + for A in cases: + + b = asmatrix(rand(A.shape[0],1)) + x = asmatrix(rand(A.shape[0],1)) + + x_copy = x.copy() + gauss_seidel(A, x, b, iterations=1, sweep='forward') + assert_almost_equal( x, gold(A,x_copy,b,iterations=1,sweep='forward') ) + + x_copy = x.copy() + gauss_seidel(A, x, b, iterations=1, sweep='backward') + assert_almost_equal( x, gold(A,x_copy,b,iterations=1,sweep='backward') ) + + x_copy = x.copy() + gauss_seidel(A, x, b, iterations=1, sweep='symmetric') + assert_almost_equal( x, gold(A,x_copy,b,iterations=1,sweep='symmetric') ) + + + def test_gauss_seidel_csr(self): N = 1 A = spdiags([2*ones(N),-ones(N),-ones(N)],[0,-1,1],N,N,format='csr') Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-15 16:15:12 UTC (rev 3838) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-15 19:32:21 UTC (rev 3839) @@ -183,7 +183,7 @@ def setUp(self): self.cases = [] - self.cases.append(( poisson( (100,), format='csr'), None)) + self.cases.append(( poisson( (10000,), format='csr'), None)) self.cases.append(( poisson( (100,100), format='csr'), None)) # TODO add unstructured tests @@ -206,39 +206,36 @@ assert(avg_convergence_ratio < 0.5) def test_DAD(self): - for A,candidates in self.cases: + A = poisson( (100,100), format='csr' ) - x = rand(A.shape[0]) - b = A*rand(A.shape[0]) + x = rand(A.shape[0]) + b = rand(A.shape[0]) + + D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() + D_inv = diag_sparse(1.0/D.data) + + DAD = D*A*D + + B = ones((A.shape[0],1)) + + Dinv_B = D_inv * B + + #TODO force 2 level method and check that result is the same + + sa1 = smoothed_aggregation_solver(A, B, max_levels=2, rescale=False) + sa2 = smoothed_aggregation_solver(D*A*D, D_inv * B, max_levels=2, rescale=False) + + #assert_almost_equal( sa2.Ps[0], sa1.Ps[0] + x_sol,residuals = sa2.solve(b,x0=x,maxiter=10,tol=1e-12,return_residuals=True) + + avg_convergence_ratio = (residuals[-1]/residuals[0])**(1.0/len(residuals)) + print avg_convergence_ratio + + assert(avg_convergence_ratio < 0.2) - D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() - D_inv = diag_sparse(1.0/D.data) - DAD = D*A*D - if candidates is None: - candidates = ones((A.shape[0],1)) - DAD_candidates = D_inv * candidates - - #TODO force 2 level method and check that result is the same - - #ml = smoothed_aggregation_solver(A,candidates,max_coarse=1,max_levels=2) - - ml = smoothed_aggregation_solver(DAD,DAD_candidates,max_coarse=100,max_levels=2,rescale=False) - - #print (D_inv*ml.Ps[0]).todense() - - x_sol,residuals = ml.solve(b,x0=x,maxiter=10,tol=1e-12,return_residuals=True) - - avg_convergence_ratio = (residuals[-1]/residuals[0])**(1.0/len(residuals)) - #print avg_convergence_ratio - - assert(avg_convergence_ratio < 0.5) - - - - ################################################ ## reference implementations for unittests ## ################################################ Modified: trunk/scipy/sandbox/multigrid/tests/test_utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-15 16:15:12 UTC (rev 3838) +++ trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-15 19:32:21 UTC (rev 3839) @@ -12,27 +12,28 @@ from scipy.sandbox.multigrid.utils import symmetric_rescaling class TestUtils(TestCase): - def test_approximate_spectral_radius(self): - cases = [] - - cases.append( matrix([[-4]]) ) - cases.append( array([[-4]]) ) - - cases.append( array([[2,0],[0,1]]) ) - cases.append( array([[-2,0],[0,1]]) ) - - cases.append( array([[100,0,0],[0,101,0],[0,0,99]]) ) - - for i in range(1,5): - cases.append( rand(i,i) ) - - # method should be almost exact for small matrices - for A in cases: - Asp = csr_matrix(A) - assert_almost_equal( approximate_spectral_radius(A), norm(A,2) ) - assert_almost_equal( approximate_spectral_radius(Asp), norm(A,2) ) - - #TODO test larger matrices +# def test_approximate_spectral_radius(self): +# cases = [] +# +# cases.append( matrix([[-4]]) ) +# cases.append( array([[-4]]) ) +# +# cases.append( array([[2,0],[0,1]]) ) +# cases.append( array([[-2,0],[0,1]]) ) +# +# cases.append( array([[100,0,0],[0,101,0],[0,0,99]]) ) +# +# for i in range(1,5): +# cases.append( rand(i,i) ) +# +# # method should be almost exact for small matrices +# for A in cases: +# A = A.astype(float) +# Asp = csr_matrix(A) +# assert_almost_equal( approximate_spectral_radius(A,tol=1e-2), norm(A,2), decimal=1 ) +# assert_almost_equal( approximate_spectral_radius(Asp,tol=1e-2), norm(A,2), decimal=1 ) +# +# #TODO test larger matrices def test_infinity_norm(self): A = matrix([[-4]]) Modified: trunk/scipy/sandbox/multigrid/utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/utils.py 2008-01-15 16:15:12 UTC (rev 3838) +++ trunk/scipy/sandbox/multigrid/utils.py 2008-01-15 19:32:21 UTC (rev 3839) @@ -12,7 +12,7 @@ from scipy.sparse.sputils import upcast -def approximate_spectral_radius(A,tol=0.1,maxiter=10,symmetric=None): +def approximate_spectral_radius(A,tol=0.1,maxiter=20,symmetric=None): """approximate the spectral radius of a matrix *Parameters*: @@ -36,8 +36,8 @@ An approximation to the spectral radius of A (scalar value) """ - #from scipy.sandbox.arpack import eigen - #return norm(eigen(A, k=1, ncv=10, which='LM', maxiter=maxiter, tol=tol, return_eigenvectors=False)) + from scipy.sandbox.arpack import eigen + return norm(eigen(A, k=1, ncv=min(10,A.shape[0]), which='LM', tol=tol, return_eigenvectors=False)) if not isspmatrix(A): A = asmatrix(A) #convert dense arrays to matrix type From scipy-svn at scipy.org Wed Jan 16 07:05:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 16 Jan 2008 06:05:26 -0600 (CST) Subject: [Scipy-svn] r3840 - trunk/scipy/misc/tests Message-ID: <20080116120526.EFEDC39C1C8@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-16 06:05:14 -0600 (Wed, 16 Jan 2008) New Revision: 3840 Modified: trunk/scipy/misc/tests/test_pilutil.py Log: Only run PIL tests if PIL is importable Modified: trunk/scipy/misc/tests/test_pilutil.py =================================================================== --- trunk/scipy/misc/tests/test_pilutil.py 2008-01-15 19:32:21 UTC (rev 3839) +++ trunk/scipy/misc/tests/test_pilutil.py 2008-01-16 12:05:14 UTC (rev 3840) @@ -4,7 +4,14 @@ from scipy.testing import * -import PIL.Image +try: + import PIL.Image +except ImportError: + _have_PIL = False +else: + _have_PIL = True +TestCase.__test__ = _have_PIL + import scipy.misc.pilutil as pilutil datapath = os.path.dirname(__file__) @@ -29,6 +36,7 @@ assert img.min() >= imin assert img.max() <= imax + at dec.is_nosetest(_have_PIL) def test_fromimage(): ''' Test generator for parametric tests ''' data = {'icon.png':(0,255), From scipy-svn at scipy.org Wed Jan 16 07:27:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 16 Jan 2008 06:27:47 -0600 (CST) Subject: [Scipy-svn] r3841 - in trunk/scipy: linsolve sandbox/multigrid sparse/tests Message-ID: <20080116122747.DF647C7C058@new.scipy.org> Author: wnbell Date: 2008-01-16 06:27:45 -0600 (Wed, 16 Jan 2008) New Revision: 3841 Modified: trunk/scipy/linsolve/linsolve.py trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sparse/tests/test_base.py Log: cleaned up linsolve Modified: trunk/scipy/linsolve/linsolve.py =================================================================== --- trunk/scipy/linsolve/linsolve.py 2008-01-16 12:05:14 UTC (rev 3840) +++ trunk/scipy/linsolve/linsolve.py 2008-01-16 12:27:45 UTC (rev 3841) @@ -1,7 +1,11 @@ -from scipy.sparse import isspmatrix_csc, isspmatrix_csr, isspmatrix, spdiags -import _superlu +from warnings import warn + from numpy import asarray +from scipy.sparse import isspmatrix_csc, isspmatrix_csr, isspmatrix, \ + SparseEfficiencyWarning, csc_matrix +import _superlu + import umfpack if hasattr( umfpack, 'UMFPACK_OK' ): isUmfpack = True @@ -10,6 +14,7 @@ isUmfpack = False useUmfpack = True + #convert numpy char to superLU char superLU_transtabl = {'f':'s', 'd':'d', 'F':'c', 'D':'z'} @@ -34,30 +39,10 @@ if isUmfpack: umfpack.configure( **kwargs ) -def _toCS_superLU( A ): - if hasattr(A, 'tocsc') and not isspmatrix_csr( A ): - mat = A.tocsc() - csc = 1 - elif hasattr(A, 'tocsr'): - mat = A.tocsr() - csc = 0 - else: - raise ValueError, "matrix cannot be converted to CSC/CSR" - return mat, csc -def _toCS_umfpack( A ): - if isspmatrix_csr( A ) or isspmatrix_csc( A ): - mat = A - else: - if hasattr(A, 'tocsc'): - mat = A.tocsc() - elif hasattr(A, 'tocsr'): - mat = A.tocsr() - else: - raise ValueError, "matrix cannot be converted to CSC/CSR" - return mat - def spsolve(A, b, permc_spec=2): + """Solve the sparse linear system Ax=b + """ if isspmatrix( b ): b = b.toarray() @@ -67,47 +52,44 @@ else: raise ValueError, "rhs must be a vector (has shape %s)" % (b.shape,) - if not isspmatrix(A): - raise TypeError,'expected sparse matrix' + if not (isspmatrix_csc(A) or isspmatrix_csr(A)): + A = csc_matrix(A) + warn('spsolve requires CSC or CSR matrix format', SparseEfficiencyWarning) + A.sort_indices() A = A.asfptype() #upcast to a floating point format - if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'): - raise ValueError, "sparse matrix must be able to return CSC format--"\ - "A.tocsc()--or CSR format--A.tocsr()" - if not hasattr(A, 'shape'): - raise ValueError, "sparse matrix must be able to return shape" \ - " (rows, cols) = A.shape" M, N = A.shape if (M != N): - raise ValueError, "matrix must be square (has shape %s)" % (A.shape,) + raise ValueError, "matrix must be square (has shape %s)" % (M,N) if M != b.size: raise ValueError, "matrix - rhs size mismatch (%s - %s)"\ - % (A.shape, b.shape) + % (A.shape, b.size) - if isUmfpack and useUmfpack: - mat = _toCS_umfpack( A ) - - if mat.dtype.char not in 'dD': + if A.dtype.char not in 'dD': raise ValueError, "convert matrix data to double, please, using"\ " .astype(), or set linsolve.useUmfpack = False" family = {'d' : 'di', 'D' : 'zi'} - umf = umfpack.UmfpackContext( family[mat.dtype.char] ) - return umf.linsolve( umfpack.UMFPACK_A, mat, b, + umf = umfpack.UmfpackContext( family[A.dtype.char] ) + return umf.linsolve( umfpack.UMFPACK_A, A, b, autoTranspose = True ) else: - mat, csc = _toCS_superLU( A ) - ftype = superLU_transtabl[mat.dtype.char] - index0 = mat.indices - lastel, data, index1 = mat.nnz, mat.data, mat.indptr + if isspmatrix_csc(A): + flag = 1 # CSC format + else: + flag = 0 # CSR format + + ftype = superLU_transtabl[A.dtype.char] + gssv = eval('_superlu.' + ftype + 'gssv') - b = asarray(b, dtype=data.dtype) - return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0] + b = asarray(b, dtype=A.dtype) + return gssv(N, A.nnz, A.data, A.indices, A.indptr, b, flag, permc_spec)[0] + def splu(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): """ @@ -118,19 +100,22 @@ See scipy.linsolve._superlu.dgstrf for more info. """ + + if not isspmatrix_csc(A): + A = csc_matrix(A) + warn('splu requires CSC matrix format', SparseEfficiencyWarning) + + A.sort_indices() + A = A.asfptype() #upcast to a floating point format + M, N = A.shape if (M != N): - raise ValueError, "can only factor square matrices" + raise ValueError, "can only factor square matrices" #is this true? -## if isUmfpack: -## print "UMFPACK is present - try umfpack.numeric and umfpack.solve instead!" + ftype = superLU_transtabl[A.dtype.char] - csc = A.tocsc() - csc = csc.asfptype() #upcast to a floating point format - ftype = superLU_transtabl[csc.dtype.char] - gstrf = eval('_superlu.' + ftype + 'gstrf') - return gstrf(N, csc.nnz, csc.data, csc.indices, csc.indptr, permc_spec, + return gstrf(N, A.nnz, A.data, A.indices, A.indptr, permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) def factorized( A ): @@ -143,29 +128,34 @@ x2 = solve( rhs2 ) # Uses again the LU factors. """ if isUmfpack and useUmfpack: - mat = _toCS_umfpack( A ) + if not isspmatrix_csc(A): + A = csc_matrix(A) + warn('splu requires CSC matrix format', SparseEfficiencyWarning) - if mat.dtype.char not in 'dD': + A.sort_indices() + A = A.asfptype() #upcast to a floating point format + + if A.dtype.char not in 'dD': raise ValueError, "convert matrix data to double, please, using"\ " .astype(), or set linsolve.useUmfpack = False" family = {'d' : 'di', 'D' : 'zi'} - umf = umfpack.UmfpackContext( family[mat.dtype.char] ) + umf = umfpack.UmfpackContext( family[A.dtype.char] ) # Make LU decomposition. - umf.numeric( mat ) + umf.numeric( A ) def solve( b ): - return umf.solve( umfpack.UMFPACK_A, mat, b, autoTranspose = True ) + return umf.solve( umfpack.UMFPACK_A, A, b, autoTranspose = True ) return solve else: return splu( A ).solve def _testme(): - from scipy.sparse import csc_matrix + from scipy.sparse import csc_matrix, spdiags from numpy import array - from scipy.linsolve import spdiags, spsolve, use_solver + from scipy.linsolve import spsolve, use_solver print "Inverting a sparse linear system:" print "The sparse matrix (constructed from diagonals):" Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-16 12:05:14 UTC (rev 3840) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-16 12:27:45 UTC (rev 3841) @@ -206,7 +206,7 @@ if len(self.As) == 1: #TODO make spsolve preserve dimensions - x[:] = spsolve(A,b).reshape(x.shape) + x[:] = spsolve(A.tocsc(),b).reshape(x.shape) return self.presmoother(A,x,b) @@ -219,7 +219,7 @@ if lvl == len(self.As) - 2: #use direct solver on coarsest level #TODO reuse factors for efficiency? - coarse_x[:] = spsolve(self.As[-1],coarse_b).reshape(coarse_x.shape) + coarse_x[:] = spsolve(self.As[-1].tocsc(),coarse_b).reshape(coarse_x.shape) #coarse_x[:] = scipy.linalg.cg(self.As[-1],coarse_b,tol=1e-12)[0].reshape(coarse_x.shape) #A_inv = asarray(scipy.linalg.pinv2(self.As[-1].todense())) #coarse_x[:] = scipy.dot(A_inv,coarse_b) Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-01-16 12:05:14 UTC (rev 3840) +++ trunk/scipy/sparse/tests/test_base.py 2008-01-16 12:27:45 UTC (rev 3841) @@ -13,6 +13,8 @@ python tests/test_sparse.py """ +import warnings + import numpy from numpy import arange, zeros, array, dot, ones, matrix, asmatrix, \ asarray, vstack, ndarray, kron, transpose @@ -27,7 +29,10 @@ from scipy.linsolve import splu +warnings.simplefilter('ignore',SparseEfficiencyWarning) + + #TODO test spmatrix( [[1,2],[3,4]] ) format #TODO check that invalid shape in constructor raises exception #TODO check that spmatrix( ... , copy=X ) is respected @@ -485,8 +490,6 @@ class _TestGetSet: def test_setelement(self): - import warnings - warnings.simplefilter('ignore',SparseEfficiencyWarning) a = self.spmatrix((3,4)) a[1,2] = 4.0 a[0,1] = 3 From scipy-svn at scipy.org Wed Jan 16 08:15:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 16 Jan 2008 07:15:39 -0600 (CST) Subject: [Scipy-svn] r3842 - in trunk/scipy: linsolve/umfpack/tests misc/tests stats testing Message-ID: <20080116131539.7849D39C20E@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-16 07:15:30 -0600 (Wed, 16 Jan 2008) New Revision: 3842 Modified: trunk/scipy/linsolve/umfpack/tests/test_umfpack.py trunk/scipy/misc/tests/test_pilutil.py trunk/scipy/stats/morestats.py trunk/scipy/testing/decorators.py Log: Renamed test setting decorator, cleaned up test disabling for umfpack Modified: trunk/scipy/linsolve/umfpack/tests/test_umfpack.py =================================================================== --- trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-16 12:27:45 UTC (rev 3841) +++ trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-16 13:15:30 UTC (rev 3842) @@ -17,13 +17,11 @@ import scipy.linsolve.umfpack as um # Allow disabling of nose tests if umfpack not present -have_umfpack = um.umfpack._um is not None +TestCase.__test__ = um.umfpack._um is not None class TestSolvers(TestCase): """Tests inverting a sparse linear system""" - __test__ = have_umfpack - def test_solve_complex_without_umfpack(self): """Solve: single precision complex""" linsolve.use_solver( useUmfpack = False ) @@ -110,8 +108,6 @@ class TestFactorization(TestCase): """Tests factorizing a sparse linear system""" - __test__ = have_umfpack - def test_complex_lu(self): """Getting factors of complex matrix""" umfpack = um.UmfpackContext("zi") Modified: trunk/scipy/misc/tests/test_pilutil.py =================================================================== --- trunk/scipy/misc/tests/test_pilutil.py 2008-01-16 12:27:45 UTC (rev 3841) +++ trunk/scipy/misc/tests/test_pilutil.py 2008-01-16 13:15:30 UTC (rev 3842) @@ -36,7 +36,7 @@ assert img.min() >= imin assert img.max() <= imax - at dec.is_nosetest(_have_PIL) + at dec.setastest(_have_PIL) def test_fromimage(): ''' Test generator for parametric tests ''' data = {'icon.png':(0,255), Modified: trunk/scipy/stats/morestats.py =================================================================== --- trunk/scipy/stats/morestats.py 2008-01-16 12:27:45 UTC (rev 3841) +++ trunk/scipy/stats/morestats.py 2008-01-16 13:15:30 UTC (rev 3842) @@ -17,7 +17,7 @@ import scipy.special as special import futil import numpy as sb -from scipy.testing.decorators import is_nosetest +from scipy.testing.decorators import setastest __all__ = ['find_repeats', 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot', @@ -770,7 +770,7 @@ pval = distributions.f.sf(W,k-1,Ntot-k) # 1 - cdf return W, pval - at is_nosetest(False) + at setastest(False) def binom_test(x,n=None,p=0.5): """An exact (two-sided) test of the null hypothesis that the probability of success in a Bernoulli experiment is p. Modified: trunk/scipy/testing/decorators.py =================================================================== --- trunk/scipy/testing/decorators.py 2008-01-16 12:27:45 UTC (rev 3841) +++ trunk/scipy/testing/decorators.py 2008-01-16 13:15:30 UTC (rev 3842) @@ -27,11 +27,11 @@ t.willfail = True return t -def is_nosetest(tf): +def setastest(tf=True): ''' Signals to nose that this function is or is not a test - + e.g - >>> @is_nosetest(False) + >>> @setastest(False) >>> def func_with_test_in_name(arg1, arg2): pass ... >>> From scipy-svn at scipy.org Wed Jan 16 16:57:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 16 Jan 2008 15:57:57 -0600 (CST) Subject: [Scipy-svn] r3843 - in trunk/scipy/sandbox/multigrid: . examples tests Message-ID: <20080116215757.9853A39C015@new.scipy.org> Author: wnbell Date: 2008-01-16 15:57:52 -0600 (Wed, 16 Jan 2008) New Revision: 3843 Modified: trunk/scipy/sandbox/multigrid/examples/adaptive.py trunk/scipy/sandbox/multigrid/tests/test_sa.py trunk/scipy/sandbox/multigrid/tests/test_utils.py trunk/scipy/sandbox/multigrid/utils.py Log: fixed error in approximate_spectral_radius Modified: trunk/scipy/sandbox/multigrid/examples/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-16 13:15:30 UTC (rev 3842) +++ trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-16 21:57:52 UTC (rev 3843) @@ -10,7 +10,7 @@ #A = poisson( (200,200), spacing=(1,1e-2) ) #anisotropic D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() -A = D * A * D +#A = D * A * D Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-16 13:15:30 UTC (rev 3842) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-16 21:57:52 UTC (rev 3843) @@ -202,9 +202,9 @@ x_sol,residuals = ml.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) avg_convergence_ratio = (residuals[-1]/residuals[0])**(1.0/len(residuals)) + + assert(avg_convergence_ratio < 0.25) - assert(avg_convergence_ratio < 0.5) - def test_DAD(self): A = poisson( (100,100), format='csr' ) @@ -218,20 +218,17 @@ B = ones((A.shape[0],1)) - Dinv_B = D_inv * B - #TODO force 2 level method and check that result is the same - sa1 = smoothed_aggregation_solver(A, B, max_levels=2, rescale=False) - sa2 = smoothed_aggregation_solver(D*A*D, D_inv * B, max_levels=2, rescale=False) + #sa1 = smoothed_aggregation_solver(A, B, max_levels=2, rescale=False) + sa2 = smoothed_aggregation_solver(D*A*D, D_inv * B, max_levels=2, rescale=True) #assert_almost_equal( sa2.Ps[0], sa1.Ps[0] x_sol,residuals = sa2.solve(b,x0=x,maxiter=10,tol=1e-12,return_residuals=True) avg_convergence_ratio = (residuals[-1]/residuals[0])**(1.0/len(residuals)) - print avg_convergence_ratio - - assert(avg_convergence_ratio < 0.2) + + assert(avg_convergence_ratio < 0.25) Modified: trunk/scipy/sandbox/multigrid/tests/test_utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-16 13:15:30 UTC (rev 3842) +++ trunk/scipy/sandbox/multigrid/tests/test_utils.py 2008-01-16 21:57:52 UTC (rev 3843) @@ -1,39 +1,38 @@ from scipy.testing import * -import numpy -import scipy -from numpy import matrix,array,diag,zeros,sqrt +from numpy import matrix, array, diag, zeros, sqrt from scipy import rand from scipy.sparse import csr_matrix -from scipy.linalg import norm +from scipy.linalg import eigvals, norm - from scipy.sandbox.multigrid.utils import * from scipy.sandbox.multigrid.utils import symmetric_rescaling class TestUtils(TestCase): -# def test_approximate_spectral_radius(self): -# cases = [] -# -# cases.append( matrix([[-4]]) ) -# cases.append( array([[-4]]) ) -# -# cases.append( array([[2,0],[0,1]]) ) -# cases.append( array([[-2,0],[0,1]]) ) -# -# cases.append( array([[100,0,0],[0,101,0],[0,0,99]]) ) -# -# for i in range(1,5): -# cases.append( rand(i,i) ) -# -# # method should be almost exact for small matrices -# for A in cases: -# A = A.astype(float) -# Asp = csr_matrix(A) -# assert_almost_equal( approximate_spectral_radius(A,tol=1e-2), norm(A,2), decimal=1 ) -# assert_almost_equal( approximate_spectral_radius(Asp,tol=1e-2), norm(A,2), decimal=1 ) -# -# #TODO test larger matrices + def test_approximate_spectral_radius(self): + cases = [] + + cases.append( matrix([[-4]]) ) + cases.append( array([[-4]]) ) + + cases.append( array([[2,0],[0,1]]) ) + cases.append( array([[-2,0],[0,1]]) ) + + cases.append( array([[100,0,0],[0,101,0],[0,0,99]]) ) + + for i in range(1,5): + cases.append( rand(i,i) ) + + # method should be almost exact for small matrices + for A in cases: + A = A.astype(float) + Asp = csr_matrix(A) + + expected = max([norm(x) for x in eigvals(A)]) + assert_almost_equal( approximate_spectral_radius(A), expected ) + assert_almost_equal( approximate_spectral_radius(Asp), expected ) + + #TODO test larger matrices def test_infinity_norm(self): A = matrix([[-4]]) Modified: trunk/scipy/sandbox/multigrid/utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/utils.py 2008-01-16 13:15:30 UTC (rev 3842) +++ trunk/scipy/sandbox/multigrid/utils.py 2008-01-16 21:57:52 UTC (rev 3843) @@ -3,16 +3,16 @@ import numpy import scipy -from scipy import ravel,arange,concatenate,tile,asarray,sqrt,diff, \ - rand,zeros,empty,asmatrix,dot -from scipy.linalg import norm,eigvals +from scipy import ravel, arange, concatenate, tile, asarray, sqrt, diff, \ + rand, zeros, ones, empty, asmatrix, dot +from scipy.linalg import norm, eigvals from scipy.sparse import isspmatrix, isspmatrix_csr, isspmatrix_csc, \ isspmatrix_bsr, csr_matrix, csc_matrix, bsr_matrix, coo_matrix, \ extract_diagonal from scipy.sparse.sputils import upcast -def approximate_spectral_radius(A,tol=0.1,maxiter=20,symmetric=None): +def approximate_spectral_radius(A,tol=0.1,maxiter=10,symmetric=None): """approximate the spectral radius of a matrix *Parameters*: @@ -36,8 +36,8 @@ An approximation to the spectral radius of A (scalar value) """ - from scipy.sandbox.arpack import eigen - return norm(eigen(A, k=1, ncv=min(10,A.shape[0]), which='LM', tol=tol, return_eigenvectors=False)) + #from scipy.sandbox.arpack import eigen + #return norm(eigen(A, k=1, ncv=min(10,A.shape[0]), which='LM', tol=tol, return_eigenvectors=False)) if not isspmatrix(A): A = asmatrix(A) #convert dense arrays to matrix type @@ -98,8 +98,8 @@ V = V[1:] H[1,0] = H[0,1] beta = H[2,1] - - return norm(H[:j+1,:j+1],2) + + return max([norm(x) for x in eigvals(H[:j+1,:j+1])]) @@ -112,9 +112,9 @@ if isspmatrix_csr(A) or isspmatrix_csc(A): #avoid copying index and ptr arrays abs_A = A.__class__((abs(A.data),A.indices,A.indptr),shape=A.shape) - return (abs_A * numpy.ones(A.shape[1],dtype=A.dtype)).max() + return (abs_A * ones(A.shape[1],dtype=A.dtype)).max() else: - return (abs(A) * numpy.ones(A.shape[1],dtype=A.dtype)).max() + return (abs(A) * ones(A.shape[1],dtype=A.dtype)).max() def diag_sparse(A): """ From scipy-svn at scipy.org Wed Jan 16 17:42:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 16 Jan 2008 16:42:53 -0600 (CST) Subject: [Scipy-svn] r3844 - in trunk/scipy/sandbox/multigrid: . examples Message-ID: <20080116224253.4A3F339C11F@new.scipy.org> Author: wnbell Date: 2008-01-16 16:42:48 -0600 (Wed, 16 Jan 2008) New Revision: 3844 Modified: trunk/scipy/sandbox/multigrid/adaptive.py trunk/scipy/sandbox/multigrid/examples/adaptive.py trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sandbox/multigrid/utils.py Log: reworked aSA to better agree with SA Modified: trunk/scipy/sandbox/multigrid/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-16 21:57:52 UTC (rev 3843) +++ trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-16 22:42:48 UTC (rev 3844) @@ -48,148 +48,187 @@ return As,Ps,Ts,Bs -class adaptive_sa_solver: - def __init__(self, A, aggregation=None, max_levels=10, max_coarse=100,\ - max_candidates=1, mu=5, epsilon=0.1): +def adaptive_sa_solver(A, max_candidates=1, mu=5, max_levels=10, max_coarse=100, \ + epsilon=0.0, omega=4.0/3.0, symmetric=True, rescale=True, + aggregation=None): + """Create a multilevel solver using Smoothed Aggregation (SA) + + *Parameters*: + + A : {csr_matrix} + NxN matrix in CSR or BSR format + max_candidates : {integer} : default 1 + Maximum number of near-nullspace candidates to generate. + mu : {integer} : default 5 + Number of cycles used at each level of the adaptive setup phase. + max_levels: {integer} : default 10 + Maximum number of levels to be used in the multilevel solver. + max_coarse: {integer} : default 500 + Maximum number of variables permitted on the coarse grid. + epsilon: {float} : default 0.0 + Strength of connection parameter used in aggregation. + omega: {float} : default 4.0/3.0 + Damping parameter used in prolongator smoothing (0 < omega < 2) + symmetric: {boolean} : default True + True if A is symmetric, False otherwise + rescale: {boolean} : default True + If True, symmetrically rescale A by the diagonal + i.e. A -> D * A * D, where D is diag(A)^-0.5 + aggregation: {None, list of csr_matrix} : optional + List of csr_matrix objects that describe a user-defined + multilevel aggregation of the variables. + TODO ELABORATE + + *Notes*: + Unlike the standard Smoothed Aggregation (SA) method, adaptive SA + does not require knowledge of near-nullspace candidate vectors. + Instead, an adaptive procedure computes one or more candidates + 'from scratch'. This approach is useful when no candidates are known + or the candidates have been invalidated due to changes to matrix A. - self.A = A - self.Rs = [] - if self.A.shape[0] <= max_coarse: - raise ValueError,'small matrices not handled yet' + *Example*: + TODO - #first candidate - x,AggOps = self.__initialization_stage(A, max_levels = max_levels, \ - max_coarse = max_coarse, \ - mu = mu, epsilon = epsilon, \ - aggregation = aggregation ) + *References*: + "Adaptive Smoothed Aggregation ($\alpha$SA) Multigrid" + Brezina, Falgout, MacLachlan, Manteuffel, McCormick, and Ruge + SIAM Review Volume 47 , Issue 2 (2005) + http://www.cs.umn.edu/~maclach/research/aSA2.pdf - #create SA using x here - As,Ps,Ts,Bs = sa_hierarchy(A,x,AggOps) + """ + + if A.shape[0] <= max_coarse: + raise ValueError,'small matrices not handled yet' - for i in range(max_candidates - 1): - x = self.__develop_new_candidate(As,Ps,Ts,Bs,AggOps,mu=mu) + #first candidate + x,AggOps = asa_initial_setup_stage(A, max_levels = max_levels, \ + max_coarse = max_coarse, mu = mu, epsilon = epsilon, \ + aggregation = aggregation ) - B = hstack((Bs[0],x)) - As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) + #create SA using x here + As,Ps,Ts,Bs = sa_hierarchy(A,x,AggOps) - #improve candidates? - if False: - print "improving candidates" - B = Bs[0] - for i in range(max_candidates): - B = B[:,1:] - As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) - x = self.__develop_new_candidate(As,Ps,Ts,Bs,AggOps,mu=mu) - B = hstack((B,x)) + for i in range(max_candidates - 1): + x = asa_general_setup_stage(As,Ps,Ts,Bs,AggOps,mu=mu) + + B = hstack((Bs[0],x)) + As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) + + #improve candidates? + if False: + print "improving candidates" + B = Bs[0] + for i in range(max_candidates): + B = B[:,1:] As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) + x = asa_general_setup_stage(As,Ps,Ts,Bs,AggOps,mu=mu) + B = hstack((B,x)) + As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) - self.Ts = Ts - self.solver = multilevel_solver(As,Ps) - self.AggOps = AggOps - self.Bs = Bs + return multilevel_solver(As,Ps) - def __initialization_stage(self,A,max_levels,max_coarse,mu,epsilon,aggregation): - if aggregation is not None: - max_coarse = 0 - max_levels = len(aggregation) + 1 +def asa_initial_setup_stage(A, max_levels, max_coarse, mu, epsilon, aggregation): + if aggregation is not None: + max_coarse = 0 + max_levels = len(aggregation) + 1 - # aSA parameters - # mu - number of test relaxation iterations - # epsilon - minimum acceptable relaxation convergence factor + # aSA parameters + # mu - number of test relaxation iterations + # epsilon - minimum acceptable relaxation convergence factor - #step 1 - A_l = A - x = rand(A_l.shape[0],1) # TODO see why randn() fails here - skip_f_to_i = False + #step 1 + A_l = A + x = rand(A_l.shape[0],1) # TODO see why randn() fails here + skip_f_to_i = False - #step 2 - gauss_seidel(A_l, x, zeros_like(x), iterations=mu, sweep='symmetric') + #step 2 + gauss_seidel(A_l, x, zeros_like(x), iterations=mu, sweep='symmetric') - #step 3 - #TODO test convergence rate here + #step 3 + #TODO test convergence rate here - As = [A] - Ps = [] - AggOps = [] + As = [A] + Ps = [] + AggOps = [] - while len(AggOps) + 1 < max_levels and A_l.shape[0] > max_coarse: - if aggregation is None: - W_l = sa_constant_interpolation(A_l,epsilon=0) #step 4b - else: - W_l = aggregation[len(AggOps)] - P_l,x = sa_fit_candidates(W_l,x) #step 4c - I_l = sa_smoothed_prolongator(A_l,P_l) #step 4d - A_l = I_l.T.tocsr() * A_l * I_l #step 4e + while len(AggOps) + 1 < max_levels and A_l.shape[0] > max_coarse: + if aggregation is None: + W_l = sa_constant_interpolation(A_l,epsilon=0) #step 4b + else: + W_l = aggregation[len(AggOps)] + P_l,x = sa_fit_candidates(W_l,x) #step 4c + I_l = sa_smoothed_prolongator(A_l,P_l) #step 4d + A_l = I_l.T.tocsr() * A_l * I_l #step 4e - AggOps.append(W_l) - Ps.append(I_l) - As.append(A_l) + AggOps.append(W_l) + Ps.append(I_l) + As.append(A_l) - if A_l.shape <= max_coarse: break + if A_l.shape <= max_coarse: break - if not skip_f_to_i: - x_hat = x.copy() #step 4g - gauss_seidel(A_l,x,zeros_like(x),iterations=mu,sweep='symmetric') #step 4h - x_A_x = dot(x.T,A_l*x) - if (x_A_x/dot(x_hat.T,A_l*x_hat))**(1.0/mu) < epsilon: #step 4i - print "sufficient convergence, skipping" - skip_f_to_i = True - if x_A_x == 0: - x = x_hat #need to restore x + if not skip_f_to_i: + x_hat = x.copy() #step 4g + gauss_seidel(A_l,x,zeros_like(x),iterations=mu,sweep='symmetric') #step 4h + x_A_x = dot(x.T,A_l*x) + if (x_A_x/dot(x_hat.T,A_l*x_hat))**(1.0/mu) < epsilon: #step 4i + print "sufficient convergence, skipping" + skip_f_to_i = True + if x_A_x == 0: + x = x_hat #need to restore x - #update fine-level candidate - for A_l,I in reversed(zip(As[1:],Ps)): - gauss_seidel(A_l,x,zeros_like(x),iterations=mu,sweep='symmetric') #TEST - x = I * x - gauss_seidel(A,x,zeros_like(x),iterations=mu,sweep='symmetric') #TEST + #update fine-level candidate + for A_l,I in reversed(zip(As[1:],Ps)): + gauss_seidel(A_l,x,zeros_like(x),iterations=mu,sweep='symmetric') #TEST + x = I * x + gauss_seidel(A,x,zeros_like(x),iterations=mu,sweep='symmetric') #TEST - return x,AggOps #first candidate,aggregation + return x,AggOps #first candidate,aggregation - def __develop_new_candidate(self,As,Ps,Ts,Bs,AggOps,mu): - A = As[0] +def asa_general_setup_stage(As, Ps, Ts, Bs, AggOps, mu): + A = As[0] - x = randn(A.shape[0],1) - b = zeros_like(x) + x = randn(A.shape[0],1) + b = zeros_like(x) - x = multilevel_solver(As,Ps).solve(b, x0=x, tol=1e-10, maxiter=mu) + x = multilevel_solver(As,Ps).solve(b, x0=x, tol=1e-10, maxiter=mu) - #TEST FOR CONVERGENCE HERE + #TEST FOR CONVERGENCE HERE - temp_Ps = [] - temp_As = [A] + temp_Ps = [] + temp_As = [A] - def make_bridge(P): - M,N = P.shape - K = P.blocksize[0] - bnnz = P.indptr[-1] - data = zeros( (bnnz, K+1, K), dtype=P.dtype ) - data[:,:-1,:-1] = P.data - return bsr_matrix( (data, P.indices, P.indptr), shape=( (K+1)*(M/K), N) ) + def make_bridge(P): + M,N = P.shape + K = P.blocksize[0] + bnnz = P.indptr[-1] + data = zeros( (bnnz, K+1, K), dtype=P.dtype ) + data[:,:-1,:-1] = P.data + return bsr_matrix( (data, P.indices, P.indptr), shape=( (K+1)*(M/K), N) ) - for i in range(len(As) - 2): - B = zeros( (x.shape[0], Bs[i+1].shape[1] + 1), dtype=x.dtype) - T,R = sa_fit_candidates(AggOp,B) + for i in range(len(As) - 2): + B = zeros( (x.shape[0], Bs[i+1].shape[1] + 1), dtype=x.dtype) + T,R = sa_fit_candidates(AggOp,B) - P = sa_smoothed_prolongator(A,T) - A = P.T.tocsr() * A * P + P = sa_smoothed_prolongator(A,T) + A = P.T.tocsr() * A * P - temp_Ps.append(P) - temp_As.append(A) + temp_Ps.append(P) + temp_As.append(A) - bridge = make_bridge(Ps[i+1]) + bridge = make_bridge(Ps[i+1]) - solver = multilevel_solver( [A] + As[i+2:], [bridge] + Ps[i+2:] ) + solver = multilevel_solver( [A] + As[i+2:], [bridge] + Ps[i+2:] ) - x = R[:,-1].reshape(-1,1) - x = solver.solve(zeros_like(x), x0=x, tol=1e-8, maxiter=mu) + x = R[:,-1].reshape(-1,1) + x = solver.solve(zeros_like(x), x0=x, tol=1e-8, maxiter=mu) - for A,P in reversed(zip(temp_As,temp_Ps)): - x = P * x - gauss_seidel(A,x,zeros_like(x),iterations=mu,sweep='symmetric') + for A,P in reversed(zip(temp_As,temp_Ps)): + x = P * x + gauss_seidel(A,x,zeros_like(x),iterations=mu,sweep='symmetric') - return x + return x # def __augment_cycle(self,As,Ps,Ts,Bs,AggOps,x): # A = As[0] Modified: trunk/scipy/sandbox/multigrid/examples/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-16 21:57:52 UTC (rev 3843) +++ trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-16 22:42:48 UTC (rev 3844) @@ -10,7 +10,7 @@ #A = poisson( (200,200), spacing=(1,1e-2) ) #anisotropic D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() -#A = D * A * D +A = D * A * D @@ -28,12 +28,12 @@ print "solving" if True: - x_sol,residuals = asa.solver.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) + x_sol,residuals = asa.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) else: residuals = [] def add_resid(x): residuals.append(linalg.norm(b - A*x)) - A.psolve = asa.solver.psolve + A.psolve = asa.psolve x_sol = linalg.cg(A,b,x0=x,maxiter=30,tol=1e-12,callback=add_resid)[0] residuals = array(residuals)/residuals[0] @@ -43,7 +43,7 @@ print "last convergence factor",residuals[-1]/residuals[-2] print -print asa.solver +print asa print "constant Rayleigh quotient",dot(ones(A.shape[0]),A*ones(A.shape[0]))/float(A.shape[0]) @@ -69,10 +69,10 @@ show() -for c in asa.Bs[0].T: - plot2d(c) - #plot2d_arrows(c) - print "candidate Rayleigh quotient",dot(c,A*c)/dot(c,c) +#for c in asa.Bs[0].T: +# plot2d(c) +# #plot2d_arrows(c) +# print "candidate Rayleigh quotient",dot(c,A*c)/dot(c,c) #plot2d(x_sol) Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-16 21:57:52 UTC (rev 3843) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-16 22:42:48 UTC (rev 3844) @@ -41,11 +41,9 @@ -def smoothed_aggregation_solver(A, B=None, \ - aggregation=None, max_levels=10, \ - max_coarse=500, epsilon=0.0, \ - omega=4.0/3.0, symmetric=True, \ - rescale = True): +def smoothed_aggregation_solver(A, B=None, max_levels=10, max_coarse=500, \ + epsilon=0.0, omega=4.0/3.0, symmetric=True, rescale=True, \ + aggregation=None): """Create a multilevel solver using Smoothed Aggregation (SA) *Parameters*: @@ -55,19 +53,6 @@ B : {None, array_like} : optional Near-nullspace candidates stored in the columns of an NxK array. The default value B=None is equivalent to B=ones((N,1)) - blocks : {None, array_like} : optional - Array of length N that groups the variables into 'superblocks'. - For example, in a 2d vector-valued problem where the even - variables [0,2,4,...N-2] correspond to the x-components and the - odd variables [1,3,5,...,N-1] correspond to the y-components then - blocks=[0,0,1,1,2,2,...,N/2,N/2] is expected. The default - value blocks=None is equivalent to blocks=[0,1,2,..,N] which - implies that each variable should be aggregated seperately. - The default is appropriate for scalar valued problems. - aggregation: {None, list of csr_matrix} : optional - List of csr_matrix objects that describe a user-defined - multilevel aggregation of the variables. - TODO ELABORATE max_levels: {integer} : default 10 Maximum number of levels to be used in the multilevel solver. max_coarse: {integer} : default 500 @@ -81,6 +66,10 @@ rescale: {boolean} : default True If True, symmetrically rescale A by the diagonal i.e. A -> D * A * D, where D is diag(A)^-0.5 + aggregation: {None, list of csr_matrix} : optional + List of csr_matrix objects that describe a user-defined + multilevel aggregation of the variables. + TODO ELABORATE *Example*: TODO Modified: trunk/scipy/sandbox/multigrid/utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/utils.py 2008-01-16 21:57:52 UTC (rev 3843) +++ trunk/scipy/sandbox/multigrid/utils.py 2008-01-16 22:42:48 UTC (rev 3844) @@ -21,6 +21,7 @@ tol : {scalar} Tolerance of approximation + Currently unused maxiter : {integer} Maximum number of iterations to perform From scipy-svn at scipy.org Thu Jan 17 00:52:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 16 Jan 2008 23:52:53 -0600 (CST) Subject: [Scipy-svn] r3845 - trunk/scipy/sandbox Message-ID: <20080117055253.DB4AF39C168@new.scipy.org> Author: rkern Date: 2008-01-16 23:52:52 -0600 (Wed, 16 Jan 2008) New Revision: 3845 Removed: trunk/scipy/sandbox/delaunay/ Log: delaunay sandbox package moved to scikits.delaunay From scipy-svn at scipy.org Thu Jan 17 09:00:55 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 17 Jan 2008 08:00:55 -0600 (CST) Subject: [Scipy-svn] r3846 - trunk/scipy/sandbox Message-ID: <20080117140055.69B22C7C0D2@new.scipy.org> Author: dhuard Date: 2008-01-17 08:00:45 -0600 (Thu, 17 Jan 2008) New Revision: 3846 Removed: trunk/scipy/sandbox/dhuard/ Log: Removed dhuard sandbox directory From scipy-svn at scipy.org Thu Jan 17 10:13:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 17 Jan 2008 09:13:53 -0600 (CST) Subject: [Scipy-svn] r3847 - trunk/scipy/sparse Message-ID: <20080117151353.2C35339C019@new.scipy.org> Author: wnbell Date: 2008-01-17 09:13:50 -0600 (Thu, 17 Jan 2008) New Revision: 3847 Modified: trunk/scipy/sparse/base.py Log: fixed typo in asfptype Modified: trunk/scipy/sparse/base.py =================================================================== --- trunk/scipy/sparse/base.py 2008-01-17 14:00:45 UTC (rev 3846) +++ trunk/scipy/sparse/base.py 2008-01-17 15:13:50 UTC (rev 3847) @@ -5,6 +5,7 @@ from warnings import warn +import numpy from numpy import asarray, asmatrix, asanyarray, ones from sputils import isdense, isscalarlike, isintlike From scipy-svn at scipy.org Thu Jan 17 10:41:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 17 Jan 2008 09:41:47 -0600 (CST) Subject: [Scipy-svn] r3848 - trunk/scipy/linsolve Message-ID: <20080117154147.04EA739C019@new.scipy.org> Author: wnbell Date: 2008-01-17 09:41:44 -0600 (Thu, 17 Jan 2008) New Revision: 3848 Modified: trunk/scipy/linsolve/linsolve.py Log: fixed bug with umfpack and 2D RHS Modified: trunk/scipy/linsolve/linsolve.py =================================================================== --- trunk/scipy/linsolve/linsolve.py 2008-01-17 15:13:50 UTC (rev 3847) +++ trunk/scipy/linsolve/linsolve.py 2008-01-17 15:41:44 UTC (rev 3848) @@ -71,6 +71,8 @@ if A.dtype.char not in 'dD': raise ValueError, "convert matrix data to double, please, using"\ " .astype(), or set linsolve.useUmfpack = False" + + b = asarray(b, dtype=A.dtype).reshape(-1) family = {'d' : 'di', 'D' : 'zi'} umf = umfpack.UmfpackContext( family[A.dtype.char] ) From scipy-svn at scipy.org Fri Jan 18 18:49:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 18 Jan 2008 17:49:12 -0600 (CST) Subject: [Scipy-svn] r3849 - in trunk/scipy: . fftpack fftpack/benchmarks fftpack/tests linalg linalg/benchmarks linalg/tests optimize optimize/benchmarks optimize/tests sparse sparse/benchmarks stsci/image/lib testing Message-ID: <20080118234912.03E9D39C337@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-18 17:48:52 -0600 (Fri, 18 Jan 2008) New Revision: 3849 Added: trunk/scipy/fftpack/benchmarks/ trunk/scipy/fftpack/benchmarks/bench_basic.py trunk/scipy/fftpack/benchmarks/bench_pseudo_diffs.py trunk/scipy/linalg/benchmarks/ trunk/scipy/linalg/benchmarks/bench_basic.py trunk/scipy/linalg/benchmarks/bench_decom.py trunk/scipy/optimize/_tstutils.py trunk/scipy/optimize/benchmarks/ trunk/scipy/optimize/benchmarks/bench_zeros.py trunk/scipy/sparse/benchmarks/bench_sparse.py Removed: trunk/scipy/sparse/benchmarks/test_sparse.py Modified: trunk/scipy/__init__.py trunk/scipy/fftpack/__init__.py trunk/scipy/fftpack/tests/test_basic.py trunk/scipy/fftpack/tests/test_pseudo_diffs.py trunk/scipy/linalg/__init__.py trunk/scipy/linalg/tests/test_basic.py trunk/scipy/linalg/tests/test_decomp.py trunk/scipy/optimize/__init__.py trunk/scipy/optimize/tests/test_zeros.py trunk/scipy/sparse/__init__.py trunk/scipy/stsci/image/lib/_image.py trunk/scipy/testing/decorators.py trunk/scipy/testing/nosetester.py Log: Moved benchmarks over to benchmark directories, added .bench function, cleanup up stsci import Modified: trunk/scipy/__init__.py =================================================================== --- trunk/scipy/__init__.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/__init__.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -64,7 +64,7 @@ from testing.pkgtester import Tester test = Tester().test - +bench = Tester().bench __doc__ += """ Utility tools Modified: trunk/scipy/fftpack/__init__.py =================================================================== --- trunk/scipy/fftpack/__init__.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/fftpack/__init__.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -19,3 +19,4 @@ from scipy.testing.pkgtester import Tester test = Tester().test +bench = Tester().bench Added: trunk/scipy/fftpack/benchmarks/bench_basic.py =================================================================== --- trunk/scipy/fftpack/benchmarks/bench_basic.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/fftpack/benchmarks/bench_basic.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -0,0 +1,220 @@ +""" Test functions for fftpack.basic module +""" +import sys +from scipy.testing import * +from scipy.fftpack import ifft,fft,fftn,ifftn,rfft,irfft +from scipy.fftpack import _fftpack as fftpack + +from numpy import arange, add, array, asarray, zeros, dot, exp, pi,\ + swapaxes, double, cdouble +import numpy.fft + +from numpy.random import rand +def random(size): + return rand(*size) + +def direct_dft(x): + x = asarray(x) + n = len(x) + y = zeros(n,dtype=cdouble) + w = -arange(n)*(2j*pi/n) + for i in range(n): + y[i] = dot(exp(i*w),x) + return y + +def direct_idft(x): + x = asarray(x) + n = len(x) + y = zeros(n,dtype=cdouble) + w = arange(n)*(2j*pi/n) + for i in range(n): + y[i] = dot(exp(i*w),x)/n + return y + + +class TestFft(TestCase): + + def bench_random(self): + from numpy.fft import fft as numpy_fft + print + print ' Fast Fourier Transform' + print '=================================================' + print ' | real input | complex input ' + print '-------------------------------------------------' + print ' size | scipy | numpy | scipy | numpy ' + print '-------------------------------------------------' + for size,repeat in [(100,7000),(1000,2000), + (256,10000), + (512,10000), + (1024,1000), + (2048,1000), + (2048*2,500), + (2048*4,500), + ]: + print '%5s' % size, + sys.stdout.flush() + + for x in [random([size]).astype(double), + random([size]).astype(cdouble)+random([size]).astype(cdouble)*1j + ]: + if size > 500: y = fft(x) + else: y = direct_dft(x) + assert_array_almost_equal(fft(x),y) + print '|%8.2f' % measure('fft(x)',repeat), + sys.stdout.flush() + + assert_array_almost_equal(numpy_fft(x),y) + print '|%8.2f' % measure('numpy_fft(x)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + sys.stdout.flush() + +class TestIfft(TestCase): + + def bench_random(self): + from numpy.fft import ifft as numpy_ifft + print + print ' Inverse Fast Fourier Transform' + print '===============================================' + print ' | real input | complex input ' + print '-----------------------------------------------' + print ' size | scipy | numpy | scipy | numpy ' + print '-----------------------------------------------' + for size,repeat in [(100,7000),(1000,2000), + (256,10000), + (512,10000), + (1024,1000), + (2048,1000), + (2048*2,500), + (2048*4,500), + ]: + print '%5s' % size, + sys.stdout.flush() + + for x in [random([size]).astype(double), + random([size]).astype(cdouble)+random([size]).astype(cdouble)*1j + ]: + if size > 500: y = ifft(x) + else: y = direct_idft(x) + assert_array_almost_equal(ifft(x),y) + print '|%8.2f' % measure('ifft(x)',repeat), + sys.stdout.flush() + + assert_array_almost_equal(numpy_ifft(x),y) + print '|%8.2f' % measure('numpy_ifft(x)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + sys.stdout.flush() + +class TestRfft(TestCase): + + def bench_random(self): + from numpy.fft import rfft as numpy_rfft + print + print 'Fast Fourier Transform (real data)' + print '==================================' + print ' size | scipy | numpy ' + print '----------------------------------' + for size,repeat in [(100,7000),(1000,2000), + (256,10000), + (512,10000), + (1024,1000), + (2048,1000), + (2048*2,500), + (2048*4,500), + ]: + print '%5s' % size, + sys.stdout.flush() + + x = random([size]).astype(double) + print '|%8.2f' % measure('rfft(x)',repeat), + sys.stdout.flush() + + print '|%8.2f' % measure('numpy_rfft(x)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + sys.stdout.flush() + +class TestIrfft(TestCase): + + def bench_random(self): + from numpy.fft import irfft as numpy_irfft + + print + print 'Inverse Fast Fourier Transform (real data)' + print '==================================' + print ' size | scipy | numpy ' + print '----------------------------------' + for size,repeat in [(100,7000),(1000,2000), + (256,10000), + (512,10000), + (1024,1000), + (2048,1000), + (2048*2,500), + (2048*4,500), + ]: + print '%5s' % size, + sys.stdout.flush() + + x = random([size]).astype(double) + x1 = zeros(size/2+1,dtype=cdouble) + x1[0] = x[0] + for i in range(1,size/2): + x1[i] = x[2*i-1] + 1j * x[2*i] + if not size%2: + x1[-1] = x[-1] + y = irfft(x) + + print '|%8.2f' % measure('irfft(x)',repeat), + sys.stdout.flush() + + assert_array_almost_equal(numpy_irfft(x1,size),y) + print '|%8.2f' % measure('numpy_irfft(x1,size)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + + sys.stdout.flush() + +class TestFftn(TestCase): + + def bench_random(self): + from numpy.fft import fftn as numpy_fftn + print + print ' Multi-dimensional Fast Fourier Transform' + print '===================================================' + print ' | real input | complex input ' + print '---------------------------------------------------' + print ' size | scipy | numpy | scipy | numpy ' + print '---------------------------------------------------' + for size,repeat in [((100,100),100),((1000,100),7), + ((256,256),10), + ((512,512),3), + ]: + print '%9s' % ('%sx%s'%size), + sys.stdout.flush() + + for x in [random(size).astype(double), + random(size).astype(cdouble)+random(size).astype(cdouble)*1j + ]: + y = fftn(x) + #if size > 500: y = fftn(x) + #else: y = direct_dft(x) + assert_array_almost_equal(fftn(x),y) + print '|%8.2f' % measure('fftn(x)',repeat), + sys.stdout.flush() + + assert_array_almost_equal(numpy_fftn(x),y) + print '|%8.2f' % measure('numpy_fftn(x)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + + sys.stdout.flush() + + +if __name__ == "__main__": + nose.run(argv=['', __file__]) Added: trunk/scipy/fftpack/benchmarks/bench_pseudo_diffs.py =================================================================== --- trunk/scipy/fftpack/benchmarks/bench_pseudo_diffs.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/fftpack/benchmarks/bench_pseudo_diffs.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -0,0 +1,186 @@ +""" Benchmark functions for fftpack.pseudo_diffs module +""" +import sys + +from numpy import arange, add, array, sin, cos, pi,exp,tanh,sum,sign + +from scipy.testing import * +from scipy.fftpack import diff,fft,ifft,tilbert,itilbert,hilbert,ihilbert,rfft +from scipy.fftpack import shift +from scipy.fftpack import fftfreq + +def random(size): + return rand(*size) + +def direct_diff(x,k=1,period=None): + fx = fft(x) + n = len (fx) + if period is None: + period = 2*pi + w = fftfreq(n)*2j*pi/period*n + if k<0: + w = 1 / w**k + w[0] = 0.0 + else: + w = w**k + if n>2000: + w[250:n-250] = 0.0 + return ifft(w*fx).real + +def direct_tilbert(x,h=1,period=None): + fx = fft(x) + n = len (fx) + if period is None: + period = 2*pi + w = fftfreq(n)*h*2*pi/period*n + w[0] = 1 + w = 1j/tanh(w) + w[0] = 0j + return ifft(w*fx) + +def direct_hilbert(x): + fx = fft(x) + n = len (fx) + w = fftfreq(n)*n + w = 1j*sign(w) + return ifft(w*fx) + +def direct_shift(x,a,period=None): + n = len(x) + if period is None: + k = fftfreq(n)*1j*n + else: + k = fftfreq(n)*2j*pi/period*n + return ifft(fft(x)*exp(k*a)).real + + +class TestDiff(TestCase): + + def bench_random(self): + print + print 'Differentiation of periodic functions' + print '=====================================' + print ' size | convolve | naive' + print '-------------------------------------' + for size,repeat in [(100,1500),(1000,300), + (256,1500), + (512,1000), + (1024,500), + (2048,200), + (2048*2,100), + (2048*4,50), + ]: + print '%6s' % size, + sys.stdout.flush() + x = arange (size)*2*pi/size + if size<2000: + f = sin(x)*cos(4*x)+exp(sin(3*x)) + else: + f = sin(x)*cos(4*x) + assert_array_almost_equal(diff(f,1),direct_diff(f,1)) + assert_array_almost_equal(diff(f,2),direct_diff(f,2)) + print '| %9.2f' % measure('diff(f,3)',repeat), + sys.stdout.flush() + print '| %9.2f' % measure('direct_diff(f,3)',repeat), + sys.stdout.flush() + print ' (secs for %s calls)' % (repeat) + + +class TestTilbert(TestCase): + + def bench_random(self): + print + print ' Tilbert transform of periodic functions' + print '=========================================' + print ' size | optimized | naive' + print '-----------------------------------------' + for size,repeat in [(100,1500),(1000,300), + (256,1500), + (512,1000), + (1024,500), + (2048,200), + (2048*2,100), + (2048*4,50), + ]: + print '%6s' % size, + sys.stdout.flush() + x = arange (size)*2*pi/size + if size<2000: + f = sin(x)*cos(4*x)+exp(sin(3*x)) + else: + f = sin(x)*cos(4*x) + assert_array_almost_equal(tilbert(f,1),direct_tilbert(f,1)) + print '| %9.2f' % measure('tilbert(f,1)',repeat), + sys.stdout.flush() + print '| %9.2f' % measure('direct_tilbert(f,1)',repeat), + sys.stdout.flush() + print ' (secs for %s calls)' % (repeat) + + +class TestHilbert(TestCase): + + def bench_random(self): + print + print ' Hilbert transform of periodic functions' + print '=========================================' + print ' size | optimized | naive' + print '-----------------------------------------' + for size,repeat in [(100,1500),(1000,300), + (256,1500), + (512,1000), + (1024,500), + (2048,200), + (2048*2,100), + (2048*4,50), + ]: + print '%6s' % size, + sys.stdout.flush() + x = arange (size)*2*pi/size + if size<2000: + f = sin(x)*cos(4*x)+exp(sin(3*x)) + else: + f = sin(x)*cos(4*x) + assert_array_almost_equal(hilbert(f),direct_hilbert(f)) + print '| %9.2f' % measure('hilbert(f)',repeat), + sys.stdout.flush() + print '| %9.2f' % measure('direct_hilbert(f)',repeat), + sys.stdout.flush() + print ' (secs for %s calls)' % (repeat) + + +class TestShift(TestCase): + + def bench_random(self): + print + print ' Shifting periodic functions' + print '==============================' + print ' size | optimized | naive' + print '------------------------------' + for size,repeat in [(100,1500),(1000,300), + (256,1500), + (512,1000), + (1024,500), + (2048,200), + (2048*2,100), + (2048*4,50), + ]: + print '%6s' % size, + sys.stdout.flush() + x = arange (size)*2*pi/size + a = 1 + if size<2000: + f = sin(x)*cos(4*x)+exp(sin(3*x)) + sf = sin(x+a)*cos(4*(x+a))+exp(sin(3*(x+a))) + else: + f = sin(x)*cos(4*x) + sf = sin(x+a)*cos(4*(x+a)) + assert_array_almost_equal(direct_shift(f,1),sf) + assert_array_almost_equal(shift(f,1),sf) + print '| %9.2f' % measure('shift(f,a)',repeat), + sys.stdout.flush() + print '| %9.2f' % measure('direct_shift(f,a)',repeat), + sys.stdout.flush() + print ' (secs for %s calls)' % (repeat) + +if __name__ == "__main__": + nose.run(argv=['', __file__]) Modified: trunk/scipy/fftpack/tests/test_basic.py =================================================================== --- trunk/scipy/fftpack/tests/test_basic.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/fftpack/tests/test_basic.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -124,43 +124,7 @@ y = fftpack.zrfft(x) assert_array_almost_equal(y,y2) - @dec.bench - def test_random(self): - from numpy.fft import fft as numpy_fft - print - print ' Fast Fourier Transform' - print '=================================================' - print ' | real input | complex input ' - print '-------------------------------------------------' - print ' size | scipy | numpy | scipy | numpy ' - print '-------------------------------------------------' - for size,repeat in [(100,7000),(1000,2000), - (256,10000), - (512,10000), - (1024,1000), - (2048,1000), - (2048*2,500), - (2048*4,500), - ]: - print '%5s' % size, - sys.stdout.flush() - for x in [random([size]).astype(double), - random([size]).astype(cdouble)+random([size]).astype(cdouble)*1j - ]: - if size > 500: y = fft(x) - else: y = direct_dft(x) - assert_array_almost_equal(fft(x),y) - print '|%8.2f' % measure('fft(x)',repeat), - sys.stdout.flush() - - assert_array_almost_equal(numpy_fft(x),y) - print '|%8.2f' % measure('numpy_fft(x)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - sys.stdout.flush() - class TestIfft(TestCase): def test_definition(self): @@ -200,43 +164,7 @@ assert_array_almost_equal (ifft(fft(x)),x) assert_array_almost_equal (fft(ifft(x)),x) - @dec.bench - def test_random(self): - from numpy.fft import ifft as numpy_ifft - print - print ' Inverse Fast Fourier Transform' - print '===============================================' - print ' | real input | complex input ' - print '-----------------------------------------------' - print ' size | scipy | numpy | scipy | numpy ' - print '-----------------------------------------------' - for size,repeat in [(100,7000),(1000,2000), - (256,10000), - (512,10000), - (1024,1000), - (2048,1000), - (2048*2,500), - (2048*4,500), - ]: - print '%5s' % size, - sys.stdout.flush() - for x in [random([size]).astype(double), - random([size]).astype(cdouble)+random([size]).astype(cdouble)*1j - ]: - if size > 500: y = ifft(x) - else: y = direct_idft(x) - assert_array_almost_equal(ifft(x),y) - print '|%8.2f' % measure('ifft(x)',repeat), - sys.stdout.flush() - - assert_array_almost_equal(numpy_ifft(x),y) - print '|%8.2f' % measure('numpy_ifft(x)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - sys.stdout.flush() - class TestRfft(TestCase): def test_definition(self): @@ -264,35 +192,7 @@ y = fftpack.drfft(x) assert_array_almost_equal(y,y1) - @dec.bench - def test_random(self): - from numpy.fft import rfft as numpy_rfft - print - print 'Fast Fourier Transform (real data)' - print '==================================' - print ' size | scipy | numpy ' - print '----------------------------------' - for size,repeat in [(100,7000),(1000,2000), - (256,10000), - (512,10000), - (1024,1000), - (2048,1000), - (2048*2,500), - (2048*4,500), - ]: - print '%5s' % size, - sys.stdout.flush() - x = random([size]).astype(double) - print '|%8.2f' % measure('rfft(x)',repeat), - sys.stdout.flush() - - print '|%8.2f' % measure('numpy_rfft(x)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - sys.stdout.flush() - class TestIrfft(TestCase): def test_definition(self): @@ -330,46 +230,7 @@ assert_array_almost_equal (irfft(rfft(x)),x) assert_array_almost_equal (rfft(irfft(x)),x) - @dec.bench - def test_random(self): - from numpy.fft import irfft as numpy_irfft - print - print 'Inverse Fast Fourier Transform (real data)' - print '==================================' - print ' size | scipy | numpy ' - print '----------------------------------' - for size,repeat in [(100,7000),(1000,2000), - (256,10000), - (512,10000), - (1024,1000), - (2048,1000), - (2048*2,500), - (2048*4,500), - ]: - print '%5s' % size, - sys.stdout.flush() - - x = random([size]).astype(double) - x1 = zeros(size/2+1,dtype=cdouble) - x1[0] = x[0] - for i in range(1,size/2): - x1[i] = x[2*i-1] + 1j * x[2*i] - if not size%2: - x1[-1] = x[-1] - y = irfft(x) - - print '|%8.2f' % measure('irfft(x)',repeat), - sys.stdout.flush() - - assert_array_almost_equal(numpy_irfft(x1,size),y) - print '|%8.2f' % measure('numpy_irfft(x1,size)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - - sys.stdout.flush() - class TestFftn(TestCase): def test_definition(self): @@ -497,41 +358,7 @@ assert_array_almost_equal (y,swapaxes(\ fftn(swapaxes(large_x1,-1,-2)),-1,-2)) - @dec.bench - def test_random(self): - from numpy.fft import fftn as numpy_fftn - print - print ' Multi-dimensional Fast Fourier Transform' - print '===================================================' - print ' | real input | complex input ' - print '---------------------------------------------------' - print ' size | scipy | numpy | scipy | numpy ' - print '---------------------------------------------------' - for size,repeat in [((100,100),100),((1000,100),7), - ((256,256),10), - ((512,512),3), - ]: - print '%9s' % ('%sx%s'%size), - sys.stdout.flush() - for x in [random(size).astype(double), - random(size).astype(cdouble)+random(size).astype(cdouble)*1j - ]: - y = fftn(x) - #if size > 500: y = fftn(x) - #else: y = direct_dft(x) - assert_array_almost_equal(fftn(x),y) - print '|%8.2f' % measure('fftn(x)',repeat), - sys.stdout.flush() - - assert_array_almost_equal(numpy_fftn(x),y) - print '|%8.2f' % measure('numpy_fftn(x)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - - sys.stdout.flush() - class TestIfftn(TestCase): def test_definition(self): Modified: trunk/scipy/fftpack/tests/test_pseudo_diffs.py =================================================================== --- trunk/scipy/fftpack/tests/test_pseudo_diffs.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/fftpack/tests/test_pseudo_diffs.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -184,37 +184,7 @@ assert_array_almost_equal(diff(diff(f,k),-k),f) assert_array_almost_equal(diff(diff(f,-k),k),f) - @dec.bench - def test_random(self): - print - print 'Differentiation of periodic functions' - print '=====================================' - print ' size | convolve | naive' - print '-------------------------------------' - for size,repeat in [(100,1500),(1000,300), - (256,1500), - (512,1000), - (1024,500), - (2048,200), - (2048*2,100), - (2048*4,50), - ]: - print '%6s' % size, - sys.stdout.flush() - x = arange (size)*2*pi/size - if size<2000: - f = sin(x)*cos(4*x)+exp(sin(3*x)) - else: - f = sin(x)*cos(4*x) - assert_array_almost_equal(diff(f,1),direct_diff(f,1)) - assert_array_almost_equal(diff(f,2),direct_diff(f,2)) - print '| %9.2f' % measure('diff(f,3)',repeat), - sys.stdout.flush() - print '| %9.2f' % measure('direct_diff(f,3)',repeat), - sys.stdout.flush() - print ' (secs for %s calls)' % (repeat) - class TestTilbert(TestCase): def test_definition(self): @@ -248,34 +218,6 @@ assert_array_almost_equal(itilbert(tilbert(f,h),h),f) assert_array_almost_equal(tilbert(itilbert(f,h),h),f) - @dec.bench - def test_random(self): - print - print ' Tilbert transform of periodic functions' - print '=========================================' - print ' size | optimized | naive' - print '-----------------------------------------' - for size,repeat in [(100,1500),(1000,300), - (256,1500), - (512,1000), - (1024,500), - (2048,200), - (2048*2,100), - (2048*4,50), - ]: - print '%6s' % size, - sys.stdout.flush() - x = arange (size)*2*pi/size - if size<2000: - f = sin(x)*cos(4*x)+exp(sin(3*x)) - else: - f = sin(x)*cos(4*x) - assert_array_almost_equal(tilbert(f,1),direct_tilbert(f,1)) - print '| %9.2f' % measure('tilbert(f,1)',repeat), - sys.stdout.flush() - print '| %9.2f' % measure('direct_tilbert(f,1)',repeat), - sys.stdout.flush() - print ' (secs for %s calls)' % (repeat) class TestITilbert(TestCase): @@ -332,34 +274,6 @@ assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f) assert_array_almost_equal(hilbert(ihilbert(f)),f) - @dec.bench - def test_random(self): - print - print ' Hilbert transform of periodic functions' - print '=========================================' - print ' size | optimized | naive' - print '-----------------------------------------' - for size,repeat in [(100,1500),(1000,300), - (256,1500), - (512,1000), - (1024,500), - (2048,200), - (2048*2,100), - (2048*4,50), - ]: - print '%6s' % size, - sys.stdout.flush() - x = arange (size)*2*pi/size - if size<2000: - f = sin(x)*cos(4*x)+exp(sin(3*x)) - else: - f = sin(x)*cos(4*x) - assert_array_almost_equal(hilbert(f),direct_hilbert(f)) - print '| %9.2f' % measure('hilbert(f)',repeat), - sys.stdout.flush() - print '| %9.2f' % measure('direct_hilbert(f)',repeat), - sys.stdout.flush() - print ' (secs for %s calls)' % (repeat) class TestIHilbert(TestCase): @@ -398,38 +312,6 @@ assert_array_almost_equal(shift(sin(x),pi),-sin(x)) assert_array_almost_equal(shift(sin(x),pi/2),cos(x)) - @dec.bench - def test_random(self): - print - print ' Shifting periodic functions' - print '==============================' - print ' size | optimized | naive' - print '------------------------------' - for size,repeat in [(100,1500),(1000,300), - (256,1500), - (512,1000), - (1024,500), - (2048,200), - (2048*2,100), - (2048*4,50), - ]: - print '%6s' % size, - sys.stdout.flush() - x = arange (size)*2*pi/size - a = 1 - if size<2000: - f = sin(x)*cos(4*x)+exp(sin(3*x)) - sf = sin(x+a)*cos(4*(x+a))+exp(sin(3*(x+a))) - else: - f = sin(x)*cos(4*x) - sf = sin(x+a)*cos(4*(x+a)) - assert_array_almost_equal(direct_shift(f,1),sf) - assert_array_almost_equal(shift(f,1),sf) - print '| %9.2f' % measure('shift(f,a)',repeat), - sys.stdout.flush() - print '| %9.2f' % measure('direct_shift(f,a)',repeat), - sys.stdout.flush() - print ' (secs for %s calls)' % (repeat) if __name__ == "__main__": nose.run(argv=['', __file__]) Modified: trunk/scipy/linalg/__init__.py =================================================================== --- trunk/scipy/linalg/__init__.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/linalg/__init__.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -30,3 +30,4 @@ from scipy.testing.pkgtester import Tester test = Tester().test +bench = Tester().bench Added: trunk/scipy/linalg/benchmarks/bench_basic.py =================================================================== --- trunk/scipy/linalg/benchmarks/bench_basic.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/linalg/benchmarks/bench_basic.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -0,0 +1,130 @@ +import sys +import numpy +from numpy import arange, add, array, dot, zeros, identity, conjugate, transpose + +from scipy.testing import * + +from scipy.linalg import solve,inv,det,lstsq, toeplitz, hankel, tri, triu, \ + tril, pinv, pinv2, solve_banded + +def random(size): + return rand(*size) + +class TestSolve(TestCase): + + def bench_random(self): + import numpy.linalg as linalg + basic_solve = linalg.solve + print + print ' Solving system of linear equations' + print ' ==================================' + + print ' | contiguous | non-contiguous ' + print '----------------------------------------------' + print ' size | scipy | basic | scipy | basic ' + + for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: + repeat *= 2 + print '%5s' % size, + sys.stdout.flush() + + a = random([size,size]) + # larger diagonal ensures non-singularity: + for i in range(size): a[i,i] = 10*(.1+a[i,i]) + b = random([size]) + + print '| %6.2f ' % measure('solve(a,b)',repeat), + sys.stdout.flush() + + print '| %6.2f ' % measure('basic_solve(a,b)',repeat), + sys.stdout.flush() + + a = a[-1::-1,-1::-1] # turn into a non-contiguous array + assert not a.flags['CONTIGUOUS'] + + print '| %6.2f ' % measure('solve(a,b)',repeat), + sys.stdout.flush() + + print '| %6.2f ' % measure('basic_solve(a,b)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + +class TestInv(TestCase): + + def bench_random(self): + import numpy.linalg as linalg + basic_inv = linalg.inv + print + print ' Finding matrix inverse' + print ' ==================================' + print ' | contiguous | non-contiguous ' + print '----------------------------------------------' + print ' size | scipy | basic | scipy | basic' + + for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: + repeat *= 2 + print '%5s' % size, + sys.stdout.flush() + + a = random([size,size]) + # large diagonal ensures non-singularity: + for i in range(size): a[i,i] = 10*(.1+a[i,i]) + + print '| %6.2f ' % measure('inv(a)',repeat), + sys.stdout.flush() + + print '| %6.2f ' % measure('basic_inv(a)',repeat), + sys.stdout.flush() + + a = a[-1::-1,-1::-1] # turn into a non-contiguous array + assert not a.flags['CONTIGUOUS'] + + print '| %6.2f ' % measure('inv(a)',repeat), + sys.stdout.flush() + + print '| %6.2f ' % measure('basic_inv(a)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + + +class TestDet(TestCase): + + def bench_random(self): + import numpy.linalg as linalg + basic_det = linalg.det + print + print ' Finding matrix determinant' + print ' ==================================' + print ' | contiguous | non-contiguous ' + print '----------------------------------------------' + print ' size | scipy | basic | scipy | basic ' + + for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: + repeat *= 2 + print '%5s' % size, + sys.stdout.flush() + + a = random([size,size]) + + print '| %6.2f ' % measure('det(a)',repeat), + sys.stdout.flush() + + print '| %6.2f ' % measure('basic_det(a)',repeat), + sys.stdout.flush() + + a = a[-1::-1,-1::-1] # turn into a non-contiguous array + assert not a.flags['CONTIGUOUS'] + + print '| %6.2f ' % measure('det(a)',repeat), + sys.stdout.flush() + + print '| %6.2f ' % measure('basic_det(a)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + + +if __name__ == "__main__": + nose.run(argv=['', __file__]) Added: trunk/scipy/linalg/benchmarks/bench_decom.py =================================================================== --- trunk/scipy/linalg/benchmarks/bench_decom.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/linalg/benchmarks/bench_decom.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -0,0 +1,35 @@ +""" Benchmark functions for linalg.decomp module + +""" +import sys + +import numpy +from numpy import linalg +from scipy.linalg import eigvals + +from scipy.testing import * + +def random(size): + return rand(*size) + +def bench_random(): + Numeric_eigvals = linalg.eigvals + print + print ' Finding matrix eigenvalues' + print ' ==================================' + print ' | contiguous '#'| non-contiguous ' + print '----------------------------------------------' + print ' size | scipy '#'| core | scipy | core ' + + for size,repeat in [(20,150),(100,7),(200,2)]: + repeat *= 1 + print '%5s' % size, + sys.stdout.flush() + + a = random([size,size]) + + print '| %6.2f ' % measure('eigvals(a)',repeat), + sys.stdout.flush() + + print ' (secs for %s calls)' % (repeat) + Modified: trunk/scipy/linalg/tests/test_basic.py =================================================================== --- trunk/scipy/linalg/tests/test_basic.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/linalg/tests/test_basic.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -153,45 +153,7 @@ x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.dot(a,x),b) - @dec.bench - def test_bench_random(self): - import numpy.linalg as linalg - basic_solve = linalg.solve - print - print ' Solving system of linear equations' - print ' ==================================' - print ' | contiguous | non-contiguous ' - print '----------------------------------------------' - print ' size | scipy | basic | scipy | basic ' - - for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: - repeat *= 2 - print '%5s' % size, - sys.stdout.flush() - - a = random([size,size]) - # larger diagonal ensures non-singularity: - for i in range(size): a[i,i] = 10*(.1+a[i,i]) - b = random([size]) - - print '| %6.2f ' % measure('solve(a,b)',repeat), - sys.stdout.flush() - - print '| %6.2f ' % measure('basic_solve(a,b)',repeat), - sys.stdout.flush() - - a = a[-1::-1,-1::-1] # turn into a non-contiguous array - assert not a.flags['CONTIGUOUS'] - - print '| %6.2f ' % measure('solve(a,b)',repeat), - sys.stdout.flush() - - print '| %6.2f ' % measure('basic_solve(a,b)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - class TestInv(TestCase): def test_simple(self): @@ -227,44 +189,7 @@ assert_array_almost_equal(numpy.dot(a,a_inv), numpy.identity(n)) - @dec.bench - def test_bench_random(self): - import numpy.linalg as linalg - basic_inv = linalg.inv - print - print ' Finding matrix inverse' - print ' ==================================' - print ' | contiguous | non-contiguous ' - print '----------------------------------------------' - print ' size | scipy | basic | scipy | basic' - for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: - repeat *= 2 - print '%5s' % size, - sys.stdout.flush() - - a = random([size,size]) - # large diagonal ensures non-singularity: - for i in range(size): a[i,i] = 10*(.1+a[i,i]) - - print '| %6.2f ' % measure('inv(a)',repeat), - sys.stdout.flush() - - print '| %6.2f ' % measure('basic_inv(a)',repeat), - sys.stdout.flush() - - a = a[-1::-1,-1::-1] # turn into a non-contiguous array - assert not a.flags['CONTIGUOUS'] - - print '| %6.2f ' % measure('inv(a)',repeat), - sys.stdout.flush() - - print '| %6.2f ' % measure('basic_inv(a)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - - class TestDet(TestCase): def test_simple(self): @@ -297,42 +222,7 @@ d2 = basic_det(a) assert_almost_equal(d1,d2) - @dec.bench - def test_bench_random(self): - import numpy.linalg as linalg - basic_det = linalg.det - print - print ' Finding matrix determinant' - print ' ==================================' - print ' | contiguous | non-contiguous ' - print '----------------------------------------------' - print ' size | scipy | basic | scipy | basic ' - for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: - repeat *= 2 - print '%5s' % size, - sys.stdout.flush() - - a = random([size,size]) - - print '| %6.2f ' % measure('det(a)',repeat), - sys.stdout.flush() - - print '| %6.2f ' % measure('basic_det(a)',repeat), - sys.stdout.flush() - - a = a[-1::-1,-1::-1] # turn into a non-contiguous array - assert not a.flags['CONTIGUOUS'] - - print '| %6.2f ' % measure('det(a)',repeat), - sys.stdout.flush() - - print '| %6.2f ' % measure('basic_det(a)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - - def direct_lstsq(a,b,cmplx=0): at = transpose(a) if cmplx: Modified: trunk/scipy/linalg/tests/test_decomp.py =================================================================== --- trunk/scipy/linalg/tests/test_decomp.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/linalg/tests/test_decomp.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -17,7 +17,6 @@ import sys from scipy.testing import * - from scipy.linalg import eig,eigvals,lu,svd,svdvals,cholesky,qr, \ schur,rsf2csf, lu_solve,lu_factor,solve,diagsvd,hessenberg,rq, \ eig_banded, eigvals_banded @@ -27,7 +26,7 @@ from numpy import array, transpose, sometrue, diag, ones, linalg, \ argsort, zeros, arange, float32, complex64, dot, conj, identity, \ ravel, sqrt, iscomplex, shape, sort, sign, conjugate, sign, bmat, \ - asarray, matrix, isfinite + asarray, matrix, isfinite, all from numpy.random import rand @@ -59,29 +58,7 @@ (9+1j-sqrt(92+6j))/2] assert_array_almost_equal(w,exact_w) - @dec.bench - def test_bench_random(self): - import numpy.linalg as linalg - Numeric_eigvals = linalg.eigvals - print - print ' Finding matrix eigenvalues' - print ' ==================================' - print ' | contiguous '#'| non-contiguous ' - print '----------------------------------------------' - print ' size | scipy '#'| core | scipy | core ' - for size,repeat in [(20,150),(100,7),(200,2)]: - repeat *= 1 - print '%5s' % size, - sys.stdout.flush() - - a = random([size,size]) - - print '| %6.2f ' % measure('eigvals(a)',repeat), - sys.stdout.flush() - - print ' (secs for %s calls)' % (repeat) - class TestEig(TestCase): def test_simple(self): Modified: trunk/scipy/optimize/__init__.py =================================================================== --- trunk/scipy/optimize/__init__.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/optimize/__init__.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -18,3 +18,4 @@ __all__ = filter(lambda s:not s.startswith('_'),dir()) from scipy.testing.pkgtester import Tester test = Tester().test +bench = Tester().bench Added: trunk/scipy/optimize/_tstutils.py =================================================================== --- trunk/scipy/optimize/_tstutils.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/optimize/_tstutils.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -0,0 +1,47 @@ +''' Parameters used in test and benchmark methods ''' + +from random import random + +from scipy.optimize import zeros as cc + +def f1(x) : + return x*(x-1.) + +def f2(x) : + return x**2 - 1 + +def f3(x) : + return x*(x-1.)*(x-2.)*(x-3.) + +def f4(x) : + if x > 1 : return 1.0 + .1*x + if x < 1 : return -1.0 + .1*x + return 0 + +def f5(x) : + if x != 1 : return 1.0/(1. - x) + return 0 + +def f6(x) : + if x > 1 : return random() + elif x < 1 : return -random() + else : return 0 + +description = """ +f2 is a symmetric parabola, x**2 - 1 +f3 is a quartic polynomial with large hump in interval +f4 is step function with a discontinuity at 1 +f5 is a hyperbola with vertical asymptote at 1 +f6 has random values positive to left of 1, negative to right + +of course these are not real problems. They just test how the +'good' solvers behave in bad circumstances where bisection is +really the best. A good solver should not be much worse than +bisection in such circumstance, while being faster for smooth +monotone sorts of functions. +""" + +methods = [cc.bisect,cc.ridder,cc.brenth,cc.brentq] +mstrings = ['cc.bisect','cc.ridder','cc.brenth','cc.brentq'] +functions = [f2,f3,f4,f5,f6] +fstrings = ['f2','f3','f4','f5','f6'] Added: trunk/scipy/optimize/benchmarks/bench_zeros.py =================================================================== --- trunk/scipy/optimize/benchmarks/bench_zeros.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/optimize/benchmarks/bench_zeros.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -0,0 +1,35 @@ +from math import sqrt + +from scipy.testing import * + +from scipy.optimize import zeros as cc + +# Import testing parameters +from scipy.optimize._tstutils import methods, mstrings, functions, \ + fstrings, description + +class BenchZeros(TestCase): + def bench_run(self): + a = .5 + b = sqrt(3) + repeat = 2000 + + print description + + print 'TESTING SPEED\n' + print 'times in seconds for %d iterations \n'%repeat + for i in range(len(functions)) : + print 'function %s\n'%fstrings[i] + func = functions[i] + for j in range(len(methods)) : + meth = methods[j] + try: + t = measure("meth(func,a,b)",repeat) + except: + print '%s : failed'%mstrings[j] + else: + print '%s : %5.3f'%(mstrings[j],t) + print '\n\n' + +if __name__ == '__main__' : + nose.run(argv=['', __file__]) Modified: trunk/scipy/optimize/tests/test_zeros.py =================================================================== --- trunk/scipy/optimize/tests/test_zeros.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/optimize/tests/test_zeros.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -1,55 +1,15 @@ #!/usr/bin/env python +from math import sqrt from scipy.testing import * from scipy.optimize import zeros as cc -from math import sin,sqrt,log -from random import random +# Import testing parameters +from scipy.optimize._tstutils import methods, mstrings, functions, \ + fstrings, description -def f1(x) : - return x*(x-1.) - -def f2(x) : - return x**2 - 1 - -def f3(x) : - return x*(x-1.)*(x-2.)*(x-3.) - -def f4(x) : - if x > 1 : return 1.0 + .1*x - if x < 1 : return -1.0 + .1*x - return 0 - -def f5(x) : - if x != 1 : return 1.0/(1. - x) - return 0 - -def f6(x) : - if x > 1 : return random() - elif x < 1 : return -random() - else : return 0 - -description = """ -f2 is a symmetric parabola, x**2 - 1 -f3 is a quartic polynomial with large hump in interval -f4 is step function with a discontinuity at 1 -f5 is a hyperbola with vertical asymptote at 1 -f6 has random values positive to left of 1, negative to right - -of course these are not real problems. They just test how the -'good' solvers behave in bad circumstances where bisection is -really the best. A good solver should not be much worse than -bisection in such circumstance, while being faster for smooth -monotone sorts of functions. -""" - -methods = [cc.bisect,cc.ridder,cc.brenth,cc.brentq] -mstrings = ['cc.bisect','cc.ridder','cc.brenth','cc.brentq'] -functions = [f2,f3,f4,f5,f6] -fstrings = ['f2','f3','f4','f5','f6'] - class TestBasic(TestCase) : def run_check(self, method, name): a = .5 @@ -69,28 +29,6 @@ def test_brenth(self): self.run_check(cc.brenth, 'brenth') - @dec.bench - def test_run(self): - a = .5 - b = sqrt(3) - repeat = 2000 - print description - - print 'TESTING SPEED\n' - print 'times in seconds for %d iterations \n'%repeat - for i in range(len(functions)) : - print 'function %s\n'%fstrings[i] - func = functions[i] - for j in range(len(methods)) : - meth = methods[j] - try: - t = measure("meth(func,a,b)",repeat) - except: - print '%s : failed'%mstrings[j] - else: - print '%s : %5.3f'%(mstrings[j],t) - print '\n\n' - if __name__ == '__main__' : nose.run(argv=['', __file__]) Modified: trunk/scipy/sparse/__init__.py =================================================================== --- trunk/scipy/sparse/__init__.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/sparse/__init__.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -17,3 +17,4 @@ __all__ = filter(lambda s:not s.startswith('_'),dir()) from scipy.testing.pkgtester import Tester test = Tester().test +bench = Tester().bench Copied: trunk/scipy/sparse/benchmarks/bench_sparse.py (from rev 3848, trunk/scipy/sparse/benchmarks/test_sparse.py) =================================================================== --- trunk/scipy/sparse/benchmarks/test_sparse.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/sparse/benchmarks/bench_sparse.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -0,0 +1,281 @@ +"""general tests and simple benchmarks for the sparse module""" + +import numpy +from numpy import ones, array, asarray, empty + +import random +from scipy.testing import * + +from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ + coo_matrix, lil_matrix, dia_matrix, spidentity, spdiags, \ + spkron +from scipy.linsolve import splu + + +def random_sparse(m,n,nnz_per_row): + rows = numpy.arange(m).repeat(nnz_per_row) + cols = numpy.random.random_integers(low=0,high=n-1,size=nnz_per_row*m) + vals = numpy.random.random_sample(m*nnz_per_row) + return coo_matrix((vals,(rows,cols)),(m,n)).tocsr() + + +#TODO move this to a matrix gallery and add unittests +def poisson2d(N,dtype='d',format=None): + """ + Return a sparse matrix for the 2d poisson problem + with standard 5-point finite difference stencil on a + square N-by-N grid. + """ + if N == 1: + diags = asarray( [[4]],dtype=dtype) + return dia_matrix((diags,[0]), shape=(1,1)).asformat(format) + + offsets = array([0,-N,N,-1,1]) + + diags = empty((5,N**2),dtype=dtype) + + diags[0] = 4 #main diagonal + diags[1:] = -1 #all offdiagonals + + diags[3,N-1::N] = 0 #first lower diagonal + diags[4,N::N] = 0 #first upper diagonal + + return dia_matrix((diags,offsets),shape=(N**2,N**2)).asformat(format) + +import time +class TestSparseTools(TestCase): + """Simple benchmarks for sparse matrix module""" + + def bench_arithmetic(self): + matrices = [] + #matrices.append( ('A','Identity', spidentity(500**2,format='csr')) ) + matrices.append( ('A','Poisson5pt', poisson2d(500,format='csr')) ) + matrices.append( ('B','Poisson5pt^2', poisson2d(500,format='csr')**2) ) + + print + print ' Sparse Matrix Arithmetic' + print '====================================================================' + print ' var | name | shape | dtype | nnz ' + print '--------------------------------------------------------------------' + fmt = ' %1s | %14s | %20s | %9s | %8d ' + + for var,name,mat in matrices: + name = name.center(14) + shape = ("%s" % (mat.shape,)).center(20) + dtype = mat.dtype.name.center(9) + print fmt % (var,name,shape,dtype,mat.nnz) + + space = ' ' * 10 + print + print space+' Timings' + print space+'==========================================' + print space+' format | operation | time (msec) ' + print space+'------------------------------------------' + fmt = space+' %3s | %17s | %7.1f ' + + for format in ['csr']: + vars = dict( [(var,mat.asformat(format)) for (var,name,mat) in matrices ] ) + for X,Y in [ ('A','A'),('A','B'),('B','A'),('B','B') ]: + x,y = vars[X],vars[Y] + for op in ['__add__','__sub__','multiply','__div__','__mul__']: + fn = getattr(x,op) + fn(y) #warmup + + start = time.clock() + iter = 0 + while iter < 5 or time.clock() < start + 1: + fn(y) + iter += 1 + end = time.clock() + + msec_per_it = 1000*(end - start)/float(iter) + operation = (X + '.' + op + '(' + Y + ')').center(17) + print fmt % (format,operation,msec_per_it) + + + def bench_sort(self): + """sort CSR column indices""" + matrices = [] + matrices.append( ('Rand10', 1e4, 10) ) + matrices.append( ('Rand25', 1e4, 25) ) + matrices.append( ('Rand50', 1e4, 50) ) + matrices.append( ('Rand100', 1e4, 100) ) + matrices.append( ('Rand200', 1e4, 200) ) + + print + print ' Sparse Matrix Index Sorting' + print '=====================================================================' + print ' type | name | shape | nnz | time (msec) ' + print '---------------------------------------------------------------------' + fmt = ' %3s | %12s | %20s | %8d | %6.2f ' + + for name,N,K in matrices: + N = int(N) + A = random_sparse(N,N,K) + + start = time.clock() + iter = 0 + while iter < 5 and time.clock() - start < 1: + A._has_sorted_indices = False + A.sort_indices() + iter += 1 + end = time.clock() + + name = name.center(12) + shape = ("%s" % (A.shape,)).center(20) + + print fmt % (A.format,name,shape,A.nnz,1e3*(end-start)/float(iter) ) + + def bench_matvec(self): + matrices = [] + matrices.append(('Identity', spidentity(10**4,format='dia'))) + matrices.append(('Identity', spidentity(10**4,format='csr'))) + matrices.append(('Poisson5pt', poisson2d(300,format='dia'))) + matrices.append(('Poisson5pt', poisson2d(300,format='csr'))) + matrices.append(('Poisson5pt', poisson2d(300,format='bsr'))) + + A = spkron(poisson2d(150),ones((2,2))).tobsr(blocksize=(2,2)) + matrices.append( ('Block2x2', A.tocsr()) ) + matrices.append( ('Block2x2', A) ) + + A = spkron(poisson2d(100),ones((3,3))).tobsr(blocksize=(3,3)) + matrices.append( ('Block3x3', A.tocsr()) ) + matrices.append( ('Block3x3', A) ) + + print + print ' Sparse Matrix Vector Product' + print '==================================================================' + print ' type | name | shape | nnz | MFLOPs ' + print '------------------------------------------------------------------' + fmt = ' %3s | %12s | %20s | %8d | %6.1f ' + + for name,A in matrices: + x = ones(A.shape[1],dtype=A.dtype) + + y = A*x #warmup + + start = time.clock() + iter = 0 + while iter < 5 or time.clock() < start + 1: + try: + #avoid creating y if possible + A.matvec(x,y) + except: + y = A*x + iter += 1 + end = time.clock() + + del y + + name = name.center(12) + shape = ("%s" % (A.shape,)).center(20) + MFLOPs = (2*A.nnz*iter/(end-start))/float(1e6) + + print fmt % (A.format,name,shape,A.nnz,MFLOPs) + + def bench_construction(self): + """build matrices by inserting single values""" + matrices = [] + matrices.append( ('Empty',csr_matrix((10000,10000))) ) + matrices.append( ('Identity',spidentity(10000)) ) + matrices.append( ('Poisson5pt', poisson2d(100)) ) + + print + print ' Sparse Matrix Construction' + print '====================================================================' + print ' type | name | shape | nnz | time (sec) ' + print '--------------------------------------------------------------------' + fmt = ' %3s | %12s | %20s | %8d | %6.4f ' + + for name,A in matrices: + A = A.tocoo() + + for format in ['lil','dok']: + + start = time.clock() + + iter = 0 + while time.clock() < start + 0.5: + T = eval(format + '_matrix')(A.shape) + for i,j,v in zip(A.row,A.col,A.data): + T[i,j] = v + iter += 1 + end = time.clock() + + del T + name = name.center(12) + shape = ("%s" % (A.shape,)).center(20) + + print fmt % (format,name,shape,A.nnz,(end-start)/float(iter)) + + def bench_conversion(self): + A = poisson2d(100) + + formats = ['csr','csc','coo','lil','dok'] + + print + print ' Sparse Matrix Conversion' + print '==========================================================' + print ' format | tocsr() | tocsc() | tocoo() | tolil() | todok() ' + print '----------------------------------------------------------' + + for fromfmt in formats: + base = getattr(A,'to' + fromfmt)() + + times = [] + + for tofmt in formats: + try: + fn = getattr(base,'to' + tofmt) + except: + times.append(None) + else: + x = fn() #warmup + start = time.clock() + iter = 0 + while time.clock() < start + 0.2: + x = fn() + iter += 1 + end = time.clock() + del x + times.append( (end - start)/float(iter)) + + output = " %3s " % fromfmt + for t in times: + if t is None: + output += '| n/a ' + else: + output += '| %5.1fms ' % (1000*t) + print output + + +class TestLarge(TestCase): + def bench_large(self): + # Create a 100x100 matrix with 100 non-zero elements + # and play around with it + #TODO move this out of Common since it doesn't use spmatrix + random.seed(0) + A = dok_matrix((100,100)) + for k in range(100): + i = random.randrange(100) + j = random.randrange(100) + A[i,j] = 1. + csr = A.tocsr() + csc = A.tocsc() + csc2 = csr.tocsc() + coo = A.tocoo() + csr2 = coo.tocsr() + assert_array_equal(A.transpose().todense(), csr.transpose().todense()) + assert_array_equal(csc.todense(), csr.todense()) + assert_array_equal(csr.todense(), csr2.todense()) + assert_array_equal(csr2.todense().transpose(), coo.transpose().todense()) + assert_array_equal(csr2.todense(), csc2.todense()) + csr_plus_csc = csr + csc + csc_plus_csr = csc + csr + assert_array_equal(csr_plus_csc.todense(), (2*A).todense()) + assert_array_equal(csr_plus_csc.todense(), csc_plus_csr.todense()) + + +if __name__ == "__main__": + nose.run(argv=['', __file__]) + Deleted: trunk/scipy/sparse/benchmarks/test_sparse.py =================================================================== --- trunk/scipy/sparse/benchmarks/test_sparse.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/sparse/benchmarks/test_sparse.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -1,286 +0,0 @@ -"""general tests and simple benchmarks for the sparse module""" - -import numpy -from numpy import ones, array, asarray, empty - -import random -from scipy.testing import * - -from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ - coo_matrix, lil_matrix, dia_matrix, spidentity, spdiags, \ - spkron -from scipy.linsolve import splu - - -def random_sparse(m,n,nnz_per_row): - rows = numpy.arange(m).repeat(nnz_per_row) - cols = numpy.random.random_integers(low=0,high=n-1,size=nnz_per_row*m) - vals = numpy.random.random_sample(m*nnz_per_row) - return coo_matrix((vals,(rows,cols)),(m,n)).tocsr() - - -#TODO move this to a matrix gallery and add unittests -def poisson2d(N,dtype='d',format=None): - """ - Return a sparse matrix for the 2d poisson problem - with standard 5-point finite difference stencil on a - square N-by-N grid. - """ - if N == 1: - diags = asarray( [[4]],dtype=dtype) - return dia_matrix((diags,[0]), shape=(1,1)).asformat(format) - - offsets = array([0,-N,N,-1,1]) - - diags = empty((5,N**2),dtype=dtype) - - diags[0] = 4 #main diagonal - diags[1:] = -1 #all offdiagonals - - diags[3,N-1::N] = 0 #first lower diagonal - diags[4,N::N] = 0 #first upper diagonal - - return dia_matrix((diags,offsets),shape=(N**2,N**2)).asformat(format) - -import time -class TestSparseTools(TestCase): - """Simple benchmarks for sparse matrix module""" - - @dec.bench - def test_arithmetic(self): - matrices = [] - #matrices.append( ('A','Identity', spidentity(500**2,format='csr')) ) - matrices.append( ('A','Poisson5pt', poisson2d(500,format='csr')) ) - matrices.append( ('B','Poisson5pt^2', poisson2d(500,format='csr')**2) ) - - print - print ' Sparse Matrix Arithmetic' - print '====================================================================' - print ' var | name | shape | dtype | nnz ' - print '--------------------------------------------------------------------' - fmt = ' %1s | %14s | %20s | %9s | %8d ' - - for var,name,mat in matrices: - name = name.center(14) - shape = ("%s" % (mat.shape,)).center(20) - dtype = mat.dtype.name.center(9) - print fmt % (var,name,shape,dtype,mat.nnz) - - space = ' ' * 10 - print - print space+' Timings' - print space+'==========================================' - print space+' format | operation | time (msec) ' - print space+'------------------------------------------' - fmt = space+' %3s | %17s | %7.1f ' - - for format in ['csr']: - vars = dict( [(var,mat.asformat(format)) for (var,name,mat) in matrices ] ) - for X,Y in [ ('A','A'),('A','B'),('B','A'),('B','B') ]: - x,y = vars[X],vars[Y] - for op in ['__add__','__sub__','multiply','__div__','__mul__']: - fn = getattr(x,op) - fn(y) #warmup - - start = time.clock() - iter = 0 - while iter < 5 or time.clock() < start + 1: - fn(y) - iter += 1 - end = time.clock() - - msec_per_it = 1000*(end - start)/float(iter) - operation = (X + '.' + op + '(' + Y + ')').center(17) - print fmt % (format,operation,msec_per_it) - - - @dec.bench - def test_sort(self): - """sort CSR column indices""" - matrices = [] - matrices.append( ('Rand10', 1e4, 10) ) - matrices.append( ('Rand25', 1e4, 25) ) - matrices.append( ('Rand50', 1e4, 50) ) - matrices.append( ('Rand100', 1e4, 100) ) - matrices.append( ('Rand200', 1e4, 200) ) - - print - print ' Sparse Matrix Index Sorting' - print '=====================================================================' - print ' type | name | shape | nnz | time (msec) ' - print '---------------------------------------------------------------------' - fmt = ' %3s | %12s | %20s | %8d | %6.2f ' - - for name,N,K in matrices: - N = int(N) - A = random_sparse(N,N,K) - - start = time.clock() - iter = 0 - while iter < 5 and time.clock() - start < 1: - A._has_sorted_indices = False - A.sort_indices() - iter += 1 - end = time.clock() - - name = name.center(12) - shape = ("%s" % (A.shape,)).center(20) - - print fmt % (A.format,name,shape,A.nnz,1e3*(end-start)/float(iter) ) - - @dec.bench - def test_matvec(self): - matrices = [] - matrices.append(('Identity', spidentity(10**4,format='dia'))) - matrices.append(('Identity', spidentity(10**4,format='csr'))) - matrices.append(('Poisson5pt', poisson2d(300,format='dia'))) - matrices.append(('Poisson5pt', poisson2d(300,format='csr'))) - matrices.append(('Poisson5pt', poisson2d(300,format='bsr'))) - - A = spkron(poisson2d(150),ones((2,2))).tobsr(blocksize=(2,2)) - matrices.append( ('Block2x2', A.tocsr()) ) - matrices.append( ('Block2x2', A) ) - - A = spkron(poisson2d(100),ones((3,3))).tobsr(blocksize=(3,3)) - matrices.append( ('Block3x3', A.tocsr()) ) - matrices.append( ('Block3x3', A) ) - - print - print ' Sparse Matrix Vector Product' - print '==================================================================' - print ' type | name | shape | nnz | MFLOPs ' - print '------------------------------------------------------------------' - fmt = ' %3s | %12s | %20s | %8d | %6.1f ' - - for name,A in matrices: - x = ones(A.shape[1],dtype=A.dtype) - - y = A*x #warmup - - start = time.clock() - iter = 0 - while iter < 5 or time.clock() < start + 1: - try: - #avoid creating y if possible - A.matvec(x,y) - except: - y = A*x - iter += 1 - end = time.clock() - - del y - - name = name.center(12) - shape = ("%s" % (A.shape,)).center(20) - MFLOPs = (2*A.nnz*iter/(end-start))/float(1e6) - - print fmt % (A.format,name,shape,A.nnz,MFLOPs) - - @dec.bench - def test_construction(self): - """build matrices by inserting single values""" - matrices = [] - matrices.append( ('Empty',csr_matrix((10000,10000))) ) - matrices.append( ('Identity',spidentity(10000)) ) - matrices.append( ('Poisson5pt', poisson2d(100)) ) - - print - print ' Sparse Matrix Construction' - print '====================================================================' - print ' type | name | shape | nnz | time (sec) ' - print '--------------------------------------------------------------------' - fmt = ' %3s | %12s | %20s | %8d | %6.4f ' - - for name,A in matrices: - A = A.tocoo() - - for format in ['lil','dok']: - - start = time.clock() - - iter = 0 - while time.clock() < start + 0.5: - T = eval(format + '_matrix')(A.shape) - for i,j,v in zip(A.row,A.col,A.data): - T[i,j] = v - iter += 1 - end = time.clock() - - del T - name = name.center(12) - shape = ("%s" % (A.shape,)).center(20) - - print fmt % (format,name,shape,A.nnz,(end-start)/float(iter)) - - @dec.bench - def test_conversion(self): - A = poisson2d(100) - - formats = ['csr','csc','coo','lil','dok'] - - print - print ' Sparse Matrix Conversion' - print '==========================================================' - print ' format | tocsr() | tocsc() | tocoo() | tolil() | todok() ' - print '----------------------------------------------------------' - - for fromfmt in formats: - base = getattr(A,'to' + fromfmt)() - - times = [] - - for tofmt in formats: - try: - fn = getattr(base,'to' + tofmt) - except: - times.append(None) - else: - x = fn() #warmup - start = time.clock() - iter = 0 - while time.clock() < start + 0.2: - x = fn() - iter += 1 - end = time.clock() - del x - times.append( (end - start)/float(iter)) - - output = " %3s " % fromfmt - for t in times: - if t is None: - output += '| n/a ' - else: - output += '| %5.1fms ' % (1000*t) - print output - - -class TestLarge(TestCase): - def test_large(self): - # Create a 100x100 matrix with 100 non-zero elements - # and play around with it - #TODO move this out of Common since it doesn't use spmatrix - random.seed(0) - A = dok_matrix((100,100)) - for k in range(100): - i = random.randrange(100) - j = random.randrange(100) - A[i,j] = 1. - csr = A.tocsr() - csc = A.tocsc() - csc2 = csr.tocsc() - coo = A.tocoo() - csr2 = coo.tocsr() - assert_array_equal(A.transpose().todense(), csr.transpose().todense()) - assert_array_equal(csc.todense(), csr.todense()) - assert_array_equal(csr.todense(), csr2.todense()) - assert_array_equal(csr2.todense().transpose(), coo.transpose().todense()) - assert_array_equal(csr2.todense(), csc2.todense()) - csr_plus_csc = csr + csc - csc_plus_csr = csc + csr - assert_array_equal(csr_plus_csc.todense(), (2*A).todense()) - assert_array_equal(csr_plus_csc.todense(), csc_plus_csr.todense()) - - -if __name__ == "__main__": - unittest.main() - Modified: trunk/scipy/stsci/image/lib/_image.py =================================================================== --- trunk/scipy/stsci/image/lib/_image.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/stsci/image/lib/_image.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -1,6 +1,6 @@ import numpy as num -import convolve -import convolve._correlate as _correlate +import scipy.stsci.convolve +import scipy.stsci.convolve._correlate as _correlate MLab=num def _translate(a, dx, dy, output=None, mode="nearest", cval=0.0): Modified: trunk/scipy/testing/decorators.py =================================================================== --- trunk/scipy/testing/decorators.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/testing/decorators.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -11,15 +11,6 @@ t.slow = True return t -def bench(t): - ''' Labels a test as a benchmark. - - Benchmark tests are often slow, and intended to test timings - between different algorithms rather than validity of the result. ''' - - t.bench = True - return t - def willfail(t): ''' Labels test as known failure Modified: trunk/scipy/testing/nosetester.py =================================================================== --- trunk/scipy/testing/nosetester.py 2008-01-17 15:41:44 UTC (rev 3848) +++ trunk/scipy/testing/nosetester.py 2008-01-18 23:48:52 UTC (rev 3849) @@ -1,10 +1,11 @@ ''' Nose test running -Implements .test functions for modules. +Implements test and bench functions for modules. ''' import os import sys +import re import nose @@ -30,6 +31,7 @@ returning this class if nose is present, and a null class otherwise. """ + def __init__(self, package=None): ''' Test class init @@ -39,7 +41,6 @@ If string, gives full path to package If None, extract calling module path Default is None - ''' if package is None: f = sys._getframe(1) @@ -50,45 +51,80 @@ package = os.path.dirname(package.__file__) self.package_path = package - def test(self, label='fast', verbose=1, doctests=False, extra_argv=None): - ''' Module testing function + def _add_doc(testtype): + ''' Decorator to add docstring to functions using test labels Parameters ---------- + testtype : string + Type of test for function docstring + ''' + def docit(func): + test_header = \ + '''Parameters + ---------- label : {'fast', 'full', '', attribute identifer} - Identifies tests to run. This can be a string to pass to + Identifies %(testtype)s to run. This can be a string to pass to the nosetests executable with the'-A' option, or one of several special values. Special values are: 'fast' - the default - which corresponds to nosetests -A option of - 'not slow and not bench and not willfail'. - 'full' - fast (as above) and slow tests as in - nosetests -A option of 'not bench and not willfail'. - None or '' - run all tests and benchmarks + 'not slow and not willfail'. + 'full' - fast (as above) and slow %(testtype)s as in + nosetests -A option of 'not willfail'. + None or '' - run all %(testtype)ss attribute_identifier - string passed directly to nosetests as '-A' verbose : integer verbosity value for test outputs, 1-10 - doctests : boolean - If True, run doctests in module, default False extra_argv : list - List with any extra args to pass to nosetests + List with any extra args to pass to nosetests''' \ + % {'testtype': testtype} + func.__doc__ = func.__doc__ % { + 'test_header': test_header} + return func + return docit + + @_add_doc('(testtype)') + def _test_argv(self, label, verbose, extra_argv): + ''' Generate argv for nosetest command + + %(test_header)s ''' - argv = ['scipy module test', self.package_path, '-s'] + argv = [__file__, self.package_path, '-s'] if label: if not isinstance(label, basestring): - raise TypeError, 'Test selection label should be a string' + raise TypeError, 'Selection label should be a string' if label == 'fast': - label = 'not slow and not bench and not willfail' + label = 'not slow and not willfail' elif label == 'full': - label = 'not bench and not willfail' + label = 'not willfail' argv += ['-A', label] argv += ['--verbosity', str(verbose)] + if extra_argv: + argv += extra_argv + return argv + + @_add_doc('test') + def test(self, label='fast', verbose=1, extra_argv=None, doctests=False): + ''' Run tests for module using nose + + %(test_header)s + doctests : boolean + If True, run doctests in module, default False + ''' + argv = self._test_argv(label, verbose, extra_argv) if doctests: argv+=['--with-doctest'] - if extra_argv: - argv+= extra_argv nose.run(argv=argv) + + @_add_doc('benchmark') + def bench(self, label='fast', verbose=1, extra_argv=None): + ''' Run benchmarks for module using nose + %(test_header)s''' + argv = self._test_argv(label, verbose, extra_argv) + argv += ['--match', r'(?:^|[\\b_\\.%s-])[Bb]ench' % os.sep] + nose.run(argv=argv) From scipy-svn at scipy.org Fri Jan 18 19:54:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 18 Jan 2008 18:54:53 -0600 (CST) Subject: [Scipy-svn] r3850 - trunk/scipy/misc/tests Message-ID: <20080119005453.E4BF939C0BA@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-18 18:54:50 -0600 (Fri, 18 Jan 2008) New Revision: 3850 Modified: trunk/scipy/misc/tests/test_pilutil.py Log: Fix import error for PIL tests when PIL not present Modified: trunk/scipy/misc/tests/test_pilutil.py =================================================================== --- trunk/scipy/misc/tests/test_pilutil.py 2008-01-18 23:48:52 UTC (rev 3849) +++ trunk/scipy/misc/tests/test_pilutil.py 2008-01-19 00:54:50 UTC (rev 3850) @@ -10,10 +10,9 @@ _have_PIL = False else: _have_PIL = True + import scipy.misc.pilutil as pilutil TestCase.__test__ = _have_PIL -import scipy.misc.pilutil as pilutil - datapath = os.path.dirname(__file__) class TestPILUtil(TestCase): From scipy-svn at scipy.org Sat Jan 19 10:39:56 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 19 Jan 2008 09:39:56 -0600 (CST) Subject: [Scipy-svn] r3851 - trunk/scipy/testing Message-ID: <20080119153956.03BA2C7C152@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-19 09:39:51 -0600 (Sat, 19 Jan 2008) New Revision: 3851 Modified: trunk/scipy/testing/nulltester.py Log: Fix bench error on scipy import when nose is not installed Modified: trunk/scipy/testing/nulltester.py =================================================================== --- trunk/scipy/testing/nulltester.py 2008-01-19 00:54:50 UTC (rev 3850) +++ trunk/scipy/testing/nulltester.py 2008-01-19 15:39:51 UTC (rev 3851) @@ -13,4 +13,6 @@ pass def test(self, labels=None, *args, **kwargs): raise ImportError, 'Need nose for tests - see %s' % nose_url + def bench(self, labels=None, *args, **kwargs): + raise ImportError, 'Need nose for benchmarks - see %s' % nose_url From scipy-svn at scipy.org Sat Jan 19 14:43:07 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 19 Jan 2008 13:43:07 -0600 (CST) Subject: [Scipy-svn] r3852 - in trunk/scipy/sandbox/multigrid: . examples tests Message-ID: <20080119194307.E707739C010@new.scipy.org> Author: wnbell Date: 2008-01-19 13:43:04 -0600 (Sat, 19 Jan 2008) New Revision: 3852 Modified: trunk/scipy/sandbox/multigrid/adaptive.py trunk/scipy/sandbox/multigrid/examples/adaptive.py trunk/scipy/sandbox/multigrid/sa.py trunk/scipy/sandbox/multigrid/tests/test_adaptive.py trunk/scipy/sandbox/multigrid/utils.py Log: updated aSA Modified: trunk/scipy/sandbox/multigrid/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-19 15:39:51 UTC (rev 3851) +++ trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-19 19:43:04 UTC (rev 3852) @@ -6,7 +6,8 @@ from numpy import sqrt, ravel, diff, zeros, zeros_like, inner, concatenate, \ asarray, hstack, ascontiguousarray, isinf, dot from numpy.random import randn, rand -from scipy.sparse import csr_matrix,coo_matrix +from scipy.linalg import norm +from scipy.sparse import csr_matrix, coo_matrix, bsr_matrix from relaxation import gauss_seidel from multilevel import multilevel_solver @@ -40,7 +41,7 @@ for AggOp in AggOps: P,B = sa_fit_candidates(AggOp,B) I = sa_smoothed_prolongator(A,P) - A = I.T.tocsr() * A * I + A = I.T.asformat(I.format) * A * I As.append(A) Ts.append(P) Ps.append(I) @@ -99,18 +100,22 @@ """ if A.shape[0] <= max_coarse: - raise ValueError,'small matrices not handled yet' + return multilevel_solver( [A], [] ) #first candidate x,AggOps = asa_initial_setup_stage(A, max_levels = max_levels, \ max_coarse = max_coarse, mu = mu, epsilon = epsilon, \ aggregation = aggregation ) + #TODO make sa_fit_candidates work for small Bs + x /= norm(x) + #create SA using x here As,Ps,Ts,Bs = sa_hierarchy(A,x,AggOps) for i in range(max_candidates - 1): x = asa_general_setup_stage(As,Ps,Ts,Bs,AggOps,mu=mu) + x /= norm(x) B = hstack((Bs[0],x)) As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) @@ -122,7 +127,7 @@ for i in range(max_candidates): B = B[:,1:] As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) - x = asa_general_setup_stage(As,Ps,Ts,Bs,AggOps,mu=mu) + x = asa_general_setup_stage(As,Ps,Ts,Bs,AggOps,mu) B = hstack((B,x)) As,Ps,Ts,Bs = sa_hierarchy(A,B,AggOps) @@ -159,7 +164,7 @@ W_l = aggregation[len(AggOps)] P_l,x = sa_fit_candidates(W_l,x) #step 4c I_l = sa_smoothed_prolongator(A_l,P_l) #step 4d - A_l = I_l.T.tocsr() * A_l * I_l #step 4e + A_l = I_l.T.asformat(I_l.format) * A_l * I_l #step 4e AggOps.append(W_l) Ps.append(I_l) @@ -189,7 +194,7 @@ def asa_general_setup_stage(As, Ps, Ts, Bs, AggOps, mu): A = As[0] - x = randn(A.shape[0],1) + x = rand(A.shape[0],1) b = zeros_like(x) x = multilevel_solver(As,Ps).solve(b, x0=x, tol=1e-10, maxiter=mu) @@ -204,15 +209,20 @@ K = P.blocksize[0] bnnz = P.indptr[-1] data = zeros( (bnnz, K+1, K), dtype=P.dtype ) - data[:,:-1,:-1] = P.data + data[:,:-1,:] = P.data return bsr_matrix( (data, P.indices, P.indptr), shape=( (K+1)*(M/K), N) ) for i in range(len(As) - 2): - B = zeros( (x.shape[0], Bs[i+1].shape[1] + 1), dtype=x.dtype) - T,R = sa_fit_candidates(AggOp,B) + B_old = Bs[i] + B = zeros( (x.shape[0], B_old.shape[1] + 1), dtype=x.dtype) + B[:B_old.shape[0],:B_old.shape[1]] = B_old + B[:,-1] = x.reshape(-1) + + T,R = sa_fit_candidates(AggOps[i],B) + P = sa_smoothed_prolongator(A,T) - A = P.T.tocsr() * A * P + A = P.T.asformat(P.format) * A * P temp_Ps.append(P) temp_As.append(A) @@ -242,7 +252,7 @@ # T,R = augment_candidates(AggOps[i], Ts[i], Bs[i+1], x) # # P = sa_smoothed_prolongator(A,T) -# A = P.T.tocsr() * A * P +# A = P.T.asformat(P.format) * A * P # # new_As.append(A) # new_Ps.append(P) Modified: trunk/scipy/sandbox/multigrid/examples/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-19 15:39:51 UTC (rev 3851) +++ trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-19 19:43:04 UTC (rev 3852) @@ -3,21 +3,25 @@ from scipy.sandbox.multigrid.utils import diag_sparse from scipy.sandbox.multigrid.gallery import poisson, linear_elasticity from scipy.sandbox.multigrid.adaptive import adaptive_sa_solver +from scipy.sandbox.multigrid import smoothed_aggregation_solver -#A,B = linear_elasticity( (100,100) ) +A,B = linear_elasticity( (20,20) ) -A = poisson( (200,200), format='csr' ) +#A = poisson( (200,200), format='csr' ) #A = poisson( (200,200), spacing=(1,1e-2) ) #anisotropic -D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() -A = D * A * D +#D = diag_sparse(1.0/sqrt(10**(12*rand(A.shape[0])-6))).tocsr() +#A = D * A * D from time import clock; start = clock() -asa = adaptive_sa_solver(A, max_levels=2, max_candidates=1, mu=10) +#asa = smoothed_aggregation_solver(A,B,max_levels=2) +#Bs = [B] +asa,Bs = adaptive_sa_solver(A, max_levels=2, max_coarse=10, max_candidates=3, mu=15) + print "Adaptive Solver Construction: %s seconds" % (clock() - start); del start random.seed(0) #make tests repeatable @@ -27,14 +31,14 @@ print "solving" -if True: - x_sol,residuals = asa.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) +if False: + x_sol,residuals = asa.solve(b,x0=x,maxiter=20,tol=1e-10,return_residuals=True) else: residuals = [] def add_resid(x): residuals.append(linalg.norm(b - A*x)) A.psolve = asa.psolve - x_sol = linalg.cg(A,b,x0=x,maxiter=30,tol=1e-12,callback=add_resid)[0] + x_sol = linalg.cg(A,b,x0=x,maxiter=30,tol=1e-10,callback=add_resid)[0] residuals = array(residuals)/residuals[0] @@ -69,10 +73,10 @@ show() -#for c in asa.Bs[0].T: -# plot2d(c) -# #plot2d_arrows(c) -# print "candidate Rayleigh quotient",dot(c,A*c)/dot(c,c) +for c in Bs[0].T: + #plot2d(c) + plot2d_arrows(c) + print "candidate Rayleigh quotient",dot(c,A*c)/dot(c,c) #plot2d(x_sol) Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-19 15:39:51 UTC (rev 3851) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-19 19:43:04 UTC (rev 3852) @@ -103,6 +103,13 @@ if candidates.dtype != 'float32': candidates = asarray(candidates,dtype='float64') + if len(candidates.shape) != 2: + raise ValueError,'expected rank 2 array for argument B' + + if candidates.shape[0] % AggOp.shape[0] != 0: + raise ValueError,'dimensions of AggOp %s and B %s are incompatible' % (AggOp.shape, B.shape) + + K = candidates.shape[1] # number of near-nullspace candidates blocksize = candidates.shape[0] / AggOp.shape[0] @@ -167,8 +174,11 @@ A_filtered = sa_filtered_matrix(A,epsilon) #use filtered matrix for anisotropic problems # TODO use scale_rows() - D_inv = diag_sparse(1.0/diag_sparse(A_filtered)) - D_inv_A = D_inv * A_filtered + D = diag_sparse(A_filtered) + D_inv = 1.0 / D + D_inv[D == 0] = 0 + + D_inv_A = diag_sparse(D_inv) * A_filtered D_inv_A *= omega/approximate_spectral_radius(D_inv_A) # smooth tentative prolongator T Modified: trunk/scipy/sandbox/multigrid/tests/test_adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-19 15:39:51 UTC (rev 3851) +++ trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-19 19:43:04 UTC (rev 3852) @@ -1,18 +1,56 @@ from scipy.testing import * +from numpy import arange, ones, zeros, array, eye, vstack, diff +from scipy import rand from scipy.sparse import csr_matrix -from numpy import arange,ones,zeros,array,eye,vstack,diff from scipy.sandbox.multigrid.sa import sa_fit_candidates +from scipy.sandbox.multigrid import smoothed_aggregation_solver #from scipy.sandbox.multigrid.adaptive import augment_candidates +from scipy.sandbox.multigrid.gallery import * +from scipy.sandbox.multigrid.adaptive import * class TestAdaptiveSA(TestCase): def setUp(self): - pass + from numpy.random import seed + seed(0) + def test_poisson(self): + A = poisson( (100,100), format='csr' ) + + asa = adaptive_sa_solver(A, max_candidates = 1) + sa = smoothed_aggregation_solver(A, B = ones((A.shape[0],1)) ) + + b = rand(A.shape[0]) + + sol0,residuals0 = asa.solve(b, maxiter=20, tol=1e-10, return_residuals=True) + sol1,residuals1 = sa.solve(b, maxiter=20, tol=1e-10, return_residuals=True) + + conv_asa = (residuals0[-1]/residuals0[0])**(1.0/len(residuals0)) + conv_sa = (residuals1[-1]/residuals1[0])**(1.0/len(residuals1)) + + assert( conv_asa < 1.1 * conv_sa ) #aSA shouldn't be any worse than SA + +# def test_elasticity(self): +# A,B = linear_elasticity( (100,100), format='bsr' ) +# +# asa = adaptive_sa_solver(A, max_candidates = 3) +# sa = smoothed_aggregation_solver(A, B=B ) +# +# b = rand(A.shape[0]) +# +# sol0,residuals0 = asa.solve(b, maxiter=20, tol=1e-10, return_residuals=True) +# sol1,residuals1 = sa.solve(b, maxiter=20, tol=1e-10, return_residuals=True) +# +# conv_asa = (residuals0[-1]/residuals0[0])**(1.0/len(residuals0)) +# conv_sa = (residuals1[-1]/residuals1[0])**(1.0/len(residuals1)) +# +# print "ASA convergence",conv_asa +# assert( conv_asa < 1.1 * conv_sa ) #aSA shouldn't be any worse than SA + #class TestAugmentCandidates(TestCase): # def setUp(self): # self.cases = [] Modified: trunk/scipy/sandbox/multigrid/utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/utils.py 2008-01-19 15:39:51 UTC (rev 3851) +++ trunk/scipy/sandbox/multigrid/utils.py 2008-01-19 19:43:04 UTC (rev 3852) @@ -46,6 +46,8 @@ if A.shape[0] != A.shape[1]: raise ValueError,'expected square matrix' + maxiter = min(A.shape[0],maxiter) + #TODO make method adaptive numpy.random.seed(0) #make results deterministic From scipy-svn at scipy.org Mon Jan 21 15:41:22 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 21 Jan 2008 14:41:22 -0600 (CST) Subject: [Scipy-svn] r3853 - in trunk/scipy: linsolve/umfpack/tests misc/tests stats/models testing Message-ID: <20080121204122.5878239C258@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-21 14:40:25 -0600 (Mon, 21 Jan 2008) New Revision: 3853 Modified: trunk/scipy/linsolve/umfpack/tests/test_umfpack.py trunk/scipy/misc/tests/test_pilutil.py trunk/scipy/stats/models/setup.py trunk/scipy/testing/decorators.py trunk/scipy/testing/utils.py Log: Fancy decorator work to do conditional SkipTest exceptions for optional dependencies Modified: trunk/scipy/linsolve/umfpack/tests/test_umfpack.py =================================================================== --- trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-19 19:43:04 UTC (rev 3852) +++ trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-21 20:40:25 UTC (rev 3853) @@ -14,10 +14,17 @@ from scipy.sparse import csc_matrix, dok_matrix, spdiags import numpy as nm -import scipy.linsolve.umfpack as um - +try: + import scipy.linsolve.umfpack as um +except (ImportError, AttributeError): + _have_umfpack = False +else: + _have_umfpack = um.umfpack._um is not None + # Allow disabling of nose tests if umfpack not present -TestCase.__test__ = um.umfpack._um is not None +# See end of file for application +_umfpack_skip = dec.skipif(not _have_umfpack, + 'UMFPACK appears not to be compiled') class TestSolvers(TestCase): """Tests inverting a sparse linear system""" @@ -165,6 +172,9 @@ self.complex_matrices = [x.astype(nm.complex128) for x in self.real_matrices] +# Skip methods if umfpack not present +for cls in [TestSolvers, TestFactorization]: + decorate_methods(cls, _umfpack_skip) if __name__ == "__main__": nose.run(argv=['', __file__]) Modified: trunk/scipy/misc/tests/test_pilutil.py =================================================================== --- trunk/scipy/misc/tests/test_pilutil.py 2008-01-19 19:43:04 UTC (rev 3852) +++ trunk/scipy/misc/tests/test_pilutil.py 2008-01-21 20:40:25 UTC (rev 3853) @@ -11,8 +11,10 @@ else: _have_PIL = True import scipy.misc.pilutil as pilutil -TestCase.__test__ = _have_PIL +# Function / method decorator for skipping PIL tests on import failure +_pilskip = dec.skipif(not _have_PIL, 'Need to import PIL for this test') + datapath = os.path.dirname(__file__) class TestPILUtil(TestCase): @@ -28,14 +30,13 @@ assert_equal(pilutil.bytescale(x),x) assert_equal(pilutil.bytescale(y),[0,127,255]) - def tst_fromimage(filename, irange): img = pilutil.fromimage(PIL.Image.open(filename)) imin,imax = irange assert img.min() >= imin assert img.max() <= imax - at dec.setastest(_have_PIL) + at _pilskip def test_fromimage(): ''' Test generator for parametric tests ''' data = {'icon.png':(0,255), @@ -44,5 +45,7 @@ for fn, irange in data.iteritems(): yield tst_fromimage, os.path.join(datapath,'data',fn), irange +decorate_methods(TestPILUtil, _pilskip) + if __name__ == "__main__": nose.run(argv=['', __file__]) Modified: trunk/scipy/stats/models/setup.py =================================================================== --- trunk/scipy/stats/models/setup.py 2008-01-19 19:43:04 UTC (rev 3852) +++ trunk/scipy/stats/models/setup.py 2008-01-21 20:40:25 UTC (rev 3853) @@ -8,7 +8,6 @@ config.add_data_dir('tests') try: - import sys from scipy.stats.models.bspline_module import mod n, s, d = weave_ext(mod) config.add_extension(n, s, **d) Modified: trunk/scipy/testing/decorators.py =================================================================== --- trunk/scipy/testing/decorators.py 2008-01-19 19:43:04 UTC (rev 3852) +++ trunk/scipy/testing/decorators.py 2008-01-21 20:40:25 UTC (rev 3853) @@ -1,5 +1,10 @@ """Decorators for labeling test objects.""" +try: + import nose +except ImportError: + pass + def slow(t): """Labels a test as 'slow'. @@ -25,9 +30,33 @@ >>> @setastest(False) >>> def func_with_test_in_name(arg1, arg2): pass ... - >>> + >>> + + Note that this decorator cannot use the nose namespace, because it + can be called from a non-test. ''' def set_test(t): t.__test__ = tf return t return set_test + +def skipif(skip_condition, msg=None): + ''' Make function raise SkipTest exception if skip_condition is true + + Parameters + --------- + skip_condition : bool + Flag to determine whether to skip test (True) or not (False) + msg : string + Message to give on raising a SkipTest exception + ''' + if msg is None: + msg = 'Test skipped due to test condition (see code)' + def skip_decorator(f): + def skipper(*args, **kwargs): + if skip_condition: + raise nose.SkipTest, msg + else: + return f(*args, **kwargs) + return nose.tools.make_decorator(f)(skipper) + return skip_decorator Modified: trunk/scipy/testing/utils.py =================================================================== --- trunk/scipy/testing/utils.py 2008-01-19 19:43:04 UTC (rev 3852) +++ trunk/scipy/testing/utils.py 2008-01-21 20:40:25 UTC (rev 3853) @@ -1,10 +1,13 @@ """Simple testing utilities """ -__all__ = ['set_local_path', 'restore_path', 'measure', 'info', 'warn', 'error'] +__all__ = ['set_local_path', 'restore_path', 'measure', 'info', 'warn',\ + 'error', 'decorate_methods'] import os import sys +import re +from inspect import isfunction from numpy.distutils.misc_util import yellow_text, red_text from numpy.testing.utils import jiffies @@ -58,3 +61,38 @@ def error(message): print >> sys.stderr,red_text('Error: %s' % (message)) sys.stderr.flush() + +def decorate_methods(cls, decorator, testmatch=None): + ''' Apply decorator to all methods in class matching testmatch + + Parameters + ---------- + cls : class + Class to decorate methods for + decorator : function + Decorator to apply to methods + testmatch : compiled regexp or string to compile to regexp + Decorators are applied if testmatch.search(methodname) + is not None. Default value is + re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep) + (the default for nose) + ''' + if testmatch is None: + testmatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep) + else: + testmatch = re.compile(testmatch) + cls_attr = cls.__dict__ + methods = filter(isfunction, cls_attr.values()) + for function in methods: + try: + if hasattr(function, 'compat_func_name'): + funcname = function.compat_func_name + else: + funcname = function.__name__ + except AttributeError: + # not a function + continue + if testmatch.search(funcname) and not funcname.startswith('_'): + setattr(cls, funcname, decorator(function)) + return + From scipy-svn at scipy.org Tue Jan 22 10:06:30 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 22 Jan 2008 09:06:30 -0600 (CST) Subject: [Scipy-svn] r3854 - in trunk/scipy: sandbox/multigrid sparse Message-ID: <20080122150630.34E1939C292@new.scipy.org> Author: wnbell Date: 2008-01-22 09:06:22 -0600 (Tue, 22 Jan 2008) New Revision: 3854 Modified: trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sandbox/multigrid/sa.py trunk/scipy/sparse/bsr.py Log: minor change to SA Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-21 20:40:25 UTC (rev 3853) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-22 15:06:22 UTC (rev 3854) @@ -102,35 +102,45 @@ As = [A] Ps = [] + Rs = [] if aggregation is None: while len(As) < max_levels and A.shape[0] > max_coarse: P,B = sa_interpolation(A,B,epsilon*0.5**(len(As)-1),omega=omega) + R = P.T.asformat(P.format) - A = (P.T.asformat(P.format) * A) * P #galerkin operator + A = R * A * P #galerkin operator As.append(A) + Rs.append(R) Ps.append(P) else: #use user-defined aggregation for AggOp in aggregation: P,B = sa_interpolation(A,B,omega=omega,AggOp=AggOp) + R = P.T.asformat(P.format) - A = (P.T.tocsr() * A) * P #galerkin operator + A = R * A * P #galerkin operator As.append(A) + Rs.append(R) Ps.append(P) - return multilevel_solver(As,Ps,preprocess=pre,postprocess=post) + return multilevel_solver(As,Ps,Rs=Rs,preprocess=pre,postprocess=post) class multilevel_solver: - def __init__(self,As,Ps,preprocess=None,postprocess=None): + def __init__(self,As,Ps,Rs=None,preprocess=None,postprocess=None): self.As = As self.Ps = Ps self.preprocess = preprocess self.postprocess = postprocess + if Rs is None: + self.Rs = [P.T for P in self.Ps] + else: + self.Rs = Rs + def __repr__(self): output = 'multilevel_solver\n' output += 'Number of Levels: %d\n' % len(self.As) @@ -202,7 +212,7 @@ residual = b - A*x - coarse_b = self.Ps[lvl].T * residual + coarse_b = self.Rs[lvl] * residual coarse_x = zeros_like(coarse_b) if lvl == len(self.As) - 2: @@ -212,7 +222,7 @@ #coarse_x[:] = scipy.linalg.cg(self.As[-1],coarse_b,tol=1e-12)[0].reshape(coarse_x.shape) #A_inv = asarray(scipy.linalg.pinv2(self.As[-1].todense())) #coarse_x[:] = scipy.dot(A_inv,coarse_b) - #print "coarse residual norm",scipy.linalg.norm(coarse_b - self.As[-1]*coarse_x) + print "coarse residual norm",scipy.linalg.norm(coarse_b - self.As[-1]*coarse_x) else: self.__solve(lvl+1,coarse_x,coarse_b) Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-21 20:40:25 UTC (rev 3853) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-22 15:06:22 UTC (rev 3854) @@ -96,38 +96,38 @@ else: sa_constant_interpolation(csr_matrix(A),epsilon) -def sa_fit_candidates(AggOp,candidates,tol=1e-10): +def sa_fit_candidates(AggOp,B,tol=1e-10): if not isspmatrix_csr(AggOp): raise TypeError,'expected csr_matrix for argument AggOp' - if candidates.dtype != 'float32': - candidates = asarray(candidates,dtype='float64') + if B.dtype != 'float32': + B = asarray(B,dtype='float64') - if len(candidates.shape) != 2: + if len(B.shape) != 2: raise ValueError,'expected rank 2 array for argument B' - if candidates.shape[0] % AggOp.shape[0] != 0: + if B.shape[0] % AggOp.shape[0] != 0: raise ValueError,'dimensions of AggOp %s and B %s are incompatible' % (AggOp.shape, B.shape) - K = candidates.shape[1] # number of near-nullspace candidates - blocksize = candidates.shape[0] / AggOp.shape[0] + K = B.shape[1] # number of near-nullspace candidates + blocksize = B.shape[0] / AggOp.shape[0] N_fine,N_coarse = AggOp.shape - R = zeros((N_coarse,K,K),dtype=candidates.dtype) #storage for coarse candidates + R = zeros((N_coarse,K,K), dtype=B.dtype) #storage for coarse candidates candidate_matrices = [] - threshold = tol * abs(candidates).max() # cutoff for small basis functions - for i in range(K): - c = candidates[:,i] + c = B[:,i] c = c.reshape(-1,blocksize,1)[diff(AggOp.indptr) == 1] # eliminate DOFs that aggregation misses X = bsr_matrix( (c, AggOp.indices, AggOp.indptr), \ shape=(blocksize*N_fine, N_coarse) ) + col_thresholds = tol * bsr_matrix((X.data**2,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() + #orthogonalize X against previous for j,A in enumerate(candidate_matrices): D_AtX = bsr_matrix((A.data*X.data,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of A.T * X @@ -135,9 +135,10 @@ X.data -= scale_columns(A,D_AtX).data #normalize X - D_XtX = bsr_matrix((X.data**2,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of X.T * X - col_norms = sqrt(D_XtX) - mask = col_norms < threshold # set small basis functions to 0 + col_norms = bsr_matrix((X.data**2,X.indices,X.indptr),shape=X.shape).sum(axis=0).A.flatten() #same as diagonal of X.T * X + mask = col_norms < col_thresholds # set small basis functions to 0 + + col_norms = sqrt(col_norms) col_norms[mask] = 0 R[:,i,i] = col_norms col_norms = 1.0/col_norms @@ -186,7 +187,7 @@ return P -def sa_interpolation(A,candidates,epsilon=0.0,omega=4.0/3.0,AggOp=None): +def sa_interpolation(A,B,epsilon=0.0,omega=4.0/3.0,AggOp=None): if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): A = csr_matrix(A) @@ -200,7 +201,7 @@ raise ValueError,'incompatible aggregation operator' - T,coarse_candidates = sa_fit_candidates(AggOp,candidates) + T,coarse_candidates = sa_fit_candidates(AggOp,B) P = sa_smoothed_prolongator(A,T,epsilon,omega) return P,coarse_candidates Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-21 20:40:25 UTC (rev 3853) +++ trunk/scipy/sparse/bsr.py 2008-01-22 15:06:22 UTC (rev 3854) @@ -166,7 +166,7 @@ else: self.shape = shape - self.check_format() + self.check_format(full_check=False) def check_format(self, full_check=True): """check whether the matrix format is valid From scipy-svn at scipy.org Tue Jan 22 17:25:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 22 Jan 2008 16:25:32 -0600 (CST) Subject: [Scipy-svn] r3855 - trunk/scipy/sparse/tests Message-ID: <20080122222532.3FA0B39C144@new.scipy.org> Author: wnbell Date: 2008-01-22 16:25:28 -0600 (Tue, 22 Jan 2008) New Revision: 3855 Modified: trunk/scipy/sparse/tests/test_base.py Log: added sparse unittests Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-01-22 15:06:22 UTC (rev 3854) +++ trunk/scipy/sparse/tests/test_base.py 2008-01-22 22:25:28 UTC (rev 3855) @@ -33,7 +33,6 @@ -#TODO test spmatrix( [[1,2],[3,4]] ) format #TODO check that invalid shape in constructor raises exception #TODO check that spmatrix( ... , copy=X ) is respected #TODO test repr(spmatrix) @@ -97,6 +96,10 @@ assert_array_equal(self.spmatrix(A.A).todense(),A) assert_array_equal(self.spmatrix(A.tolist()).todense(),A) + def test_fromlist(self): + A = matrix([[1,0,0],[2,3,4],[0,5,0],[0,0,0]]) + assert_array_equal(self.spmatrix(A.tolist()).todense(),A) + def test_todense(self): chk = self.datsp.todense() assert_array_equal(chk,self.dat) @@ -122,7 +125,19 @@ check2 = dot(self.datsp.toarray(), b) assert_array_equal(dense_dot_dense, check2) + def test_asfptype(self): + A = self.spmatrix( arange(6,dtype='int32').reshape(2,3) ) + assert_equal( A.dtype , 'int32' ) + assert_equal( A.asfptype().dtype, 'float64' ) + assert_equal( A.astype('int16').asfptype().dtype , 'float32' ) + assert_equal( A.astype('complex128').asfptype().dtype , 'complex128' ) + + B = A.asfptype() + C = B.asfptype() + assert( B is C ) + + def test_mul_scalar(self): assert_array_equal(self.dat*2,(self.datsp*2).todense()) assert_array_equal(self.dat*17.3,(self.datsp*17.3).todense()) @@ -415,20 +430,7 @@ # assert_array_equal(dense_dot_dense, dense_dot_sparse) - def test_extract_diagonal(self): - """ - Test extraction of main diagonal from sparse matrices - """ - L = [] - L.append(array([[0,0,3],[1,6,4],[5,2,0]])) - L.append(array([[1,2,3]])) - L.append(array([[7],[6],[5]])) - L.append(array([[2]])) - for A in L: - assert_array_equal(numpy.diag(A),extract_diagonal(self.spmatrix(A))) - - class _TestInplaceArithmetic: def test_imul_scalar(self): a = self.datsp.copy() From scipy-svn at scipy.org Tue Jan 22 22:57:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 22 Jan 2008 21:57:11 -0600 (CST) Subject: [Scipy-svn] r3856 - trunk/scipy/sandbox Message-ID: <20080123035711.D5CEF39C2C1@new.scipy.org> Author: mattknox_ca Date: 2008-01-22 21:57:05 -0600 (Tue, 22 Jan 2008) New Revision: 3856 Removed: trunk/scipy/sandbox/timeseries/ Log: deleting timeseries module from sandbox. Moved to scikits svn From scipy-svn at scipy.org Wed Jan 23 14:55:59 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 23 Jan 2008 13:55:59 -0600 (CST) Subject: [Scipy-svn] r3857 - in trunk/scipy: testing weave/tests Message-ID: <20080123195559.7188839C0D4@new.scipy.org> Author: matthew.brett at gmail.com Date: 2008-01-23 13:55:50 -0600 (Wed, 23 Jan 2008) New Revision: 3857 Modified: trunk/scipy/testing/decorators.py trunk/scipy/testing/nosetester.py trunk/scipy/weave/tests/test_scxx_dict.py Log: Some testing package doctrings, removed willfail decorator in favor of skipknownfailure decorator Modified: trunk/scipy/testing/decorators.py =================================================================== --- trunk/scipy/testing/decorators.py 2008-01-23 03:57:05 UTC (rev 3856) +++ trunk/scipy/testing/decorators.py 2008-01-23 19:55:50 UTC (rev 3857) @@ -1,5 +1,15 @@ -"""Decorators for labeling test objects.""" +"""Decorators for labeling test objects +Decorators that merely return a modified version of the original +function object are straightforward. Decorators that return a new +function object need to use +nose.tools.make_decorator(original_function)(decorator) in returning +the decorator, in order to preserve metadata such as function name, +setup and teardown functions and so on - see nose.tools for more +information. + +""" + try: import nose except ImportError: @@ -16,24 +26,24 @@ t.slow = True return t -def willfail(t): - ''' Labels test as known failure +def setastest(tf=True): + ''' Signals to nose that this function is or is not a test - This label allows the tester to deselect the test in standard cases ''' - t.willfail = True - return t + Parameters + ---------- + tf : bool + If True specifies this is a test, not a test otherwise -def setastest(tf=True): - ''' Signals to nose that this function is or is not a test - e.g >>> @setastest(False) >>> def func_with_test_in_name(arg1, arg2): pass ... >>> - Note that this decorator cannot use the nose namespace, because it - can be called from a non-test. + This decorator cannot use the nose namespace, because it can be + called from a non-test module. See also istest and nottest in + nose.tools + ''' def set_test(t): t.__test__ = tf @@ -49,9 +59,22 @@ Flag to determine whether to skip test (True) or not (False) msg : string Message to give on raising a SkipTest 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. ''' if msg is None: - msg = 'Test skipped due to test condition (see code)' + msg = 'Test skipped due to test condition' def skip_decorator(f): def skipper(*args, **kwargs): if skip_condition: @@ -60,3 +83,10 @@ return f(*args, **kwargs) return nose.tools.make_decorator(f)(skipper) return skip_decorator + +def skipknownfailure(f): + ''' Decorator to raise SkipTest for test known to fail + ''' + def skipper(*args, **kwargs): + raise nose.SkipTest, 'This test is known to fail' + return nose.tools.make_decorator(f)(skipper) Modified: trunk/scipy/testing/nosetester.py =================================================================== --- trunk/scipy/testing/nosetester.py 2008-01-23 03:57:05 UTC (rev 3856) +++ trunk/scipy/testing/nosetester.py 2008-01-23 19:55:50 UTC (rev 3857) @@ -70,9 +70,9 @@ Special values are: 'fast' - the default - which corresponds to nosetests -A option of - 'not slow and not willfail'. + 'not slow'. 'full' - fast (as above) and slow %(testtype)s as in - nosetests -A option of 'not willfail'. + no -A option to nosetests - same as '' None or '' - run all %(testtype)ss attribute_identifier - string passed directly to nosetests as '-A' @@ -93,13 +93,11 @@ %(test_header)s ''' argv = [__file__, self.package_path, '-s'] - if label: + if label and label != 'full': if not isinstance(label, basestring): raise TypeError, 'Selection label should be a string' if label == 'fast': - label = 'not slow and not willfail' - elif label == 'full': - label = 'not willfail' + label = 'not slow' argv += ['-A', label] argv += ['--verbosity', str(verbose)] if extra_argv: Modified: trunk/scipy/weave/tests/test_scxx_dict.py =================================================================== --- trunk/scipy/weave/tests/test_scxx_dict.py 2008-01-23 03:57:05 UTC (rev 3856) +++ trunk/scipy/weave/tests/test_scxx_dict.py 2008-01-23 19:55:50 UTC (rev 3857) @@ -111,8 +111,8 @@ def test_char(self): self.generic_get('return_val = a["b"];') + @dec.skipknownfailure @dec.slow - @dec.willfail def test_char_fail(self): # We can't through a KeyError for dicts on RHS of # = but not on LHS. Not sure how to deal with this. @@ -134,8 +134,8 @@ """ self.generic_get(code,['a']) + @dec.skipknownfailure @dec.slow - @dec.willfail def test_obj_fail(self): # We can't through a KeyError for dicts on RHS of # = but not on LHS. Not sure how to deal with this. From scipy-svn at scipy.org Wed Jan 23 17:38:14 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 23 Jan 2008 16:38:14 -0600 (CST) Subject: [Scipy-svn] r3858 - trunk/scipy/ndimage Message-ID: <20080123223814.209BD39C00C@new.scipy.org> Author: stefan Date: 2008-01-23 16:37:53 -0600 (Wed, 23 Jan 2008) New Revision: 3858 Modified: trunk/scipy/ndimage/filters.py trunk/scipy/ndimage/interpolation.py Log: Use decorators to add commonly used docstrings. Modified: trunk/scipy/ndimage/filters.py =================================================================== --- trunk/scipy/ndimage/filters.py 2008-01-23 19:55:50 UTC (rev 3857) +++ trunk/scipy/ndimage/filters.py 2008-01-23 22:37:53 UTC (rev 3858) @@ -33,13 +33,32 @@ import _ni_support import _nd_image +_mode_doc = \ +"""The mode parameter determines how the array borders are handled, + where cval is the value when mode is equal to 'constant'. Other + modes are 'nearest', 'mirror', 'reflect' and 'wrap'.""" + +_origin_doc = """ + + The origin parameter controls the placement of the filter.""" + +def moredoc(*args): + def decorate(f): + if not f.__doc__: f.__doc__ = "" + for a in args: f.__doc__ += a + return f + return decorate + + at moredoc(_mode_doc, _origin_doc) def correlate1d(input, weights, axis = -1, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculate a one-dimensional correlation along the given axis. The lines of the array along the given axis are correlated with the given weights. The weights parameter must be a one-dimensional sequence - of numbers.""" + of numbers. + + """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError, 'Complex type not supported' @@ -58,19 +77,23 @@ origin) return return_value + at moredoc(_mode_doc, _origin_doc) def convolve1d(input, weights, axis = -1, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculate a one-dimensional convolution along the given axis. The lines of the array along the given axis are convolved with the given weights. The weights parameter must be a one-dimensional sequence - of numbers.""" + of numbers. + + """ weights = weights[::-1] origin = -origin if not len(weights) & 1: origin -= 1 return correlate1d(input, weights, axis, output, mode, cval, origin) + at moredoc(_mode_doc, _origin_doc) def gaussian_filter1d(input, sigma, axis = -1, order = 0, output = None, mode = "reflect", cval = 0.0): """One-dimensional Gaussian filter. @@ -80,6 +103,7 @@ kernel. An order of 1, 2, or 3 corresponds to convolution with the first, second or third derivatives of a Gaussian. Higher order derivatives are not implemented. + """ sd = float(sigma) # make the length of the filter equal to 4 times the standard @@ -122,6 +146,7 @@ weights[lw - ii] = tmp return correlate1d(input, weights, axis, output, mode, cval, 0) + at moredoc(_mode_doc, _origin_doc) def gaussian_filter(input, sigma, order = 0, output = None, mode = "reflect", cval = 0.0): """Multi-dimensional Gaussian filter. @@ -141,6 +166,7 @@ types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. + """ input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) @@ -158,8 +184,10 @@ output[...] = input[...] return return_value + at moredoc(_mode_doc, _origin_doc) def prewitt(input, axis = -1, output = None, mode = "reflect", cval = 0.0): """Calculate a Prewitt filter. + """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) @@ -170,8 +198,10 @@ correlate1d(output, [1, 1, 1], ii, output, mode, cval, 0,) return return_value + at moredoc(_mode_doc, _origin_doc) def sobel(input, axis = -1, output = None, mode = "reflect", cval = 0.0): """Calculate a Sobel filter. + """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) @@ -182,6 +212,7 @@ correlate1d(output, [1, 2, 1], ii, output, mode, cval, 0) return return_value + at moredoc(_mode_doc, _origin_doc) def generic_laplace(input, derivative2, output = None, mode = "reflect", cval = 0.0, extra_arguments = (), extra_keywords = {}): """Calculate a multidimensional laplace filter using the provided @@ -196,6 +227,7 @@ The extra_arguments and extra_keywords arguments can be used to pass extra arguments and keywords that are passed to derivative2 at each call. + """ input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) @@ -211,14 +243,17 @@ output[...] = input[...] return return_value + at moredoc(_mode_doc, _origin_doc) def laplace(input, output = None, mode = "reflect", cval = 0.0): """Calculate a multidimensional laplace filter using an estimation for the second derivative based on differences. + """ def derivative2(input, axis, output, mode, cval): return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0) return generic_laplace(input, derivative2, output, mode, cval) + at moredoc(_mode_doc, _origin_doc) def gaussian_laplace(input, sigma, output = None, mode = "reflect", cval = 0.0): """Calculate a multidimensional laplace filter using gaussian @@ -227,6 +262,7 @@ The standard-deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.. + """ input = numpy.asarray(input) def derivative2(input, axis, output, mode, cval, sigma): @@ -236,6 +272,7 @@ return generic_laplace(input, derivative2, output, mode, cval, extra_arguments = (sigma,)) + at moredoc(_mode_doc, _origin_doc) def generic_gradient_magnitude(input, derivative, output = None, mode = "reflect", cval = 0.0, extra_arguments = (), extra_keywords = {}): @@ -251,6 +288,7 @@ The extra_arguments and extra_keywords arguments can be used to pass extra arguments and keywords that are passed to derivative2 at each call. + """ input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) @@ -269,6 +307,7 @@ output[...] = input[...] return return_value + at moredoc(_mode_doc, _origin_doc) def gaussian_gradient_magnitude(input, sigma, output = None, mode = "reflect", cval = 0.0): """Calculate a multidimensional gradient magnitude using gaussian @@ -277,6 +316,7 @@ The standard-deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.. + """ input = numpy.asarray(input) def derivative(input, axis, output, mode, cval, sigma): @@ -312,30 +352,37 @@ _nd_image.correlate(input, weights, output, mode, cval, origins) return return_value + at moredoc(_mode_doc, _origin_doc) def correlate(input, weights, output = None, mode = 'reflect', cval = 0.0, origin = 0): """Multi-dimensional correlation. The array is correlated with the given kernel. + """ return _correlate_or_convolve(input, weights, output, mode, cval, origin, False) + at moredoc(_mode_doc, _origin_doc) def convolve(input, weights, output = None, mode = 'reflect', cval = 0.0, origin = 0): """Multi-dimensional convolution. The array is convolved with the given kernel. + """ return _correlate_or_convolve(input, weights, output, mode, cval, origin, True) + at moredoc(_mode_doc, _origin_doc) def uniform_filter1d(input, size, axis = -1, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculate a one-dimensional uniform filter along the given axis. The lines of the array along the given axis are filtered with a - uniform filter of given size.""" + uniform filter of given size. + + """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError, 'Complex type not supported' @@ -350,6 +397,7 @@ origin) return return_value + at moredoc(_mode_doc, _origin_doc) def uniform_filter(input, size = 3, output = None, mode = "reflect", cval = 0.0, origin = 0): """Multi-dimensional uniform filter. @@ -363,6 +411,7 @@ in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. + """ input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) @@ -380,12 +429,15 @@ output[...] = input[...] return return_value + at moredoc(_mode_doc, _origin_doc) def minimum_filter1d(input, size, axis = -1, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculate a one-dimensional minimum filter along the given axis. The lines of the array along the given axis are filtered with a - minimum filter of given size.""" + minimum filter of given size. + + """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError, 'Complex type not supported' @@ -400,12 +452,15 @@ origin, 1) return return_value + at moredoc(_mode_doc, _origin_doc) def maximum_filter1d(input, size, axis = -1, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculate a one-dimensional maximum filter along the given axis. The lines of the array along the given axis are filtered with a - maximum filter of given size.""" + maximum filter of given size. + + """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError, 'Complex type not supported' @@ -483,28 +538,26 @@ mode, cval, origins, minimum) return return_value + at moredoc(_mode_doc, _origin_doc) def minimum_filter(input, size = None, footprint = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculates a multi-dimensional minimum filter. Either a size or a footprint with the filter must be - provided. An output array can optionally be provided. The origin - parameter controls the placement of the filter. The mode parameter - determines how the array borders are handled, where cval is the - value when mode is equal to 'constant'. + provided. An output array can optionally be provided. + """ return _min_or_max_filter(input, size, footprint, None, output, mode, cval, origin, 1) + at moredoc(_mode_doc, _origin_doc) def maximum_filter(input, size = None, footprint = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculates a multi-dimensional maximum filter. Either a size or a footprint with the filter must be - provided. An output array can optionally be provided. The origin - parameter controls the placement of the filter. The mode parameter - determines how the array borders are handled, where cval is the - value when mode is equal to 'constant'. + provided. An output array can optionally be provided. + """ return _min_or_max_filter(input, size, footprint, None, output, mode, cval, origin, 0) @@ -561,6 +614,7 @@ origins) return return_value + at moredoc(_mode_doc, _origin_doc) def rank_filter(input, rank, size = None, footprint = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculates a multi-dimensional rank filter. @@ -568,26 +622,25 @@ The rank parameter may be less then zero, i.e., rank = -1 indicates the larges element. Either a size or a footprint with the filter must be provided. An output array can optionally be - provided. The origin parameter controls the placement of the - filter. The mode parameter determines how the array borders are - handled, where cval is the value when mode is equal to 'constant'. + provided. + """ return _rank_filter(input, rank, size, footprint, output, mode, cval, origin, 'rank') + at moredoc(_mode_doc, _origin_doc) def median_filter(input, size = None, footprint = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculates a multi-dimensional median filter. Either a size or a footprint with the filter must be provided. An - output array can optionally be provided. The origin parameter - controls the placement of the filter. The mode parameter - determines how the array borders are handled, where cval is the - value when mode is equal to 'constant'. + output array can optionally be provided. + """ return _rank_filter(input, 0, size, footprint, output, mode, cval, origin, 'median') + at moredoc(_mode_doc, _origin_doc) def percentile_filter(input, percentile, size = None, footprint = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculates a multi-dimensional percentile filter. @@ -595,28 +648,28 @@ The percentile parameter may be less then zero, i.e., percentile = -20 equals percentile = 80. Either a size or a footprint with the filter must be provided. An output array can optionally be - provided. The origin parameter controls the placement of the - filter. The mode parameter determines how the array borders are - handled, where cval is the value when mode is equal to 'constant'. + provided. + """ return _rank_filter(input, percentile, size, footprint, output, mode, cval, origin, 'percentile') + at moredoc(_mode_doc, _origin_doc) def generic_filter1d(input, function, filter_size, axis = -1, output = None, mode = "reflect", cval = 0.0, origin = 0, extra_arguments = (), extra_keywords = {}): """Calculate a one-dimensional filter along the given axis. - The function iterates over the lines of the array, calling the given - function at each line. The arguments of the line are the input line, - and the output line. The input and output lines are 1D double arrays. - The input line is extended appropiately according to the filter size - and origin. The output line must be modified in-place with the result. - The origin parameter controls the placement of the filter. The mode - parameter determines how the array borders are handled, where cval is - the value when mode is equal to 'constant'. The extra_arguments and - extra_keywords arguments can be used to pass extra arguments and - keywords that are passed to the function at each call.""" + The function iterates over the lines of the array, calling the + given function at each line. The arguments of the line are the + input line, and the output line. The input and output lines are 1D + double arrays. The input line is extended appropiately according + to the filter size and origin. The output line must be modified + in-place with the result. The extra_arguments and extra_keywords + arguments can be used to pass extra arguments and keywords that + are passed to the function at each call. + + """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError, 'Complex type not supported' @@ -632,6 +685,7 @@ mode, cval, origin, extra_arguments, extra_keywords) return return_value + at moredoc(_mode_doc, _origin_doc) def generic_filter(input, function, size = None, footprint = None, output = None, mode = "reflect", cval = 0.0, origin = 0, extra_arguments = (), extra_keywords = {}): @@ -642,12 +696,11 @@ as a 1D array of double values. Either a size or a footprint with the filter must be provided. An - output array can optionally be provided. The origin parameter - controls the placement of the filter. The mode parameter - determines how the array borders are handled, where cval is the - value when mode is equal to 'constant'. The extra_arguments and + output array can optionally be provided. The extra_arguments and extra_keywords arguments can be used to pass extra arguments and - keywords that are passed to the function at each call.""" + keywords that are passed to the function at each call. + + """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError, 'Complex type not supported' Modified: trunk/scipy/ndimage/interpolation.py =================================================================== --- trunk/scipy/ndimage/interpolation.py 2008-01-23 19:55:50 UTC (rev 3857) +++ trunk/scipy/ndimage/interpolation.py 2008-01-23 22:37:53 UTC (rev 3858) @@ -110,16 +110,17 @@ extra_keywords arguments can be used to provide extra arguments and keywords that are passed to the mapping function at each call. - Example usage: - >>> a = arange(12.).reshape((4,3)) - >>> def shift_func(output_coordinates): - ... return (output_coordinates[0]-0.5, output_coordinates[1]-0.5) - ... - >>> print geometric_transform(a,shift_func) - array([[ 0. , 0. , 0. ], - [ 0. , 1.3625, 2.7375], - [ 0. , 4.8125, 6.1875], - [ 0. , 8.2625, 9.6375]]) + Example + ------- + >>> a = arange(12.).reshape((4,3)) + >>> def shift_func(output_coordinates): + ... return (output_coordinates[0]-0.5, output_coordinates[1]-0.5) + ... + >>> print geometric_transform(a,shift_func) + array([[ 0. , 0. , 0. ], + [ 0. , 1.3625, 2.7375], + [ 0. , 4.8125, 6.1875], + [ 0. , 8.2625, 9.6375]]) """ if order < 0 or order > 5: raise RuntimeError, 'spline order not supported' @@ -165,19 +166,21 @@ interpolation (necessary for spline interpolation of order > 1). If False it is assumed that the input is already filtered. - Example usage: - >>> a = arange(12.).reshape((4,3)) - >>> print a - [[ 0. 1. 2.] - [ 3. 4. 5.] - [ 6. 7. 8.] - [ 9. 10. 11.]] - >>> output = map_coordinates(a,[[0.5, 2], [0.5, 1]],order=1) - >>> print output - [ 2. 7.] + Example + ------- + >>> a = arange(12.).reshape((4,3)) + >>> print a + [[ 0. 1. 2.] + [ 3. 4. 5.] + [ 6. 7. 8.] + [ 9. 10. 11.]] + >>> output = map_coordinates(a,[[0.5, 2], [0.5, 1]],order=1) + >>> print output + [ 2. 7.] - Here, the interpolated value of a[0.5,0.5] gives output[0], while - a[2,1] is output[1]. + Here, the interpolated value of a[0.5,0.5] gives output[0], while + a[2,1] is output[1]. + """ if order < 0 or order > 5: raise RuntimeError, 'spline order not supported' From scipy-svn at scipy.org Thu Jan 24 16:11:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 24 Jan 2008 15:11:20 -0600 (CST) Subject: [Scipy-svn] r3859 - in trunk/scipy/sandbox/multigrid: . tests Message-ID: <20080124211120.1047339C07E@new.scipy.org> Author: wnbell Date: 2008-01-24 15:11:16 -0600 (Thu, 24 Jan 2008) New Revision: 3859 Modified: trunk/scipy/sandbox/multigrid/adaptive.py trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sandbox/multigrid/sa.py trunk/scipy/sandbox/multigrid/tests/test_adaptive.py trunk/scipy/sandbox/multigrid/tests/test_sa.py Log: reworked SA code made substeps accept user-defined functions Modified: trunk/scipy/sandbox/multigrid/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-23 22:37:53 UTC (rev 3858) +++ trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-24 21:11:16 UTC (rev 3859) @@ -12,8 +12,8 @@ from relaxation import gauss_seidel from multilevel import multilevel_solver from utils import approximate_spectral_radius,hstack_csr,vstack_csr,diag_sparse -from sa import sa_constant_interpolation, sa_smoothed_prolongator, \ - sa_fit_candidates +from sa import sa_standard_aggregation, sa_smoothed_prolongator, \ + sa_fit_candidates, sa_strong_connections @@ -40,7 +40,7 @@ for AggOp in AggOps: P,B = sa_fit_candidates(AggOp,B) - I = sa_smoothed_prolongator(A,P) + I = sa_smoothed_prolongator(A,A,P) A = I.T.asformat(I.format) * A * I As.append(A) Ts.append(P) @@ -159,12 +159,14 @@ while len(AggOps) + 1 < max_levels and A_l.shape[0] > max_coarse: if aggregation is None: - W_l = sa_constant_interpolation(A_l,epsilon=0) #step 4b + C_l = sa_strong_connections(A_l,epsilon) + W_l = sa_standard_aggregation(C_l) #step 4b else: W_l = aggregation[len(AggOps)] P_l,x = sa_fit_candidates(W_l,x) #step 4c - I_l = sa_smoothed_prolongator(A_l,P_l) #step 4d - A_l = I_l.T.asformat(I_l.format) * A_l * I_l #step 4e + I_l = sa_smoothed_prolongator(A_l,A_l,P_l) #step 4d + A_l = I_l.T.asformat(I_l.format) * A_l * I_l #step 4e + #TODO change variable names I_l -> P, P_l -> T AggOps.append(W_l) Ps.append(I_l) Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-23 22:37:53 UTC (rev 3858) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-24 21:11:16 UTC (rev 3859) @@ -1,5 +1,4 @@ -__all__ = ['ruge_stuben_solver','smoothed_aggregation_solver', - 'multilevel_solver'] +__all__ = ['ruge_stuben_solver','multilevel_solver'] import scipy import numpy @@ -8,7 +7,6 @@ from scipy.linsolve import spsolve from scipy.sparse import dia_matrix -from sa import sa_interpolation from rs import rs_interpolation from relaxation import gauss_seidel,jacobi,sor from utils import symmetric_rescaling, diag_sparse @@ -41,94 +39,8 @@ -def smoothed_aggregation_solver(A, B=None, max_levels=10, max_coarse=500, \ - epsilon=0.0, omega=4.0/3.0, symmetric=True, rescale=True, \ - aggregation=None): - """Create a multilevel solver using Smoothed Aggregation (SA) - *Parameters*: - A : {csr_matrix} - NxN matrix in CSR or BSR format - B : {None, array_like} : optional - Near-nullspace candidates stored in the columns of an NxK array. - The default value B=None is equivalent to B=ones((N,1)) - max_levels: {integer} : default 10 - Maximum number of levels to be used in the multilevel solver. - max_coarse: {integer} : default 500 - Maximum number of variables permitted on the coarse grid. - epsilon: {float} : default 0.0 - Strength of connection parameter used in aggregation. - omega: {float} : default 4.0/3.0 - Damping parameter used in prolongator smoothing (0 < omega < 2) - symmetric: {boolean} : default True - True if A is symmetric, False otherwise - rescale: {boolean} : default True - If True, symmetrically rescale A by the diagonal - i.e. A -> D * A * D, where D is diag(A)^-0.5 - aggregation: {None, list of csr_matrix} : optional - List of csr_matrix objects that describe a user-defined - multilevel aggregation of the variables. - TODO ELABORATE - - *Example*: - TODO - - *References*: - "Algebraic Multigrid by Smoothed Aggregation for Second and Fourth Order Elliptic Problems", - Petr Vanek and Jan Mandel and Marian Brezina - http://citeseer.ist.psu.edu/vanek96algebraic.html - - """ - - A = A.asfptype() - - if B is None: - B = ones((A.shape[0],1),dtype=A.dtype) # use constant vector - else: - B = asarray(B,dtype=A.dtype) - - pre,post = None,None #preprocess/postprocess - - if rescale: - D_sqrt,D_sqrt_inv,A = symmetric_rescaling(A) - D_sqrt,D_sqrt_inv = diag_sparse(D_sqrt),diag_sparse(D_sqrt_inv) - - B = D_sqrt * B #scale candidates - def pre(x,b): - return D_sqrt*x,D_sqrt_inv*b - def post(x): - return D_sqrt_inv*x - - As = [A] - Ps = [] - Rs = [] - - if aggregation is None: - while len(As) < max_levels and A.shape[0] > max_coarse: - P,B = sa_interpolation(A,B,epsilon*0.5**(len(As)-1),omega=omega) - R = P.T.asformat(P.format) - - A = R * A * P #galerkin operator - - As.append(A) - Rs.append(R) - Ps.append(P) - else: - #use user-defined aggregation - for AggOp in aggregation: - P,B = sa_interpolation(A,B,omega=omega,AggOp=AggOp) - R = P.T.asformat(P.format) - - A = R * A * P #galerkin operator - - As.append(A) - Rs.append(R) - Ps.append(P) - - return multilevel_solver(As,Ps,Rs=Rs,preprocess=pre,postprocess=post) - - class multilevel_solver: def __init__(self,As,Ps,Rs=None,preprocess=None,postprocess=None): self.As = As @@ -222,7 +134,7 @@ #coarse_x[:] = scipy.linalg.cg(self.As[-1],coarse_b,tol=1e-12)[0].reshape(coarse_x.shape) #A_inv = asarray(scipy.linalg.pinv2(self.As[-1].todense())) #coarse_x[:] = scipy.dot(A_inv,coarse_b) - print "coarse residual norm",scipy.linalg.norm(coarse_b - self.As[-1]*coarse_x) + #print "coarse residual norm",scipy.linalg.norm(coarse_b - self.As[-1]*coarse_x) else: self.__solve(lvl+1,coarse_x,coarse_b) Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-23 22:37:53 UTC (rev 3858) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-24 21:11:16 UTC (rev 3859) @@ -1,15 +1,14 @@ -import scipy -import numpy -from numpy import array,arange,ones,zeros,sqrt,isinf,asarray,empty,diff,\ - ascontiguousarray +from numpy import array, arange, ones, zeros, sqrt, asarray, empty, diff from scipy.sparse import csr_matrix, isspmatrix_csr, bsr_matrix, isspmatrix_bsr +import multigridtools +from multilevel import multilevel_solver from utils import diag_sparse, approximate_spectral_radius, \ symmetric_rescaling, scale_columns -import multigridtools -__all__ = ['sa_filtered_matrix','sa_strong_connections','sa_constant_interpolation', - 'sa_interpolation','sa_smoothed_prolongator','sa_fit_candidates'] +__all__ = ['smoothed_aggregation_solver', + 'sa_filtered_matrix','sa_strong_connections','sa_standard_aggregation', + 'sa_smoothed_prolongator','sa_fit_candidates'] @@ -58,43 +57,54 @@ return A_filtered -def sa_strong_connections(A,epsilon): - if not isspmatrix_csr(A): raise TypeError('expected csr_matrix') +def sa_strong_connections(A,epsilon=0): + """Compute a strength of connection matrix C - Sp,Sj,Sx = multigridtools.sa_strong_connections(A.shape[0],epsilon,A.indptr,A.indices,A.data) + C[i,j] = 1 if abs(A[i,j]) >= epsilon * abs(A[i,i] * A[j,j]) + C[i,j] = 0 otherwise - return csr_matrix((Sx,Sj,Sp),A.shape) - - -def sa_constant_interpolation(A,epsilon): - """Compute the sparsity pattern of the tentative prolongator """ - if isspmatrix_csr(A): - S = sa_strong_connections(A,epsilon) - Pj = multigridtools.sa_get_aggregates(S.shape[0],S.indptr,S.indices) - Pp = numpy.arange(len(Pj)+1) - Px = numpy.ones(len(Pj)) #TODO replace this with something else? - - return csr_matrix((Px,Pj,Pp)) + if isspmatrix_csr(A): + if epsilon == 0: + return A + else: + fn = multigridtools.sa_strong_connections + Sp,Sj,Sx = fn(A.shape[0],epsilon,A.indptr,A.indices,A.data) + return csr_matrix((Sx,Sj,Sp),A.shape) elif isspmatrix_bsr(A): - - # the strength of connection matrix is based on the Frobenius norms of the blocks M,N = A.shape R,C = A.blocksize if R != C: raise ValueError,'matrix must have square blocks' - f_norms = (A.data*A.data).reshape(-1,R*C).sum(axis=1) #Frobenius norm of each block + if epsilon == 0: + data = ones( len(A.indices), dtype=A.dtype ) + return csr_matrix((data,A.indices,A.indptr),shape=(M/R,N/C)) + else: + # the strength of connection matrix is based on the + # Frobenius norms of the blocks + data = (A.data*A.data).reshape(-1,R*C).sum(axis=1) + A = csr_matrix((data,A.indices,A.indptr),shape=(M/R,N/C)) + return sa_strong_connections(A,epsilon) + else: + raise TypeError('expected csr_matrix or bsr_matrix') + +def sa_standard_aggregation(C): + """Compute the sparsity pattern of the tentative prolongator + from a strength of connection matrix C + """ + if isspmatrix_csr(C): - A = csr_matrix((f_norms,A.indices,A.indptr),shape=(M/R,N/C)) - - return sa_constant_interpolation(A,epsilon) - + Pj = multigridtools.sa_get_aggregates(C.shape[0],C.indptr,C.indices) + Pp = arange(len(Pj)+1) + Px = ones(len(Pj)) #TODO replace this with something else? + + return csr_matrix((Px,Pj,Pp)) else: - sa_constant_interpolation(csr_matrix(A),epsilon) + raise TypeError('expected csr_matrix') def sa_fit_candidates(AggOp,B,tol=1e-10): if not isspmatrix_csr(AggOp): @@ -158,7 +168,7 @@ return Q,R -def sa_smoothed_prolongator(A,T,epsilon=0.0,omega=4.0/3.0): +def sa_smoothed_prolongator(A,C,T,epsilon=0.0,omega=4.0/3.0): """For a given matrix A and tentative prolongator T return the smoothed prolongator P @@ -187,21 +197,110 @@ return P -def sa_interpolation(A,B,epsilon=0.0,omega=4.0/3.0,AggOp=None): + +def smoothed_aggregation_solver(A, B=None, + max_levels = 10, + max_coarse = 500, + strength = sa_strong_connections, + aggregate = sa_standard_aggregation, + tentative = sa_fit_candidates, + smooth = sa_smoothed_prolongator): + """Create a multilevel solver using Smoothed Aggregation (SA) + + *Parameters*: + + A : {csr_matrix, bsr_matrix} + Square matrix in CSR or BSR format + B : {None, array_like} + Near-nullspace candidates stored in the columns of an NxK array. + The default value B=None is equivalent to B=ones((N,1)) + max_levels: {integer} : default 10 + Maximum number of levels to be used in the multilevel solver. + max_coarse: {integer} : default 500 + Maximum number of variables permitted on the coarse grid. + strength : + Function that computes the strength of connection matrix C + strength(A) -> C + aggregate : + Function that computes an aggregation operator + aggregate(C) -> AggOp + tentative: + Function that computes a tentative prolongator + tentative(AggOp,B) -> T,B_coarse + smooth : + Function that smooths the tentative prolongator + smooth(A,C,T) -> P + + Unused Parameters + epsilon: {float} : default 0.0 + Strength of connection parameter used in aggregation. + omega: {float} : default 4.0/3.0 + Damping parameter used in prolongator smoothing (0 < omega < 2) + symmetric: {boolean} : default True + True if A is symmetric, False otherwise + rescale: {boolean} : default True + If True, symmetrically rescale A by the diagonal + i.e. A -> D * A * D, where D is diag(A)^-0.5 + aggregation: {None, list of csr_matrix} : optional + List of csr_matrix objects that describe a user-defined + multilevel aggregation of the variables. + TODO ELABORATE + + *Example*: + TODO + + *References*: + "Algebraic Multigrid by Smoothed Aggregation for Second and Fourth Order Elliptic Problems", + Petr Vanek and Jan Mandel and Marian Brezina + http://citeseer.ist.psu.edu/vanek96algebraic.html + + """ + + A = A.asfptype() + if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): - A = csr_matrix(A) + raise TypeError('argument A must have type csr_matrix or bsr_matrix') - if AggOp is None: - AggOp = sa_constant_interpolation(A,epsilon=epsilon) + if A.shape[0] != A.shape[1]: + raise ValueError('expected square matrix') + + if B is None: + B = ones((A.shape[0],1),dtype=A.dtype) # use constant vector else: - if not isspmatrix_csr(AggOp): - AggOp = csr_matrix(AggOp) - if A.shape[1] != AggOp.shape[0]: - raise ValueError,'incompatible aggregation operator' + B = asarray(B,dtype=A.dtype) + pre,post = None,None #preprocess/postprocess - T,coarse_candidates = sa_fit_candidates(AggOp,B) - P = sa_smoothed_prolongator(A,T,epsilon,omega) - return P,coarse_candidates + #if rescale: + # D_sqrt,D_sqrt_inv,A = symmetric_rescaling(A) + # D_sqrt,D_sqrt_inv = diag_sparse(D_sqrt),diag_sparse(D_sqrt_inv) + # B = D_sqrt * B #scale candidates + # def pre(x,b): + # return D_sqrt*x,D_sqrt_inv*b + # def post(x): + # return D_sqrt_inv*x + + As = [A] + Ps = [] + Rs = [] + + while len(As) < max_levels and A.shape[0] > max_coarse: + C = strength(A) + AggOp = aggregate(C) + T,B = tentative(AggOp,B) + P = smooth(A,C,T) + + R = P.T.asformat(P.format) + + A = R * A * P #galerkin operator + + As.append(A) + Rs.append(R) + Ps.append(P) + + + return multilevel_solver(As,Ps,Rs=Rs,preprocess=pre,postprocess=post) + + Modified: trunk/scipy/sandbox/multigrid/tests/test_adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-23 22:37:53 UTC (rev 3858) +++ trunk/scipy/sandbox/multigrid/tests/test_adaptive.py 2008-01-24 21:11:16 UTC (rev 3859) @@ -5,8 +5,7 @@ from scipy.sparse import csr_matrix -from scipy.sandbox.multigrid.sa import sa_fit_candidates -from scipy.sandbox.multigrid import smoothed_aggregation_solver +from scipy.sandbox.multigrid.sa import sa_fit_candidates, smoothed_aggregation_solver #from scipy.sandbox.multigrid.adaptive import augment_candidates from scipy.sandbox.multigrid.gallery import * Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-23 22:37:53 UTC (rev 3858) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-24 21:11:16 UTC (rev 3859) @@ -16,12 +16,8 @@ import scipy.sandbox.multigrid -from scipy.sandbox.multigrid.sa import sa_strong_connections, sa_constant_interpolation, \ - sa_interpolation, sa_fit_candidates, \ - sa_smoothed_prolongator -from scipy.sandbox.multigrid.multilevel import smoothed_aggregation_solver +from scipy.sandbox.multigrid.sa import * from scipy.sandbox.multigrid.utils import diag_sparse - from scipy.sandbox.multigrid.gallery import poisson #def sparsity(A): @@ -61,72 +57,71 @@ assert_almost_equal(S_result.todense(),S_expected.todense()) #assert_array_equal(sparsity(S_result).todense(),sparsity(S_expected).todense()) - def test_sa_constant_interpolation(self): - for A in self.cases: - for epsilon in [0.0,0.1,0.5,1.0]: - S_expected = reference_sa_constant_interpolation(A,epsilon) + ## two aggregates in 1D + #A = poisson( (6,), format='csr') + #AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) + #candidates = ones((6,1)) - S_result = sa_constant_interpolation(A,epsilon) - assert_array_equal(S_result.todense(),S_expected.todense()) + #T_result,coarse_candidates_result = sa_fit_candidates(AggOp,candidates) + #T_expected = csr_matrix((sqrt(1.0/3.0)*ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) + #assert_almost_equal(T_result.todense(),T_expected.todense()) - #A = A.tobsr( blocksize=(1,1) ) - #S_result = sa_constant_interpolation(A,epsilon) - #assert_array_equal(S_result.todense(),S_expected.todense()) + ##check simple block examples + #A = csr_matrix(arange(16).reshape(4,4)) + #A = A + A.T + #A = A.tobsr(blocksize=(2,2)) - # two aggregates in 1D - A = poisson( (6,), format='csr') - AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) - candidates = ones((6,1)) + #S_result = sa_standard_aggregation(A,epsilon=0.0) + #S_expected = matrix([1,1]).T + #assert_array_equal(S_result.todense(),S_expected) - T_result,coarse_candidates_result = sa_fit_candidates(AggOp,candidates) - T_expected = csr_matrix((sqrt(1.0/3.0)*ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) - assert_almost_equal(T_result.todense(),T_expected.todense()) + #S_result = sa_standard_aggregation(A,epsilon=0.5) + #S_expected = matrix([1,1]).T + #assert_array_equal(S_result.todense(),S_expected) - #check simple block examples - A = csr_matrix(arange(16).reshape(4,4)) - A = A + A.T - A = A.tobsr(blocksize=(2,2)) + #S_result = sa_standard_aggregation(A,epsilon=2.0) + #S_expected = matrix([[1,0],[0,1]]) + #assert_array_equal(S_result.todense(),S_expected) - S_result = sa_constant_interpolation(A,epsilon=0.0) - S_expected = matrix([1,1]).T - assert_array_equal(S_result.todense(),S_expected) + def test_sa_standard_aggregation(self): + for C in self.cases: + S_expected = reference_sa_standard_aggregation(C) - S_result = sa_constant_interpolation(A,epsilon=0.5) - S_expected = matrix([1,1]).T - assert_array_equal(S_result.todense(),S_expected) + S_result = sa_standard_aggregation(C) + assert_array_equal(S_result.todense(),S_expected.todense()) - S_result = sa_constant_interpolation(A,epsilon=2.0) - S_expected = matrix([[1,0],[0,1]]) - assert_array_equal(S_result.todense(),S_expected) + #A = A.tobsr( blocksize=(1,1) ) + #S_result = sa_constant_interpolation(A,epsilon) + #assert_array_equal(S_result.todense(),S_expected.todense()) - def test_user_aggregation(self): - """check that the sa_interpolation accepts user-defined aggregates""" +# def test_user_aggregation(self): +# """check that the sa_interpolation accepts user-defined aggregates""" +# +# user_cases = [] +# +# #simple 1d example w/ two aggregates +# A = poisson( (6,), format='csr') +# AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) +# candidates = ones((6,1)) +# user_cases.append((A,AggOp,candidates)) +# +# #simple 1d example w/ two aggregates (not all nodes are aggregated) +# A = poisson( (6,), format='csr') +# AggOp = csr_matrix((ones(4),array([0,0,1,1]),array([0,1,1,2,3,3,4])),shape=(6,2)) +# candidates = ones((6,1)) +# user_cases.append((A,AggOp,candidates)) +# +# for A,AggOp,candidates in user_cases: +# T,coarse_candidates_result = sa_fit_candidates(AggOp,candidates) +# +# P_result = sa_interpolation(A,candidates,omega=4.0/3.0,AggOp=AggOp)[0] +# P_expected = sa_smoothed_prolongator(A,T,epsilon=0.0,omega=4.0/3.0) +# +# assert_almost_equal(P_result.todense(),P_expected.todense()) - user_cases = [] - #simple 1d example w/ two aggregates - A = poisson( (6,), format='csr') - AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) - candidates = ones((6,1)) - user_cases.append((A,AggOp,candidates)) - #simple 1d example w/ two aggregates (not all nodes are aggregated) - A = poisson( (6,), format='csr') - AggOp = csr_matrix((ones(4),array([0,0,1,1]),array([0,1,1,2,3,3,4])),shape=(6,2)) - candidates = ones((6,1)) - user_cases.append((A,AggOp,candidates)) - - for A,AggOp,candidates in user_cases: - T,coarse_candidates_result = sa_fit_candidates(AggOp,candidates) - - P_result = sa_interpolation(A,candidates,omega=4.0/3.0,AggOp=AggOp)[0] - P_expected = sa_smoothed_prolongator(A,T,epsilon=0.0,omega=4.0/3.0) - - assert_almost_equal(P_result.todense(),P_expected.todense()) - - - class TestFitCandidates(TestCase): def setUp(self): self.cases = [] @@ -191,8 +186,8 @@ def test_basic(self): """check that method converges at a reasonable rate""" - for A,candidates in self.cases: - ml = smoothed_aggregation_solver(A,candidates,max_coarse=10,max_levels=10) + for A,B in self.cases: + ml = smoothed_aggregation_solver(A,B,max_coarse=10,max_levels=10) numpy.random.seed(0) #make tests repeatable @@ -221,7 +216,7 @@ #TODO force 2 level method and check that result is the same #sa1 = smoothed_aggregation_solver(A, B, max_levels=2, rescale=False) - sa2 = smoothed_aggregation_solver(D*A*D, D_inv * B, max_levels=2, rescale=True) + sa2 = smoothed_aggregation_solver(D*A*D, D_inv * B, max_levels=2) #assert_almost_equal( sa2.Ps[0], sa1.Ps[0] x_sol,residuals = sa2.solve(b,x0=x,maxiter=10,tol=1e-12,return_residuals=True) @@ -251,16 +246,15 @@ # note that this method only tests the current implementation, not # all possible implementations -def reference_sa_constant_interpolation(A,epsilon): - S = sa_strong_connections(A,epsilon) - S = array_split(S.indices,S.indptr[1:-1]) +def reference_sa_standard_aggregation(C): + S = array_split(C.indices,C.indptr[1:-1]) - n = A.shape[0] + n = C.shape[0] R = set(range(n)) j = 0 - aggregates = empty(n,dtype=A.indices.dtype) + aggregates = empty(n,dtype=C.indices.dtype) aggregates[:] = -1 # Pass #1 From scipy-svn at scipy.org Thu Jan 24 17:11:49 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 24 Jan 2008 16:11:49 -0600 (CST) Subject: [Scipy-svn] r3860 - in trunk/scipy: sandbox/multigrid sparse sparse/tests Message-ID: <20080124221149.BDDD839C100@new.scipy.org> Author: wnbell Date: 2008-01-24 16:11:36 -0600 (Thu, 24 Jan 2008) New Revision: 3860 Modified: trunk/scipy/sandbox/multigrid/utils.py trunk/scipy/sparse/__init__.py trunk/scipy/sparse/base.py trunk/scipy/sparse/bsr.py trunk/scipy/sparse/compressed.py trunk/scipy/sparse/spfuncs.py trunk/scipy/sparse/tests/test_base.py trunk/scipy/sparse/tests/test_spfuncs.py Log: added .diagonal() function to sparse matrices Modified: trunk/scipy/sandbox/multigrid/utils.py =================================================================== --- trunk/scipy/sandbox/multigrid/utils.py 2008-01-24 21:11:16 UTC (rev 3859) +++ trunk/scipy/sandbox/multigrid/utils.py 2008-01-24 22:11:36 UTC (rev 3860) @@ -7,8 +7,7 @@ rand, zeros, ones, empty, asmatrix, dot from scipy.linalg import norm, eigvals from scipy.sparse import isspmatrix, isspmatrix_csr, isspmatrix_csc, \ - isspmatrix_bsr, csr_matrix, csc_matrix, bsr_matrix, coo_matrix, \ - extract_diagonal + isspmatrix_bsr, csr_matrix, csc_matrix, bsr_matrix, coo_matrix from scipy.sparse.sputils import upcast @@ -130,7 +129,7 @@ #TODO integrate into SciPy? if isspmatrix(A): - return extract_diagonal(A) + return A.diagonal() else: return csr_matrix((asarray(A),arange(len(A)),arange(len(A)+1)),(len(A),len(A))) Modified: trunk/scipy/sparse/__init__.py =================================================================== --- trunk/scipy/sparse/__init__.py 2008-01-24 21:11:16 UTC (rev 3859) +++ trunk/scipy/sparse/__init__.py 2008-01-24 22:11:36 UTC (rev 3860) @@ -12,7 +12,7 @@ from bsr import * from construct import * -from spfuncs import * +#from spfuncs import * __all__ = filter(lambda s:not s.startswith('_'),dir()) from scipy.testing.pkgtester import Tester Modified: trunk/scipy/sparse/base.py =================================================================== --- trunk/scipy/sparse/base.py 2008-01-24 21:11:16 UTC (rev 3859) +++ trunk/scipy/sparse/base.py 2008-01-24 22:11:36 UTC (rev 3860) @@ -459,6 +459,12 @@ return self.sum(None) * 1.0 / (self.shape[0]*self.shape[1]) else: raise ValueError, "axis out of bounds" + + def diagonal(self): + """Returns the main diagonal of the matrix + """ + #TODO support k != 0 + return self.tocsr().diagonal() def setdiag(self, values, k=0): """Fills the diagonal elements {a_ii} with the values from the Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-01-24 21:11:16 UTC (rev 3859) +++ trunk/scipy/sparse/bsr.py 2008-01-24 22:11:36 UTC (rev 3860) @@ -251,6 +251,16 @@ (_formats[format][1],) ) + def diagonal(self): + """Returns the main diagonal of the matrix + """ + M,N = self.shape + R,C = self.blocksize + y = empty( min(M,N), dtype=upcast(self.dtype) ) + sparsetools.bsr_diagonal(M/R, N/C, R, C, \ + self.indptr, self.indices, ravel(self.data), y) + return y + ########################## # NotImplemented methods # ########################## Modified: trunk/scipy/sparse/compressed.py =================================================================== --- trunk/scipy/sparse/compressed.py 2008-01-24 21:11:16 UTC (rev 3859) +++ trunk/scipy/sparse/compressed.py 2008-01-24 22:11:36 UTC (rev 3860) @@ -370,6 +370,14 @@ def getdata(self, ind): return self.data[ind] + + def diagonal(self): + """Returns the main diagonal of the matrix + """ + fn = getattr(sparsetools, self.format + "_diagonal") + y = empty( min(self.shape), dtype=upcast(self.dtype) ) + fn(self.shape[0], self.shape[1], self.indptr, self.indices, self.data, y) + return y def sum(self, axis=None): """Sum the matrix over the given axis. If the axis is None, sum Modified: trunk/scipy/sparse/spfuncs.py =================================================================== --- trunk/scipy/sparse/spfuncs.py 2008-01-24 21:11:16 UTC (rev 3859) +++ trunk/scipy/sparse/spfuncs.py 2008-01-24 22:11:36 UTC (rev 3860) @@ -1,7 +1,7 @@ """ Functions that operate on sparse matrices """ -__all__ = ['extract_diagonal','count_blocks','estimate_blocksize'] +__all__ = ['count_blocks','estimate_blocksize'] from numpy import empty, ravel @@ -15,23 +15,26 @@ from sparsetools import csr_count_blocks def extract_diagonal(A): - """extract_diagonal(A) returns the main diagonal of A.""" - #TODO extract k-th diagonal - if isspmatrix_csr(A) or isspmatrix_csc(A): - fn = getattr(sparsetools, A.format + "_diagonal") - y = empty( min(A.shape), dtype=upcast(A.dtype) ) - fn(A.shape[0],A.shape[1],A.indptr,A.indices,A.data,y) - return y - elif isspmatrix_bsr(A): - M,N = A.shape - R,C = A.blocksize - y = empty( min(M,N), dtype=upcast(A.dtype) ) - fn = sparsetools.bsr_diagonal(M/R, N/C, R, C, \ - A.indptr, A.indices, ravel(A.data), y) - return y - else: - return extract_diagonal(csr_matrix(A)) + raise NotImplementedError('use .diagonal() instead') +#def extract_diagonal(A): +# """extract_diagonal(A) returns the main diagonal of A.""" +# #TODO extract k-th diagonal +# if isspmatrix_csr(A) or isspmatrix_csc(A): +# fn = getattr(sparsetools, A.format + "_diagonal") +# y = empty( min(A.shape), dtype=upcast(A.dtype) ) +# fn(A.shape[0],A.shape[1],A.indptr,A.indices,A.data,y) +# return y +# elif isspmatrix_bsr(A): +# M,N = A.shape +# R,C = A.blocksize +# y = empty( min(M,N), dtype=upcast(A.dtype) ) +# fn = sparsetools.bsr_diagonal(M/R, N/C, R, C, \ +# A.indptr, A.indices, ravel(A.data), y) +# return y +# else: +# return extract_diagonal(csr_matrix(A)) + def estimate_blocksize(A,efficiency=0.7): """Attempt to determine the blocksize of a sparse matrix Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-01-24 21:11:16 UTC (rev 3859) +++ trunk/scipy/sparse/tests/test_base.py 2008-01-24 22:11:36 UTC (rev 3860) @@ -17,14 +17,14 @@ import numpy from numpy import arange, zeros, array, dot, ones, matrix, asmatrix, \ - asarray, vstack, ndarray, kron, transpose + asarray, vstack, ndarray, kron, transpose, diag import random from scipy.testing import * from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ coo_matrix, lil_matrix, dia_matrix, bsr_matrix, \ - extract_diagonal, speye, spkron, SparseEfficiencyWarning + speye, spkron, SparseEfficiencyWarning from scipy.sparse.sputils import supported_dtypes from scipy.linsolve import splu @@ -74,8 +74,28 @@ A = matrix([[-1, 0, 17],[0, -5, 0],[1, -4, 0],[0,0,0]],'d') assert_equal(-A,(-self.spmatrix(A)).todense()) + + def test_diagonal(self): + """Does the matrix's .diagonal() method work? + """ + mats = [] + mats.append( [[1,0,2]] ) + mats.append( [[1],[0],[2]] ) + mats.append( [[0,1],[0,2],[0,3]] ) + mats.append( [[0,0,1],[0,0,2],[0,3,0]] ) + + mats.append( kron(mats[0],[[1,2]]) ) + mats.append( kron(mats[0],[[1],[2]]) ) + mats.append( kron(mats[1],[[1,2],[3,4]]) ) + mats.append( kron(mats[2],[[1,2],[3,4]]) ) + mats.append( kron(mats[3],[[1,2],[3,4]]) ) + mats.append( kron(mats[3],[[1,2,3,4]]) ) + + for m in mats: + assert_equal(self.spmatrix(m).diagonal(),diag(m)) + def test_sum(self): - """Does the matrix's sum(,axis=0) method work? + """Does the matrix's .sum(axis=...) method work? """ assert_array_equal(self.dat.sum(), self.datsp.sum()) assert_array_equal(self.dat.sum(axis=None), self.datsp.sum(axis=None)) @@ -83,7 +103,7 @@ assert_array_equal(self.dat.sum(axis=1), self.datsp.sum(axis=1)) def test_mean(self): - """Does the matrix's mean(,axis=0) method work? + """Does the matrix's .mean(axis=...) method work? """ assert_array_equal(self.dat.mean(), self.datsp.mean()) assert_array_equal(self.dat.mean(axis=None), self.datsp.mean(axis=None)) Modified: trunk/scipy/sparse/tests/test_spfuncs.py =================================================================== --- trunk/scipy/sparse/tests/test_spfuncs.py 2008-01-24 21:11:16 UTC (rev 3859) +++ trunk/scipy/sparse/tests/test_spfuncs.py 2008-01-24 22:11:36 UTC (rev 3860) @@ -1,4 +1,4 @@ -from numpy import array, kron, diag, matrix +from numpy import array, kron, matrix, diag from scipy.testing import * from scipy.sparse.spfuncs import * @@ -49,34 +49,6 @@ - def test_extract_diagonal(self): - mats = [] - mats.append( [[1,0,2]] ) - mats.append( [[1],[0],[2]] ) - mats.append( [[0,1],[0,2],[0,3]] ) - mats.append( [[0,0,1],[0,0,2],[0,3,0]] ) - - mats.append( kron(mats[0],[[1,2]]) ) - mats.append( kron(mats[0],[[1],[2]]) ) - mats.append( kron(mats[1],[[1,2],[3,4]]) ) - mats.append( kron(mats[2],[[1,2],[3,4]]) ) - mats.append( kron(mats[3],[[1,2],[3,4]]) ) - - for m in mats: - expected = diag(m) - assert_equal(extract_diagonal(m),expected) - assert_equal(extract_diagonal(csr_matrix(m)),expected) - assert_equal(extract_diagonal(csc_matrix(m)),expected) - - for m in mats: - m = array(m) - M,N = m.shape - expected = diag(m) - for R in range(1,M+1): - for C in range(1,N+1): - if M % R == 0 and N % C == 0: - result = extract_diagonal( bsr_matrix(m,blocksize=(R,C)) ) - assert_equal(result,expected) def test_estimate_blocksize(self): From scipy-svn at scipy.org Fri Jan 25 15:01:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 25 Jan 2008 14:01:12 -0600 (CST) Subject: [Scipy-svn] r3861 - in trunk/scipy: . linalg linalg/tests sandbox/arpack/tests splinalg splinalg/isolve splinalg/isolve/tests Message-ID: <20080125200112.6A78A39C091@new.scipy.org> Author: wnbell Date: 2008-01-25 14:00:52 -0600 (Fri, 25 Jan 2008) New Revision: 3861 Added: trunk/scipy/splinalg/ trunk/scipy/splinalg/eigen/ trunk/scipy/splinalg/isolve/ trunk/scipy/splinalg/isolve/iterative.py trunk/scipy/splinalg/isolve/iterative/ trunk/scipy/splinalg/isolve/tests/ trunk/scipy/splinalg/isolve/tests/test_iterative.py Removed: trunk/scipy/linalg/iterative.py trunk/scipy/linalg/iterative/ trunk/scipy/linalg/tests/test_iterative.py Modified: trunk/scipy/linalg/__init__.py trunk/scipy/linalg/setup.py trunk/scipy/sandbox/arpack/tests/test_speigs.py trunk/scipy/setup.py Log: moved iterative solvers to splinalg.isolve Modified: trunk/scipy/linalg/__init__.py =================================================================== --- trunk/scipy/linalg/__init__.py 2008-01-24 22:11:36 UTC (rev 3860) +++ trunk/scipy/linalg/__init__.py 2008-01-25 20:00:52 UTC (rev 3861) @@ -1,5 +1,5 @@ # -# linalg - Linear algebra routines +# linalg - Dense Linear Algebra routines # from info import __doc__ @@ -9,8 +9,11 @@ from decomp import * from matfuncs import * from blas import * -from iterative import * +#from iterative import * +# TODO remove this +from scipy.splinalg.isolve import * + __all__ = filter(lambda s:not s.startswith('_'),dir()) from numpy.dual import register_func Deleted: trunk/scipy/linalg/iterative.py =================================================================== --- trunk/scipy/linalg/iterative.py 2008-01-24 22:11:36 UTC (rev 3860) +++ trunk/scipy/linalg/iterative.py 2008-01-25 20:00:52 UTC (rev 3861) @@ -1,807 +0,0 @@ -## Automatically adapted for scipy Oct 18, 2005 by - - -# Iterative methods using reverse-communication raw material -# These methods solve -# Ax = b for x - -# where A must have A.matvec(x,*args) defined -# or be a numeric array - - -__all__ = ['bicg','bicgstab','cg','cgs','gmres','qmr'] -from scipy.linalg import _iterative -import numpy as sb -import copy - -try: - False, True -except NameError: - False, True = 0, 1 - -_type_conv = {'f':'s', 'd':'d', 'F':'c', 'D':'z'} - -_coerce_rules = {('f','f'):'f', ('f','d'):'d', ('f','F'):'F', - ('f','D'):'D', ('d','f'):'d', ('d','d'):'d', - ('d','F'):'D', ('d','D'):'D', ('F','f'):'F', - ('F','d'):'D', ('F','F'):'F', ('F','D'):'D', - ('D','f'):'D', ('D','d'):'D', ('D','F'):'D', - ('D','D'):'D'} - -class get_matvec: - methname = 'matvec' - def __init__(self, obj, *args): - self.obj = obj - self.args = args - if isinstance(obj, sb.matrix): - self.callfunc = self.type1m - return - if isinstance(obj, sb.ndarray): - self.callfunc = self.type1 - return - meth = getattr(obj,self.methname,None) - if not callable(meth): - raise ValueError, "Object must be an array "\ - "or have a callable %s attribute." % (self.methname,) - - self.obj = meth - self.callfunc = self.type2 - - def __call__(self, x): - return self.callfunc(x) - - def type1(self, x): - return sb.dot(self.obj, x) - - def type1m(self, x): - return sb.dot(self.obj.A, x) - - def type2(self, x): - return self.obj(x,*self.args) - -class get_rmatvec(get_matvec): - methname = 'rmatvec' - def type1(self, x): - return sb.dot(x, self.obj) - def type1m(self, x): - return sb.dot(x, self.obj.A) - -class get_psolve: - methname = 'psolve' - def __init__(self, obj, *args): - self.obj = obj - self.args = args - meth = getattr(obj,self.methname,None) - if meth is None: # no preconditiong available - self.callfunc = self.type1 - return - - if not callable(meth): - raise ValueError, "Preconditioning method %s "\ - "must be callable." % (self.methname,) - - self.obj = meth - self.callfunc = self.type2 - - def __call__(self, x): - return self.callfunc(x) - - def type1(self, x): - return x - - def type2(self, x): - return self.obj(x,*self.args) - -class get_rpsolve(get_psolve): - methname = 'rpsolve' - -class get_psolveq(get_psolve): - - def __call__(self, x, which): - return self.callfunc(x, which) - - def type1(self, x, which): - return x - - def type2(self, x, which): - return self.obj(x,which,*self.args) - -class get_rpsolveq(get_psolveq): - methname = 'rpsolve' - -def bicg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): - """Use BIConjugate Gradient iteration to solve A x = b - - Inputs: - - A -- An array or an object with matvec(x) and rmatvec(x) methods - to represent A * x and A^H * x respectively. May also have - psolve(b) and rpsolve(b) methods for representing solutions - to the preconditioning equations M * x = b and - M^H * x = b respectively. - b -- An n-length vector - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ - b = sb.asarray(b)+0.0 - n = len(b) - if maxiter is None: - maxiter = n*10 - - if x0 is None: - x = sb.zeros(n) - else: - x = copy.copy(x0) - - if xtype is None: - try: - atyp = A.dtype.char - except AttributeError: - atyp = None - if atyp is None: - atyp = A.matvec(x).dtype.char - typ = _coerce_rules[b.dtype.char,atyp] - elif xtype == 0: - typ = b.dtype.char - else: - typ = xtype - if typ not in 'fdFD': - raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" - - x = sb.asarray(x,typ) - b = sb.asarray(b,typ) - - matvec, psolve, rmatvec, rpsolve = (None,)*4 - ltr = _type_conv[typ] - revcom = _iterative.__dict__[ltr+'bicgrevcom'] - stoptest = _iterative.__dict__[ltr+'stoptest2'] - - resid = tol - ndx1 = 1 - ndx2 = -1 - work = sb.zeros(6*n,typ) - ijob = 1 - info = 0 - ftflag = True - bnrm2 = -1.0 - iter_ = maxiter - while True: - olditer = iter_ - x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ - revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) - if callback is not None and iter_ > olditer: - callback(x) - slice1 = slice(ndx1-1, ndx1-1+n) - slice2 = slice(ndx2-1, ndx2-1+n) - if (ijob == -1): - break - elif (ijob == 1): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(work[slice1]) - elif (ijob == 2): - if rmatvec is None: - rmatvec = get_rmatvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*rmatvec(work[slice1]) - elif (ijob == 3): - if psolve is None: - psolve = get_psolve(A) - work[slice1] = psolve(work[slice2]) - elif (ijob == 4): - if rpsolve is None: - rpsolve = get_rpsolve(A) - work[slice1] = rpsolve(work[slice2]) - elif (ijob == 5): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(x) - elif (ijob == 6): - if ftflag: - info = -1 - ftflag = False - bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) - ijob = 2 - - return x, info - - -def bicgstab(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): - """Use BIConjugate Gradient STABilized iteration to solve A x = b - - Inputs: - - A -- An array or an object with a matvec(x) method - to represent A * x. May also have a psolve(b) methods for - representing solution to the preconditioning equation - M * x = b. - b -- An n-length vector - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ - b = sb.asarray(b)+0.0 - n = len(b) - if maxiter is None: - maxiter = n*10 - - if x0 is None: - x = sb.zeros(n) - else: - x = copy.copy(x0) - - - if xtype is None: - try: - atyp = A.dtype.char - except AttributeError: - atyp = None - if atyp is None: - atyp = A.matvec(x).dtype.char - typ = _coerce_rules[b.dtype.char,atyp] - elif xtype == 0: - typ = b.dtype.char - else: - typ = xtype - if typ not in 'fdFD': - raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" - - x = sb.asarray(x,typ) - b = sb.asarray(b,typ) - - matvec, psolve = (None,)*2 - ltr = _type_conv[typ] - revcom = _iterative.__dict__[ltr+'bicgstabrevcom'] - stoptest = _iterative.__dict__[ltr+'stoptest2'] - - resid = tol - ndx1 = 1 - ndx2 = -1 - work = sb.zeros(7*n,typ) - ijob = 1 - info = 0 - ftflag = True - bnrm2 = -1.0 - iter_ = maxiter - while True: - olditer = iter_ - x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ - revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) - if callback is not None and iter_ > olditer: - callback(x) - slice1 = slice(ndx1-1, ndx1-1+n) - slice2 = slice(ndx2-1, ndx2-1+n) - if (ijob == -1): - break - elif (ijob == 1): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(work[slice1]) - elif (ijob == 2): - if psolve is None: - psolve = get_psolve(A) - work[slice1] = psolve(work[slice2]) - elif (ijob == 3): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(x) - elif (ijob == 4): - if ftflag: - info = -1 - ftflag = False - bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) - ijob = 2 - - return x, info - - -def cg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): - """Use Conjugate Gradient iteration to solve A x = b (A^H = A) - - Inputs: - - A -- An array or an object with a matvec(x) method - to represent A * x. May also have a psolve(b) methods for - representing solution to the preconditioning equation - M * x = b. - b -- An n-length vector - - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ - b = sb.asarray(b)+0.0 - n = len(b) - if maxiter is None: - maxiter = n*10 - - if x0 is None: - x = sb.zeros(n) - else: - x = copy.copy(x0) - - - if xtype is None: - try: - atyp = A.dtype.char - except AttributeError: - atyp = None - if atyp is None: - atyp = A.matvec(x).dtype.char - typ = _coerce_rules[b.dtype.char,atyp] - elif xtype == 0: - typ = b.dtype.char - else: - typ = xtype - if typ not in 'fdFD': - raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" - - x = sb.asarray(x,typ) - b = sb.asarray(b,typ) - - matvec, psolve = (None,)*2 - ltr = _type_conv[typ] - revcom = _iterative.__dict__[ltr+'cgrevcom'] - stoptest = _iterative.__dict__[ltr+'stoptest2'] - - resid = tol - ndx1 = 1 - ndx2 = -1 - work = sb.zeros(4*n,typ) - ijob = 1 - info = 0 - ftflag = True - bnrm2 = -1.0 - iter_ = maxiter - while True: - olditer = iter_ - x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ - revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) - if callback is not None and iter_ > olditer: - callback(x) - slice1 = slice(ndx1-1, ndx1-1+n) - slice2 = slice(ndx2-1, ndx2-1+n) - if (ijob == -1): - break - elif (ijob == 1): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(work[slice1]) - elif (ijob == 2): - if psolve is None: - psolve = get_psolve(A) - work[slice1] = psolve(work[slice2]) - elif (ijob == 3): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(x) - elif (ijob == 4): - if ftflag: - info = -1 - ftflag = False - bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) - ijob = 2 - - return x, info - - -def cgs(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): - """Use Conjugate Gradient Squared iteration to solve A x = b - - Inputs: - - A -- An array or an object with a matvec(x) method - to represent A * x. May also have a psolve(b) methods for - representing solution to the preconditioning equation - M * x = b. - b -- An n-length vector - - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ - b = sb.asarray(b) + 0.0 - n = len(b) - if maxiter is None: - maxiter = n*10 - - if x0 is None: - x = sb.zeros(n) - else: - x = copy.copy(x0) - - if xtype is None: - try: - atyp = A.dtype.char - except AttributeError: - atyp = None - if atyp is None: - atyp = A.matvec(x).dtype.char - typ = _coerce_rules[b.dtype.char,atyp] - elif xtype == 0: - typ = b.dtype.char - else: - typ = xtype - if typ not in 'fdFD': - raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" - - x = sb.asarray(x,typ) - b = sb.asarray(b,typ) - - matvec, psolve = (None,)*2 - ltr = _type_conv[typ] - revcom = _iterative.__dict__[ltr+'cgsrevcom'] - stoptest = _iterative.__dict__[ltr+'stoptest2'] - - resid = tol - ndx1 = 1 - ndx2 = -1 - work = sb.zeros(7*n,typ) - ijob = 1 - info = 0 - ftflag = True - bnrm2 = -1.0 - iter_ = maxiter - while True: - olditer = iter_ - x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ - revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) - if callback is not None and iter_ > olditer: - callback(x) - slice1 = slice(ndx1-1, ndx1-1+n) - slice2 = slice(ndx2-1, ndx2-1+n) - if (ijob == -1): - break - elif (ijob == 1): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(work[slice1]) - elif (ijob == 2): - if psolve is None: - psolve = get_psolve(A) - work[slice1] = psolve(work[slice2]) - elif (ijob == 3): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(x) - elif (ijob == 4): - if ftflag: - info = -1 - ftflag = False - bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) - ijob = 2 - - return x, info - - -def gmres(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None, callback=None): - """Use Generalized Minimal RESidual iteration to solve A x = b - - Inputs: - - A -- An array or an object with a matvec(x) method - to represent A * x. May also have a psolve(b) methods for - representing solution to the preconditioning equation - M * x = b. - b -- An n-length vector - - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - restrt -- (n) When to restart (change this to get faster performance -- but - may not converge). - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ - b = sb.asarray(b)+0.0 - n = len(b) - if maxiter is None: - maxiter = n*10 - - if x0 is None: - x = sb.zeros(n) - else: - x = copy.copy(x0) - - if xtype is None: - try: - atyp = A.dtype.char - except AttributeError: - atyp = A.matvec(x).dtype.char - typ = _coerce_rules[b.dtype.char,atyp] - elif xtype == 0: - typ = b.dtype.char - else: - typ = xtype - if typ not in 'fdFD': - raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" - - x = sb.asarray(x,typ) - b = sb.asarray(b,typ) - - matvec, psolve = (None,)*2 - ltr = _type_conv[typ] - revcom = _iterative.__dict__[ltr+'gmresrevcom'] - stoptest = _iterative.__dict__[ltr+'stoptest2'] - - if restrt is None: - restrt = n - resid = tol - ndx1 = 1 - ndx2 = -1 - work = sb.zeros((6+restrt)*n,typ) - work2 = sb.zeros((restrt+1)*(2*restrt+2),typ) - ijob = 1 - info = 0 - ftflag = True - bnrm2 = -1.0 - iter_ = maxiter - while True: - olditer = iter_ - x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ - revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) - if callback is not None and iter_ > olditer: - callback(x) - slice1 = slice(ndx1-1, ndx1-1+n) - slice2 = slice(ndx2-1, ndx2-1+n) - if (ijob == -1): - break - elif (ijob == 1): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(x) - elif (ijob == 2): - if psolve is None: - psolve = get_psolve(A) - work[slice1] = psolve(work[slice2]) - elif (ijob == 3): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(work[slice1]) - elif (ijob == 4): - if ftflag: - info = -1 - ftflag = False - bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) - ijob = 2 - - return x, info - - -def qmr(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): - """Use Quasi-Minimal Residual iteration to solve A x = b - - Inputs: - - A -- An array or an object with matvec(x) and rmatvec(x) methods - to represent A * x and A^H * x respectively. May also have - psolve(b,) and rpsolve(b,) methods for - representing solutions to the preconditioning equations - M * x = b and M^H * x = b respectively. The argument - may be given to specify 'left' or 'right' preconditioning. - b -- An n-length vector - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ - b = sb.asarray(b)+0.0 - n = len(b) - if maxiter is None: - maxiter = n*10 - - if x0 is None: - x = sb.zeros(n) - else: - x = copy.copy(x0) - - if xtype is None: - try: - atyp = A.dtype.char - except AttributeError: - atyp = None - if atyp is None: - atyp = A.matvec(x).dtype.char - typ = _coerce_rules[b.dtype.char,atyp] - elif xtype == 0: - typ = b.dtype.char - else: - typ = xtype - if typ not in 'fdFD': - raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" - - x = sb.asarray(x,typ) - b = sb.asarray(b,typ) - - - matvec, psolve, rmatvec, rpsolve = (None,)*4 - ltr = _type_conv[typ] - revcom = _iterative.__dict__[ltr+'qmrrevcom'] - stoptest = _iterative.__dict__[ltr+'stoptest2'] - - resid = tol - ndx1 = 1 - ndx2 = -1 - work = sb.zeros(11*n,typ) - ijob = 1 - info = 0 - ftflag = True - bnrm2 = -1.0 - iter_ = maxiter - while True: - olditer = iter_ - x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ - revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) - if callback is not None and iter_ > olditer: - callback(x) - slice1 = slice(ndx1-1, ndx1-1+n) - slice2 = slice(ndx2-1, ndx2-1+n) - if (ijob == -1): - break - elif (ijob == 1): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(work[slice1]) - elif (ijob == 2): - if rmatvec is None: - rmatvec = get_rmatvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*rmatvec(work[slice1]) - elif (ijob == 3): - if psolve is None: - psolve = get_psolveq(A) - work[slice1] = psolve(work[slice2],'left') - elif (ijob == 4): - if psolve is None: - psolve = get_psolveq(A) - work[slice1] = psolve(work[slice2],'right') - elif (ijob == 5): - if rpsolve is None: - rpsolve = get_rpsolveq(A) - work[slice1] = rpsolve(work[slice2],'left') - elif (ijob == 6): - if rpsolve is None: - rpsolve = get_rpsolveq(A) - work[slice1] = rpsolve(work[slice2],'right') - elif (ijob == 7): - if matvec is None: - matvec = get_matvec(A) - work[slice2] *= sclr2 - work[slice2] += sclr1*matvec(x) - elif (ijob == 8): - if ftflag: - info = -1 - ftflag = False - bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) - ijob = 2 - - return x, info Modified: trunk/scipy/linalg/setup.py =================================================================== --- trunk/scipy/linalg/setup.py 2008-01-24 22:11:36 UTC (rev 3860) +++ trunk/scipy/linalg/setup.py 2008-01-25 20:00:52 UTC (rev 3861) @@ -183,23 +183,23 @@ extra_info = lapack_opt ) - # iterative methods - methods = ['BiCGREVCOM.f.src', - 'BiCGSTABREVCOM.f.src', - 'CGREVCOM.f.src', - 'CGSREVCOM.f.src', -# 'ChebyREVCOM.f.src', - 'GMRESREVCOM.f.src', -# 'JacobiREVCOM.f.src', - 'QMRREVCOM.f.src', -# 'SORREVCOM.f.src' - ] - Util = ['STOPTEST2.f.src','getbreak.f.src'] - sources = Util + methods + ['_iterative.pyf.src'] - config.add_extension('_iterative', - sources = [join('iterative',x) for x in sources], - extra_info = lapack_opt - ) +# # iterative methods +# methods = ['BiCGREVCOM.f.src', +# 'BiCGSTABREVCOM.f.src', +# 'CGREVCOM.f.src', +# 'CGSREVCOM.f.src', +## 'ChebyREVCOM.f.src', +# 'GMRESREVCOM.f.src', +## 'JacobiREVCOM.f.src', +# 'QMRREVCOM.f.src', +## 'SORREVCOM.f.src' +# ] +# Util = ['STOPTEST2.f.src','getbreak.f.src'] +# sources = Util + methods + ['_iterative.pyf.src'] +# config.add_extension('_iterative', +# sources = [join('iterative',x) for x in sources], +# extra_info = lapack_opt +# ) config.add_data_dir('tests') Deleted: trunk/scipy/linalg/tests/test_iterative.py =================================================================== --- trunk/scipy/linalg/tests/test_iterative.py 2008-01-24 22:11:36 UTC (rev 3860) +++ trunk/scipy/linalg/tests/test_iterative.py 2008-01-25 20:00:52 UTC (rev 3861) @@ -1,83 +0,0 @@ -#!/usr/bin/env python -# -# Created by: Ed Schofield, Jan 2007 -# -""" Test functions for the linalg.iterative module -""" -__usage__ = """ -Build linalg: - python setup_linalg.py build -Run tests if scipy is installed: - python -c 'import scipy;scipy.linalg.test()' -Run tests if linalg is not installed: - python tests/test_iterative.py [] -""" - -import sys - -from numpy import zeros, dot, diag, ones -from scipy.testing import * -from numpy.random import rand -#from numpy import arange, add, array, dot, zeros, identity, conjugate, transpose - -from scipy.linalg import iterative, norm, cg, cgs, bicg, bicgstab, gmres, qmr - - -def callback(x): - global A, b - res = b-dot(A,x) - #print "||A.x - b|| = " + str(norm(dot(A,x)-b)) - -class TestIterativeSolvers(TestCase): - def __init__(self, *args, **kwds): - TestCase.__init__(self, *args, **kwds) - self.setUp() - def setUp (self): - global A, b - n = 10 - self.tol = 1e-5 - self.x0 = zeros(n, float) - A = rand(n, n)+diag(4*ones(n)) - self.A = 0.5 * (A+A.T) - A = self.A - self.b = rand(n) - b = self.b - - def test_cg(self): - bx0 = self.x0.copy() - x, info = cg(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol - - def test_bicg(self): - bx0 = self.x0.copy() - x, info = bicg(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol - - def test_cgs(self): - bx0 = self.x0.copy() - x, info = cgs(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol - - def test_bicgstab(self): - bx0 = self.x0.copy() - x, info = bicgstab(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol - - def test_gmres(self): - bx0 = self.x0.copy() - x, info = gmres(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol - - def test_qmr(self): - bx0 = self.x0.copy() - x, info = qmr(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol - -if __name__ == "__main__": - nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/arpack/tests/test_speigs.py =================================================================== --- trunk/scipy/sandbox/arpack/tests/test_speigs.py 2008-01-24 22:11:36 UTC (rev 3860) +++ trunk/scipy/sandbox/arpack/tests/test_speigs.py 2008-01-25 20:00:52 UTC (rev 3861) @@ -22,7 +22,7 @@ vals = vals[uv_sortind] vecs = vecs[:,uv_sortind] - from scipy.linalg.iterative import get_matvec + from scipy.splinalg.isolve.iterative import get_matvec matvec = get_matvec(A) #= lambda x: N.asarray(A*x)[0] nev=4 Modified: trunk/scipy/setup.py =================================================================== --- trunk/scipy/setup.py 2008-01-24 22:11:36 UTC (rev 3860) +++ trunk/scipy/setup.py 2008-01-25 20:00:52 UTC (rev 3861) @@ -18,6 +18,7 @@ config.add_subpackage('signal') config.add_subpackage('sparse') config.add_subpackage('special') + config.add_subpackage('splinalg') config.add_subpackage('stats') config.add_subpackage('ndimage') config.add_subpackage('stsci') Copied: trunk/scipy/splinalg/isolve/iterative (from rev 3860, trunk/scipy/linalg/iterative) Copied: trunk/scipy/splinalg/isolve/iterative.py (from rev 3860, trunk/scipy/linalg/iterative.py) =================================================================== --- trunk/scipy/linalg/iterative.py 2008-01-24 22:11:36 UTC (rev 3860) +++ trunk/scipy/splinalg/isolve/iterative.py 2008-01-25 20:00:52 UTC (rev 3861) @@ -0,0 +1,808 @@ +## Automatically adapted for scipy Oct 18, 2005 by + + +# Iterative methods using reverse-communication raw material +# These methods solve +# Ax = b for x + +# where A must have A.matvec(x,*args) defined +# or be a numeric array + + +__all__ = ['bicg','bicgstab','cg','cgs','gmres','qmr'] + +import _iterative +import numpy as sb +import copy + +try: + False, True +except NameError: + False, True = 0, 1 + +_type_conv = {'f':'s', 'd':'d', 'F':'c', 'D':'z'} + +_coerce_rules = {('f','f'):'f', ('f','d'):'d', ('f','F'):'F', + ('f','D'):'D', ('d','f'):'d', ('d','d'):'d', + ('d','F'):'D', ('d','D'):'D', ('F','f'):'F', + ('F','d'):'D', ('F','F'):'F', ('F','D'):'D', + ('D','f'):'D', ('D','d'):'D', ('D','F'):'D', + ('D','D'):'D'} + +class get_matvec: + methname = 'matvec' + def __init__(self, obj, *args): + self.obj = obj + self.args = args + if isinstance(obj, sb.matrix): + self.callfunc = self.type1m + return + if isinstance(obj, sb.ndarray): + self.callfunc = self.type1 + return + meth = getattr(obj,self.methname,None) + if not callable(meth): + raise ValueError, "Object must be an array "\ + "or have a callable %s attribute." % (self.methname,) + + self.obj = meth + self.callfunc = self.type2 + + def __call__(self, x): + return self.callfunc(x) + + def type1(self, x): + return sb.dot(self.obj, x) + + def type1m(self, x): + return sb.dot(self.obj.A, x) + + def type2(self, x): + return self.obj(x,*self.args) + +class get_rmatvec(get_matvec): + methname = 'rmatvec' + def type1(self, x): + return sb.dot(x, self.obj) + def type1m(self, x): + return sb.dot(x, self.obj.A) + +class get_psolve: + methname = 'psolve' + def __init__(self, obj, *args): + self.obj = obj + self.args = args + meth = getattr(obj,self.methname,None) + if meth is None: # no preconditiong available + self.callfunc = self.type1 + return + + if not callable(meth): + raise ValueError, "Preconditioning method %s "\ + "must be callable." % (self.methname,) + + self.obj = meth + self.callfunc = self.type2 + + def __call__(self, x): + return self.callfunc(x) + + def type1(self, x): + return x + + def type2(self, x): + return self.obj(x,*self.args) + +class get_rpsolve(get_psolve): + methname = 'rpsolve' + +class get_psolveq(get_psolve): + + def __call__(self, x, which): + return self.callfunc(x, which) + + def type1(self, x, which): + return x + + def type2(self, x, which): + return self.obj(x,which,*self.args) + +class get_rpsolveq(get_psolveq): + methname = 'rpsolve' + +def bicg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): + """Use BIConjugate Gradient iteration to solve A x = b + + Inputs: + + A -- An array or an object with matvec(x) and rmatvec(x) methods + to represent A * x and A^H * x respectively. May also have + psolve(b) and rpsolve(b) methods for representing solutions + to the preconditioning equations M * x = b and + M^H * x = b respectively. + b -- An n-length vector + + Outputs: + + x -- The converged solution + info -- output result + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : illegal input or breakdown + + Optional Inputs: + + x0 -- (0) default starting guess. + tol -- (1e-5) relative tolerance to achieve + maxiter -- (10*n) maximum number of iterations + xtype -- The type of the result. If None, then it will be + determined from A.dtype.char and b. If A does not have a + typecode method then it will compute A.matvec(x0) to get a + typecode. To save the extra computation when A does not + have a typecode attribute use xtype=0 for the same type as + b or use xtype='f','d','F',or 'D' + callback -- an optional user-supplied function to call after each + iteration. It is called as callback(xk), where xk is the + current parameter vector. + """ + b = sb.asarray(b)+0.0 + n = len(b) + if maxiter is None: + maxiter = n*10 + + if x0 is None: + x = sb.zeros(n) + else: + x = copy.copy(x0) + + if xtype is None: + try: + atyp = A.dtype.char + except AttributeError: + atyp = None + if atyp is None: + atyp = A.matvec(x).dtype.char + typ = _coerce_rules[b.dtype.char,atyp] + elif xtype == 0: + typ = b.dtype.char + else: + typ = xtype + if typ not in 'fdFD': + raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" + + x = sb.asarray(x,typ) + b = sb.asarray(b,typ) + + matvec, psolve, rmatvec, rpsolve = (None,)*4 + ltr = _type_conv[typ] + revcom = _iterative.__dict__[ltr+'bicgrevcom'] + stoptest = _iterative.__dict__[ltr+'stoptest2'] + + resid = tol + ndx1 = 1 + ndx2 = -1 + work = sb.zeros(6*n,typ) + ijob = 1 + info = 0 + ftflag = True + bnrm2 = -1.0 + iter_ = maxiter + while True: + olditer = iter_ + x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ + revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) + if callback is not None and iter_ > olditer: + callback(x) + slice1 = slice(ndx1-1, ndx1-1+n) + slice2 = slice(ndx2-1, ndx2-1+n) + if (ijob == -1): + break + elif (ijob == 1): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(work[slice1]) + elif (ijob == 2): + if rmatvec is None: + rmatvec = get_rmatvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*rmatvec(work[slice1]) + elif (ijob == 3): + if psolve is None: + psolve = get_psolve(A) + work[slice1] = psolve(work[slice2]) + elif (ijob == 4): + if rpsolve is None: + rpsolve = get_rpsolve(A) + work[slice1] = rpsolve(work[slice2]) + elif (ijob == 5): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(x) + elif (ijob == 6): + if ftflag: + info = -1 + ftflag = False + bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) + ijob = 2 + + return x, info + + +def bicgstab(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): + """Use BIConjugate Gradient STABilized iteration to solve A x = b + + Inputs: + + A -- An array or an object with a matvec(x) method + to represent A * x. May also have a psolve(b) methods for + representing solution to the preconditioning equation + M * x = b. + b -- An n-length vector + + Outputs: + + x -- The converged solution + info -- output result + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : illegal input or breakdown + + Optional Inputs: + + x0 -- (0) default starting guess. + tol -- (1e-5) relative tolerance to achieve + maxiter -- (10*n) maximum number of iterations + xtype -- The type of the result. If None, then it will be + determined from A.dtype.char and b. If A does not have a + typecode method then it will compute A.matvec(x0) to get a + typecode. To save the extra computation when A does not + have a typecode attribute use xtype=0 for the same type as + b or use xtype='f','d','F',or 'D' + callback -- an optional user-supplied function to call after each + iteration. It is called as callback(xk), where xk is the + current parameter vector. + """ + b = sb.asarray(b)+0.0 + n = len(b) + if maxiter is None: + maxiter = n*10 + + if x0 is None: + x = sb.zeros(n) + else: + x = copy.copy(x0) + + + if xtype is None: + try: + atyp = A.dtype.char + except AttributeError: + atyp = None + if atyp is None: + atyp = A.matvec(x).dtype.char + typ = _coerce_rules[b.dtype.char,atyp] + elif xtype == 0: + typ = b.dtype.char + else: + typ = xtype + if typ not in 'fdFD': + raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" + + x = sb.asarray(x,typ) + b = sb.asarray(b,typ) + + matvec, psolve = (None,)*2 + ltr = _type_conv[typ] + revcom = _iterative.__dict__[ltr+'bicgstabrevcom'] + stoptest = _iterative.__dict__[ltr+'stoptest2'] + + resid = tol + ndx1 = 1 + ndx2 = -1 + work = sb.zeros(7*n,typ) + ijob = 1 + info = 0 + ftflag = True + bnrm2 = -1.0 + iter_ = maxiter + while True: + olditer = iter_ + x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ + revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) + if callback is not None and iter_ > olditer: + callback(x) + slice1 = slice(ndx1-1, ndx1-1+n) + slice2 = slice(ndx2-1, ndx2-1+n) + if (ijob == -1): + break + elif (ijob == 1): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(work[slice1]) + elif (ijob == 2): + if psolve is None: + psolve = get_psolve(A) + work[slice1] = psolve(work[slice2]) + elif (ijob == 3): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(x) + elif (ijob == 4): + if ftflag: + info = -1 + ftflag = False + bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) + ijob = 2 + + return x, info + + +def cg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): + """Use Conjugate Gradient iteration to solve A x = b (A^H = A) + + Inputs: + + A -- An array or an object with a matvec(x) method + to represent A * x. May also have a psolve(b) methods for + representing solution to the preconditioning equation + M * x = b. + b -- An n-length vector + + + Outputs: + + x -- The converged solution + info -- output result + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : illegal input or breakdown + + Optional Inputs: + + x0 -- (0) default starting guess. + tol -- (1e-5) relative tolerance to achieve + maxiter -- (10*n) maximum number of iterations + xtype -- The type of the result. If None, then it will be + determined from A.dtype.char and b. If A does not have a + typecode method then it will compute A.matvec(x0) to get a + typecode. To save the extra computation when A does not + have a typecode attribute use xtype=0 for the same type as + b or use xtype='f','d','F',or 'D' + callback -- an optional user-supplied function to call after each + iteration. It is called as callback(xk), where xk is the + current parameter vector. + """ + b = sb.asarray(b)+0.0 + n = len(b) + if maxiter is None: + maxiter = n*10 + + if x0 is None: + x = sb.zeros(n) + else: + x = copy.copy(x0) + + + if xtype is None: + try: + atyp = A.dtype.char + except AttributeError: + atyp = None + if atyp is None: + atyp = A.matvec(x).dtype.char + typ = _coerce_rules[b.dtype.char,atyp] + elif xtype == 0: + typ = b.dtype.char + else: + typ = xtype + if typ not in 'fdFD': + raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" + + x = sb.asarray(x,typ) + b = sb.asarray(b,typ) + + matvec, psolve = (None,)*2 + ltr = _type_conv[typ] + revcom = _iterative.__dict__[ltr+'cgrevcom'] + stoptest = _iterative.__dict__[ltr+'stoptest2'] + + resid = tol + ndx1 = 1 + ndx2 = -1 + work = sb.zeros(4*n,typ) + ijob = 1 + info = 0 + ftflag = True + bnrm2 = -1.0 + iter_ = maxiter + while True: + olditer = iter_ + x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ + revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) + if callback is not None and iter_ > olditer: + callback(x) + slice1 = slice(ndx1-1, ndx1-1+n) + slice2 = slice(ndx2-1, ndx2-1+n) + if (ijob == -1): + break + elif (ijob == 1): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(work[slice1]) + elif (ijob == 2): + if psolve is None: + psolve = get_psolve(A) + work[slice1] = psolve(work[slice2]) + elif (ijob == 3): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(x) + elif (ijob == 4): + if ftflag: + info = -1 + ftflag = False + bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) + ijob = 2 + + return x, info + + +def cgs(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): + """Use Conjugate Gradient Squared iteration to solve A x = b + + Inputs: + + A -- An array or an object with a matvec(x) method + to represent A * x. May also have a psolve(b) methods for + representing solution to the preconditioning equation + M * x = b. + b -- An n-length vector + + + Outputs: + + x -- The converged solution + info -- output result + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : illegal input or breakdown + + Optional Inputs: + + x0 -- (0) default starting guess. + tol -- (1e-5) relative tolerance to achieve + maxiter -- (10*n) maximum number of iterations + xtype -- The type of the result. If None, then it will be + determined from A.dtype.char and b. If A does not have a + typecode method then it will compute A.matvec(x0) to get a + typecode. To save the extra computation when A does not + have a typecode attribute use xtype=0 for the same type as + b or use xtype='f','d','F',or 'D' + callback -- an optional user-supplied function to call after each + iteration. It is called as callback(xk), where xk is the + current parameter vector. + """ + b = sb.asarray(b) + 0.0 + n = len(b) + if maxiter is None: + maxiter = n*10 + + if x0 is None: + x = sb.zeros(n) + else: + x = copy.copy(x0) + + if xtype is None: + try: + atyp = A.dtype.char + except AttributeError: + atyp = None + if atyp is None: + atyp = A.matvec(x).dtype.char + typ = _coerce_rules[b.dtype.char,atyp] + elif xtype == 0: + typ = b.dtype.char + else: + typ = xtype + if typ not in 'fdFD': + raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" + + x = sb.asarray(x,typ) + b = sb.asarray(b,typ) + + matvec, psolve = (None,)*2 + ltr = _type_conv[typ] + revcom = _iterative.__dict__[ltr+'cgsrevcom'] + stoptest = _iterative.__dict__[ltr+'stoptest2'] + + resid = tol + ndx1 = 1 + ndx2 = -1 + work = sb.zeros(7*n,typ) + ijob = 1 + info = 0 + ftflag = True + bnrm2 = -1.0 + iter_ = maxiter + while True: + olditer = iter_ + x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ + revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) + if callback is not None and iter_ > olditer: + callback(x) + slice1 = slice(ndx1-1, ndx1-1+n) + slice2 = slice(ndx2-1, ndx2-1+n) + if (ijob == -1): + break + elif (ijob == 1): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(work[slice1]) + elif (ijob == 2): + if psolve is None: + psolve = get_psolve(A) + work[slice1] = psolve(work[slice2]) + elif (ijob == 3): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(x) + elif (ijob == 4): + if ftflag: + info = -1 + ftflag = False + bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) + ijob = 2 + + return x, info + + +def gmres(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None, callback=None): + """Use Generalized Minimal RESidual iteration to solve A x = b + + Inputs: + + A -- An array or an object with a matvec(x) method + to represent A * x. May also have a psolve(b) methods for + representing solution to the preconditioning equation + M * x = b. + b -- An n-length vector + + + Outputs: + + x -- The converged solution + info -- output result + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : illegal input or breakdown + + Optional Inputs: + + x0 -- (0) default starting guess. + tol -- (1e-5) relative tolerance to achieve + restrt -- (n) When to restart (change this to get faster performance -- but + may not converge). + maxiter -- (10*n) maximum number of iterations + xtype -- The type of the result. If None, then it will be + determined from A.dtype.char and b. If A does not have a + typecode method then it will compute A.matvec(x0) to get a + typecode. To save the extra computation when A does not + have a typecode attribute use xtype=0 for the same type as + b or use xtype='f','d','F',or 'D' + callback -- an optional user-supplied function to call after each + iteration. It is called as callback(xk), where xk is the + current parameter vector. + """ + b = sb.asarray(b)+0.0 + n = len(b) + if maxiter is None: + maxiter = n*10 + + if x0 is None: + x = sb.zeros(n) + else: + x = copy.copy(x0) + + if xtype is None: + try: + atyp = A.dtype.char + except AttributeError: + atyp = A.matvec(x).dtype.char + typ = _coerce_rules[b.dtype.char,atyp] + elif xtype == 0: + typ = b.dtype.char + else: + typ = xtype + if typ not in 'fdFD': + raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" + + x = sb.asarray(x,typ) + b = sb.asarray(b,typ) + + matvec, psolve = (None,)*2 + ltr = _type_conv[typ] + revcom = _iterative.__dict__[ltr+'gmresrevcom'] + stoptest = _iterative.__dict__[ltr+'stoptest2'] + + if restrt is None: + restrt = n + resid = tol + ndx1 = 1 + ndx2 = -1 + work = sb.zeros((6+restrt)*n,typ) + work2 = sb.zeros((restrt+1)*(2*restrt+2),typ) + ijob = 1 + info = 0 + ftflag = True + bnrm2 = -1.0 + iter_ = maxiter + while True: + olditer = iter_ + x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ + revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) + if callback is not None and iter_ > olditer: + callback(x) + slice1 = slice(ndx1-1, ndx1-1+n) + slice2 = slice(ndx2-1, ndx2-1+n) + if (ijob == -1): + break + elif (ijob == 1): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(x) + elif (ijob == 2): + if psolve is None: + psolve = get_psolve(A) + work[slice1] = psolve(work[slice2]) + elif (ijob == 3): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(work[slice1]) + elif (ijob == 4): + if ftflag: + info = -1 + ftflag = False + bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) + ijob = 2 + + return x, info + + +def qmr(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, callback=None): + """Use Quasi-Minimal Residual iteration to solve A x = b + + Inputs: + + A -- An array or an object with matvec(x) and rmatvec(x) methods + to represent A * x and A^H * x respectively. May also have + psolve(b,) and rpsolve(b,) methods for + representing solutions to the preconditioning equations + M * x = b and M^H * x = b respectively. The argument + may be given to specify 'left' or 'right' preconditioning. + b -- An n-length vector + + Outputs: + + x -- The converged solution + info -- output result + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : illegal input or breakdown + + Optional Inputs: + + x0 -- (0) default starting guess. + tol -- (1e-5) relative tolerance to achieve + maxiter -- (10*n) maximum number of iterations + xtype -- The type of the result. If None, then it will be + determined from A.dtype.char and b. If A does not have a + typecode method then it will compute A.matvec(x0) to get a + typecode. To save the extra computation when A does not + have a typecode attribute use xtype=0 for the same type as + b or use xtype='f','d','F',or 'D' + callback -- an optional user-supplied function to call after each + iteration. It is called as callback(xk), where xk is the + current parameter vector. + """ + b = sb.asarray(b)+0.0 + n = len(b) + if maxiter is None: + maxiter = n*10 + + if x0 is None: + x = sb.zeros(n) + else: + x = copy.copy(x0) + + if xtype is None: + try: + atyp = A.dtype.char + except AttributeError: + atyp = None + if atyp is None: + atyp = A.matvec(x).dtype.char + typ = _coerce_rules[b.dtype.char,atyp] + elif xtype == 0: + typ = b.dtype.char + else: + typ = xtype + if typ not in 'fdFD': + raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" + + x = sb.asarray(x,typ) + b = sb.asarray(b,typ) + + + matvec, psolve, rmatvec, rpsolve = (None,)*4 + ltr = _type_conv[typ] + revcom = _iterative.__dict__[ltr+'qmrrevcom'] + stoptest = _iterative.__dict__[ltr+'stoptest2'] + + resid = tol + ndx1 = 1 + ndx2 = -1 + work = sb.zeros(11*n,typ) + ijob = 1 + info = 0 + ftflag = True + bnrm2 = -1.0 + iter_ = maxiter + while True: + olditer = iter_ + x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ + revcom(b, x, work, iter_, resid, info, ndx1, ndx2, ijob) + if callback is not None and iter_ > olditer: + callback(x) + slice1 = slice(ndx1-1, ndx1-1+n) + slice2 = slice(ndx2-1, ndx2-1+n) + if (ijob == -1): + break + elif (ijob == 1): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(work[slice1]) + elif (ijob == 2): + if rmatvec is None: + rmatvec = get_rmatvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*rmatvec(work[slice1]) + elif (ijob == 3): + if psolve is None: + psolve = get_psolveq(A) + work[slice1] = psolve(work[slice2],'left') + elif (ijob == 4): + if psolve is None: + psolve = get_psolveq(A) + work[slice1] = psolve(work[slice2],'right') + elif (ijob == 5): + if rpsolve is None: + rpsolve = get_rpsolveq(A) + work[slice1] = rpsolve(work[slice2],'left') + elif (ijob == 6): + if rpsolve is None: + rpsolve = get_rpsolveq(A) + work[slice1] = rpsolve(work[slice2],'right') + elif (ijob == 7): + if matvec is None: + matvec = get_matvec(A) + work[slice2] *= sclr2 + work[slice2] += sclr1*matvec(x) + elif (ijob == 8): + if ftflag: + info = -1 + ftflag = False + bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) + ijob = 2 + + return x, info Copied: trunk/scipy/splinalg/isolve/tests/test_iterative.py (from rev 3860, trunk/scipy/linalg/tests/test_iterative.py) =================================================================== --- trunk/scipy/linalg/tests/test_iterative.py 2008-01-24 22:11:36 UTC (rev 3860) +++ trunk/scipy/splinalg/isolve/tests/test_iterative.py 2008-01-25 20:00:52 UTC (rev 3861) @@ -0,0 +1,73 @@ +#!/usr/bin/env python +""" Test functions for the splinalg.isolve.iterative module +""" + +import sys + +from numpy import zeros, dot, diag, ones +from scipy.testing import * +from numpy.random import rand +#from numpy import arange, add, array, dot, zeros, identity, conjugate, transpose + +from scipy.linalg import norm +from scipy.splinalg.isolve import cg, cgs, bicg, bicgstab, gmres, qmr + + +def callback(x): + global A, b + res = b-dot(A,x) + #print "||A.x - b|| = " + str(norm(dot(A,x)-b)) + +class TestIterativeSolvers(TestCase): + def __init__(self, *args, **kwds): + TestCase.__init__(self, *args, **kwds) + self.setUp() + def setUp (self): + global A, b + n = 10 + self.tol = 1e-5 + self.x0 = zeros(n, float) + A = rand(n, n)+diag(4*ones(n)) + self.A = 0.5 * (A+A.T) + A = self.A + self.b = rand(n) + b = self.b + + def test_cg(self): + bx0 = self.x0.copy() + x, info = cg(self.A, self.b, self.x0, callback=callback) + assert_array_equal(bx0, self.x0) + assert norm(dot(self.A, x) - self.b) < 5*self.tol + + def test_bicg(self): + bx0 = self.x0.copy() + x, info = bicg(self.A, self.b, self.x0, callback=callback) + assert_array_equal(bx0, self.x0) + assert norm(dot(self.A, x) - self.b) < 5*self.tol + + def test_cgs(self): + bx0 = self.x0.copy() + x, info = cgs(self.A, self.b, self.x0, callback=callback) + assert_array_equal(bx0, self.x0) + assert norm(dot(self.A, x) - self.b) < 5*self.tol + + def test_bicgstab(self): + bx0 = self.x0.copy() + x, info = bicgstab(self.A, self.b, self.x0, callback=callback) + assert_array_equal(bx0, self.x0) + assert norm(dot(self.A, x) - self.b) < 5*self.tol + + def test_gmres(self): + bx0 = self.x0.copy() + x, info = gmres(self.A, self.b, self.x0, callback=callback) + assert_array_equal(bx0, self.x0) + assert norm(dot(self.A, x) - self.b) < 5*self.tol + + def test_qmr(self): + bx0 = self.x0.copy() + x, info = qmr(self.A, self.b, self.x0, callback=callback) + assert_array_equal(bx0, self.x0) + assert norm(dot(self.A, x) - self.b) < 5*self.tol + +if __name__ == "__main__": + nose.run(argv=['', __file__]) From scipy-svn at scipy.org Fri Jan 25 17:24:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 25 Jan 2008 16:24:10 -0600 (CST) Subject: [Scipy-svn] r3862 - in trunk/scipy: . linalg sandbox/multigrid sandbox/multigrid/examples sparse/tests splinalg splinalg/dsolve splinalg/dsolve/umfpack/tests Message-ID: <20080125222410.26D2139C03B@new.scipy.org> Author: wnbell Date: 2008-01-25 16:23:52 -0600 (Fri, 25 Jan 2008) New Revision: 3862 Added: trunk/scipy/splinalg/dsolve/ trunk/scipy/splinalg/dsolve/tests/ Removed: trunk/scipy/linsolve/ Modified: trunk/scipy/linalg/setup.py trunk/scipy/sandbox/multigrid/examples/adaptive.py trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sparse/tests/test_base.py trunk/scipy/splinalg/dsolve/__init__.py trunk/scipy/splinalg/dsolve/info.py trunk/scipy/splinalg/dsolve/linsolve.py trunk/scipy/splinalg/dsolve/setup.py trunk/scipy/splinalg/dsolve/umfpack/tests/test_umfpack.py Log: moved scipy.linsolve to scipy.splinalg.dsolve Modified: trunk/scipy/linalg/setup.py =================================================================== --- trunk/scipy/linalg/setup.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/linalg/setup.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -183,24 +183,6 @@ extra_info = lapack_opt ) -# # iterative methods -# methods = ['BiCGREVCOM.f.src', -# 'BiCGSTABREVCOM.f.src', -# 'CGREVCOM.f.src', -# 'CGSREVCOM.f.src', -## 'ChebyREVCOM.f.src', -# 'GMRESREVCOM.f.src', -## 'JacobiREVCOM.f.src', -# 'QMRREVCOM.f.src', -## 'SORREVCOM.f.src' -# ] -# Util = ['STOPTEST2.f.src','getbreak.f.src'] -# sources = Util + methods + ['_iterative.pyf.src'] -# config.add_extension('_iterative', -# sources = [join('iterative',x) for x in sources], -# extra_info = lapack_opt -# ) - config.add_data_dir('tests') return config Modified: trunk/scipy/sandbox/multigrid/examples/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/sandbox/multigrid/examples/adaptive.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -1,5 +1,6 @@ from scipy import * +from scipy.splinalg import * from scipy.sandbox.multigrid.utils import diag_sparse from scipy.sandbox.multigrid.gallery import poisson, linear_elasticity from scipy.sandbox.multigrid.adaptive import adaptive_sa_solver @@ -38,7 +39,7 @@ def add_resid(x): residuals.append(linalg.norm(b - A*x)) A.psolve = asa.psolve - x_sol = linalg.cg(A,b,x0=x,maxiter=30,tol=1e-10,callback=add_resid)[0] + x_sol = splinalg.cg(A,b,x0=x,maxiter=30,tol=1e-10,callback=add_resid)[0] residuals = array(residuals)/residuals[0] Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -4,7 +4,7 @@ import numpy from numpy import ones,zeros,zeros_like,array,asarray,empty from numpy.linalg import norm -from scipy.linsolve import spsolve +from scipy.splinalg import spsolve from scipy.sparse import dia_matrix from rs import rs_interpolation Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/sparse/tests/test_base.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -26,7 +26,7 @@ coo_matrix, lil_matrix, dia_matrix, bsr_matrix, \ speye, spkron, SparseEfficiencyWarning from scipy.sparse.sputils import supported_dtypes -from scipy.linsolve import splu +from scipy.splinalg import splu warnings.simplefilter('ignore',SparseEfficiencyWarning) Copied: trunk/scipy/splinalg/dsolve (from rev 3861, trunk/scipy/linsolve) Modified: trunk/scipy/splinalg/dsolve/__init__.py =================================================================== --- trunk/scipy/linsolve/__init__.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/splinalg/dsolve/__init__.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -1,9 +1,9 @@ -"Linear Solvers" +"Direct Solvers for Sparse Linear Systems" from info import __doc__ import umfpack -__doc__ = '\n\n'.join( (__doc__, umfpack.__doc__) ) +#__doc__ = '\n\n'.join( (__doc__, umfpack.__doc__) ) del umfpack from linsolve import * Modified: trunk/scipy/splinalg/dsolve/info.py =================================================================== --- trunk/scipy/linsolve/info.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/splinalg/dsolve/info.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -11,9 +11,9 @@ Example session: ->>> from scipy.sparse import csc_matrix +>>> from scipy.sparse import csc_matrix, spdiags >>> from numpy import array ->>> from scipy.linsolve import spdiags, spsolve, use_solver +>>> from scipy.splinalg import spsolve, use_solver >>> >>> print "Inverting a sparse linear system:" >>> print "The sparse matrix (constructed from diagonals):" Modified: trunk/scipy/splinalg/dsolve/linsolve.py =================================================================== --- trunk/scipy/linsolve/linsolve.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/splinalg/dsolve/linsolve.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -154,42 +154,3 @@ else: return splu( A ).solve -def _testme(): - from scipy.sparse import csc_matrix, spdiags - from numpy import array - from scipy.linsolve import spsolve, use_solver - - print "Inverting a sparse linear system:" - print "The sparse matrix (constructed from diagonals):" - a = spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5) - b = array([1, 2, 3, 4, 5]) - print "Solve: single precision complex:" - use_solver( useUmfpack = False ) - a = a.astype('F') - x = spsolve(a, b) - print x - print "Error: ", a*x-b - - print "Solve: double precision complex:" - use_solver( useUmfpack = True ) - a = a.astype('D') - x = spsolve(a, b) - print x - print "Error: ", a*x-b - - print "Solve: double precision:" - a = a.astype('d') - x = spsolve(a, b) - print x - print "Error: ", a*x-b - - print "Solve: single precision:" - use_solver( useUmfpack = False ) - a = a.astype('f') - x = spsolve(a, b.astype('f')) - print x - print "Error: ", a*x-b - - -if __name__ == "__main__": - _testme() Modified: trunk/scipy/splinalg/dsolve/setup.py =================================================================== --- trunk/scipy/linsolve/setup.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/splinalg/dsolve/setup.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -6,7 +6,7 @@ from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info - config = Configuration('linsolve',parent_package,top_path) + config = Configuration('dsolve',parent_package,top_path) config.add_data_dir('tests') lapack_opt = get_info('lapack_opt',notfound_action=2) Modified: trunk/scipy/splinalg/dsolve/umfpack/tests/test_umfpack.py =================================================================== --- trunk/scipy/linsolve/umfpack/tests/test_umfpack.py 2008-01-25 20:00:52 UTC (rev 3861) +++ trunk/scipy/splinalg/dsolve/umfpack/tests/test_umfpack.py 2008-01-25 22:23:52 UTC (rev 3862) @@ -10,12 +10,13 @@ import random from scipy.testing import * -from scipy import linsolve, rand, matrix, diag, eye +from scipy import rand, matrix, diag, eye from scipy.sparse import csc_matrix, dok_matrix, spdiags +from scipy.splinalg import linsolve import numpy as nm try: - import scipy.linsolve.umfpack as um + import scipy.splinalg.dsolve.umfpack as um except (ImportError, AttributeError): _have_umfpack = False else: From scipy-svn at scipy.org Fri Jan 25 17:28:09 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 25 Jan 2008 16:28:09 -0600 (CST) Subject: [Scipy-svn] r3863 - in trunk/scipy/splinalg: . dsolve/tests isolve Message-ID: <20080125222809.4C79539C03B@new.scipy.org> Author: wnbell Date: 2008-01-25 16:28:00 -0600 (Fri, 25 Jan 2008) New Revision: 3863 Added: trunk/scipy/splinalg/__init__.py trunk/scipy/splinalg/dsolve/tests/test_linsolve.py trunk/scipy/splinalg/info.py trunk/scipy/splinalg/isolve/__init__.py trunk/scipy/splinalg/isolve/setup.py trunk/scipy/splinalg/setup.py Log: commit missing files Added: trunk/scipy/splinalg/__init__.py =================================================================== --- trunk/scipy/splinalg/__init__.py 2008-01-25 22:23:52 UTC (rev 3862) +++ trunk/scipy/splinalg/__init__.py 2008-01-25 22:28:00 UTC (rev 3863) @@ -0,0 +1,11 @@ +"Sparse Linear Algebra routines" + +from info import __doc__ + +from isolve import * +from dsolve import * + +__all__ = filter(lambda s:not s.startswith('_'),dir()) +from scipy.testing.pkgtester import Tester +test = Tester().test +bench = Tester().bench Added: trunk/scipy/splinalg/dsolve/tests/test_linsolve.py =================================================================== --- trunk/scipy/splinalg/dsolve/tests/test_linsolve.py 2008-01-25 22:23:52 UTC (rev 3862) +++ trunk/scipy/splinalg/dsolve/tests/test_linsolve.py 2008-01-25 22:28:00 UTC (rev 3863) @@ -0,0 +1,41 @@ + +from numpy import array, finfo +from scipy.testing import * + +from scipy.linalg import norm, inv +from scipy.sparse import spdiags, csc_matrix +from scipy.splinalg.dsolve import spsolve, use_solver + +#TODO add more comprehensive tests +use_solver( useUmfpack = False ) + +class TestLinsolve(TestCase): + ## this crashes SuperLU + #def test_singular(self): + # A = csc_matrix( (5,5), dtype='d' ) + # b = array([1, 2, 3, 4, 5],dtype='d') + # x = spsolve(A,b) + + def test_twodiags(self): + A = spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5) + b = array([1, 2, 3, 4, 5]) + + # condition number of A + cond_A = norm(A.todense(),2) * norm(inv(A.todense()),2) + + + for t in ['f','d','F','D']: + eps = finfo(t).eps #floating point epsilon + b = b.astype(t) + + for format in ['csc','csr']: + Asp = A.astype(t).asformat(format) + + x = spsolve(Asp,b) + + assert( norm(b - Asp*x) < 10 * cond_A * eps ) + + +if __name__ == "__main__": + nose.run(argv=['', __file__]) + Added: trunk/scipy/splinalg/info.py =================================================================== --- trunk/scipy/splinalg/info.py 2008-01-25 22:23:52 UTC (rev 3862) +++ trunk/scipy/splinalg/info.py 2008-01-25 22:28:00 UTC (rev 3863) @@ -0,0 +1,19 @@ +""" +Sparse Linear Algebra +===================== + +There are submodules of splinalg: + 1. eigen: sparse eigenvalue problem solvers + 2. isolve: iterative methods for solving linear systems + 3. dsolve: direct factorization methods for solving linear systems + +Examples +======== + + + +""" + +#TODO show examples + +postpone_import = 1 Added: trunk/scipy/splinalg/isolve/__init__.py =================================================================== --- trunk/scipy/splinalg/isolve/__init__.py 2008-01-25 22:23:52 UTC (rev 3862) +++ trunk/scipy/splinalg/isolve/__init__.py 2008-01-25 22:28:00 UTC (rev 3863) @@ -0,0 +1,10 @@ +"Iterative Solvers for Sparse Linear Systems" + +#from info import __doc__ +from iterative import * + +__all__ = filter(lambda s:not s.startswith('_'),dir()) +from scipy.testing.pkgtester import Tester +test = Tester().test +bench = Tester().bench + Added: trunk/scipy/splinalg/isolve/setup.py =================================================================== --- trunk/scipy/splinalg/isolve/setup.py 2008-01-25 22:23:52 UTC (rev 3862) +++ trunk/scipy/splinalg/isolve/setup.py 2008-01-25 22:28:00 UTC (rev 3863) @@ -0,0 +1,48 @@ +#!/usr/bin/env python +## Automatically adapted for scipy Oct 18, 2005 by + +import os +import sys +import re +from distutils.dep_util import newer_group, newer +from glob import glob +from os.path import join + +def configuration(parent_package='',top_path=None): + from numpy.distutils.system_info import get_info, NotFoundError + + from numpy.distutils.misc_util import Configuration + + config = Configuration('isolve',parent_package,top_path) + + lapack_opt = get_info('lapack_opt') + + if not lapack_opt: + raise NotFoundError,'no lapack/blas resources found' + + # iterative methods + methods = ['BiCGREVCOM.f.src', + 'BiCGSTABREVCOM.f.src', + 'CGREVCOM.f.src', + 'CGSREVCOM.f.src', +# 'ChebyREVCOM.f.src', + 'GMRESREVCOM.f.src', +# 'JacobiREVCOM.f.src', + 'QMRREVCOM.f.src', +# 'SORREVCOM.f.src' + ] + Util = ['STOPTEST2.f.src','getbreak.f.src'] + sources = Util + methods + ['_iterative.pyf.src'] + config.add_extension('_iterative', + sources = [join('iterative',x) for x in sources], + extra_info = lapack_opt + ) + + config.add_data_dir('tests') + + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + + setup(**configuration(top_path='').todict()) Property changes on: trunk/scipy/splinalg/isolve/setup.py ___________________________________________________________________ Name: svn:executable + * Added: trunk/scipy/splinalg/setup.py =================================================================== --- trunk/scipy/splinalg/setup.py 2008-01-25 22:23:52 UTC (rev 3862) +++ trunk/scipy/splinalg/setup.py 2008-01-25 22:28:00 UTC (rev 3863) @@ -0,0 +1,15 @@ +#!/usr/bin/env python + +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + + config = Configuration('splinalg',parent_package,top_path) + + config.add_subpackage(('isolve')) + config.add_subpackage(('dsolve')) + + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) Property changes on: trunk/scipy/splinalg/setup.py ___________________________________________________________________ Name: svn:executable + * From scipy-svn at scipy.org Fri Jan 25 17:29:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 25 Jan 2008 16:29:43 -0600 (CST) Subject: [Scipy-svn] r3864 - in trunk/scipy: . linsolve Message-ID: <20080125222943.3E2FF39C03B@new.scipy.org> Author: wnbell Date: 2008-01-25 16:29:38 -0600 (Fri, 25 Jan 2008) New Revision: 3864 Added: trunk/scipy/linsolve/ trunk/scipy/linsolve/__init__.py Log: add linsolve -> splinalg pointer Added: trunk/scipy/linsolve/__init__.py =================================================================== --- trunk/scipy/linsolve/__init__.py 2008-01-25 22:28:00 UTC (rev 3863) +++ trunk/scipy/linsolve/__init__.py 2008-01-25 22:29:38 UTC (rev 3864) @@ -0,0 +1,6 @@ + +from warnings import warn + +warn('scipy.linsolve has moved to scipy.splinalg.dsolve', DeprecationWarning) + +from scipy.splinalg.dsolve import * From scipy-svn at scipy.org Fri Jan 25 17:32:50 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 25 Jan 2008 16:32:50 -0600 (CST) Subject: [Scipy-svn] r3865 - trunk/scipy/splinalg Message-ID: <20080125223250.B7E5E39C31F@new.scipy.org> Author: wnbell Date: 2008-01-25 16:32:47 -0600 (Fri, 25 Jan 2008) New Revision: 3865 Modified: trunk/scipy/splinalg/ Log: ignore *.pyc Property changes on: trunk/scipy/splinalg ___________________________________________________________________ Name: svn:ignore + __init__.pyc From scipy-svn at scipy.org Sat Jan 26 11:14:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 26 Jan 2008 10:14:57 -0600 (CST) Subject: [Scipy-svn] r3866 - in trunk/scipy: linalg splinalg/dsolve/tests splinalg/dsolve/umfpack/tests Message-ID: <20080126161457.1A0B939C20E@new.scipy.org> Author: wnbell Date: 2008-01-26 10:14:42 -0600 (Sat, 26 Jan 2008) New Revision: 3866 Added: trunk/scipy/linalg/iterative.py Modified: trunk/scipy/linalg/__init__.py trunk/scipy/splinalg/dsolve/tests/test_linsolve.py trunk/scipy/splinalg/dsolve/umfpack/tests/test_umfpack.py Log: deprecate linalg.iterative properly filter warnings in splinalg.dsolve unittests Modified: trunk/scipy/linalg/__init__.py =================================================================== --- trunk/scipy/linalg/__init__.py 2008-01-25 22:32:47 UTC (rev 3865) +++ trunk/scipy/linalg/__init__.py 2008-01-26 16:14:42 UTC (rev 3866) @@ -10,10 +10,9 @@ from matfuncs import * from blas import * -#from iterative import * -# TODO remove this -from scipy.splinalg.isolve import * +from iterative import * + __all__ = filter(lambda s:not s.startswith('_'),dir()) from numpy.dual import register_func Added: trunk/scipy/linalg/iterative.py =================================================================== --- trunk/scipy/linalg/iterative.py 2008-01-25 22:32:47 UTC (rev 3865) +++ trunk/scipy/linalg/iterative.py 2008-01-26 16:14:42 UTC (rev 3866) @@ -0,0 +1,13 @@ +__all__ = ['bicg','bicgstab','cg','cgs','gmres','qmr'] + +# Deprecated on January 26, 2008 + +from scipy.splinalg import isolve +from numpy import deprecate + +for name in __all__: + oldfn = getattr(isolve, name) + oldname='scipy.linalg.' + name + newname='scipy.splinalg.' + name + newfn = deprecate(oldfn, oldname=oldname, newname=newname) + exec(name + ' = newfn') Modified: trunk/scipy/splinalg/dsolve/tests/test_linsolve.py =================================================================== --- trunk/scipy/splinalg/dsolve/tests/test_linsolve.py 2008-01-25 22:32:47 UTC (rev 3865) +++ trunk/scipy/splinalg/dsolve/tests/test_linsolve.py 2008-01-26 16:14:42 UTC (rev 3866) @@ -1,3 +1,4 @@ +import warnings from numpy import array, finfo from scipy.testing import * @@ -3,7 +4,9 @@ from scipy.linalg import norm, inv -from scipy.sparse import spdiags, csc_matrix +from scipy.sparse import spdiags, csc_matrix, SparseEfficiencyWarning from scipy.splinalg.dsolve import spsolve, use_solver +warnings.simplefilter('ignore',SparseEfficiencyWarning) + #TODO add more comprehensive tests use_solver( useUmfpack = False ) Modified: trunk/scipy/splinalg/dsolve/umfpack/tests/test_umfpack.py =================================================================== --- trunk/scipy/splinalg/dsolve/umfpack/tests/test_umfpack.py 2008-01-25 22:32:47 UTC (rev 3865) +++ trunk/scipy/splinalg/dsolve/umfpack/tests/test_umfpack.py 2008-01-26 16:14:42 UTC (rev 3866) @@ -5,15 +5,19 @@ """ +import warnings + from numpy import transpose, array, arange import random from scipy.testing import * from scipy import rand, matrix, diag, eye -from scipy.sparse import csc_matrix, dok_matrix, spdiags +from scipy.sparse import csc_matrix, dok_matrix, spdiags, SparseEfficiencyWarning from scipy.splinalg import linsolve +warnings.simplefilter('ignore',SparseEfficiencyWarning) + import numpy as nm try: import scipy.splinalg.dsolve.umfpack as um From scipy-svn at scipy.org Sat Jan 26 11:21:48 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 26 Jan 2008 10:21:48 -0600 (CST) Subject: [Scipy-svn] r3867 - in trunk/scipy: sandbox/multigrid sandbox/multigrid/examples sandbox/multigrid/gallery sandbox/multigrid/gallery/tests sandbox/multigrid/multigridtools sandbox/multigrid/tests sandbox/multigrid/tests/sample_data splinalg splinalg/dsolve splinalg/dsolve/SuperLU splinalg/dsolve/SuperLU/SRC splinalg/dsolve/tests splinalg/dsolve/umfpack splinalg/dsolve/umfpack/tests splinalg/eigen splinalg/isolve splinalg/isolve/iterative splinalg/isolve/tests Message-ID: <20080126162148.B919439C280@new.scipy.org> Author: wnbell Date: 2008-01-26 10:21:39 -0600 (Sat, 26 Jan 2008) New Revision: 3867 Modified: trunk/scipy/sandbox/multigrid/ trunk/scipy/sandbox/multigrid/examples/ trunk/scipy/sandbox/multigrid/gallery/ trunk/scipy/sandbox/multigrid/gallery/tests/ trunk/scipy/sandbox/multigrid/multigridtools/ trunk/scipy/sandbox/multigrid/tests/ trunk/scipy/sandbox/multigrid/tests/sample_data/ trunk/scipy/splinalg/ trunk/scipy/splinalg/dsolve/ trunk/scipy/splinalg/dsolve/SuperLU/ trunk/scipy/splinalg/dsolve/SuperLU/SRC/ trunk/scipy/splinalg/dsolve/tests/ trunk/scipy/splinalg/dsolve/umfpack/ trunk/scipy/splinalg/dsolve/umfpack/tests/ trunk/scipy/splinalg/eigen/ trunk/scipy/splinalg/isolve/ trunk/scipy/splinalg/isolve/iterative/ trunk/scipy/splinalg/isolve/tests/ Log: ignore *.pyc Property changes on: trunk/scipy/sandbox/multigrid ___________________________________________________________________ Name: svn:ignore - *.so *.bak *.pyc ignore.txt + *.pyc Property changes on: trunk/scipy/sandbox/multigrid/examples ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/scipy/sandbox/multigrid/gallery ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/scipy/sandbox/multigrid/gallery/tests ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/scipy/sandbox/multigrid/multigridtools ___________________________________________________________________ Name: svn:ignore - *.so *.bak *.pyc ignore.txt + *.pyc Property changes on: trunk/scipy/sandbox/multigrid/tests ___________________________________________________________________ Name: svn:ignore - *.so *.bak *.pyc ignore.txt + *.pyc Property changes on: trunk/scipy/sandbox/multigrid/tests/sample_data ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/scipy/splinalg ___________________________________________________________________ Name: svn:ignore - __init__.pyc + *.pyc Property changes on: trunk/scipy/splinalg/dsolve ___________________________________________________________________ Name: svn:ignore - *.pyc *.swp *.pyd *.so + *.pyc Property changes on: trunk/scipy/splinalg/dsolve/SuperLU ___________________________________________________________________ Name: svn:ignore - *.pyc *.swp *.pyd *.so + *.pyc Property changes on: trunk/scipy/splinalg/dsolve/SuperLU/SRC ___________________________________________________________________ Name: svn:ignore - *.pyc *.swp *.pyd *.so + *.pyc Property changes on: trunk/scipy/splinalg/dsolve/tests ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/scipy/splinalg/dsolve/umfpack ___________________________________________________________________ Name: svn:ignore - *.pyc *.swp *.pyd *.so + *.pyc Property changes on: trunk/scipy/splinalg/dsolve/umfpack/tests ___________________________________________________________________ Name: svn:ignore - *.pyc *.swp *.pyd *.so + *.pyc Property changes on: trunk/scipy/splinalg/eigen ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/scipy/splinalg/isolve ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/scipy/splinalg/isolve/iterative ___________________________________________________________________ Name: svn:ignore - *.pyc *.swp *.pyd *.so + *.pyc Property changes on: trunk/scipy/splinalg/isolve/tests ___________________________________________________________________ Name: svn:ignore + *.pyc From scipy-svn at scipy.org Sun Jan 27 02:08:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 27 Jan 2008 01:08:18 -0600 (CST) Subject: [Scipy-svn] r3868 - branches Message-ID: <20080127070818.D203C39C14D@new.scipy.org> Author: cdavid Date: 2008-01-27 01:08:03 -0600 (Sun, 27 Jan 2008) New Revision: 3868 Added: branches/build_with_scons/ Log: create build_with_scons, the new branch to build scipy with numscons. Copied: branches/build_with_scons (from rev 3867, trunk) From scipy-svn at scipy.org Sun Jan 27 02:36:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 27 Jan 2008 01:36:10 -0600 (CST) Subject: [Scipy-svn] r3869 - trunk Message-ID: <20080127073610.5D91B39C233@new.scipy.org> Author: cdavid Date: 2008-01-27 01:36:06 -0600 (Sun, 27 Jan 2008) New Revision: 3869 Modified: trunk/ Log: Initialized merge tracking via "svnmerge" with revisions "1-3868" from http://svn.scipy.org/svn/scipy/branches/build_with_scons Property changes on: trunk ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 /branches/testing_cleanup:1-3662 + /branches/build_with_scons:1-3868 /branches/scipy.scons:1-3533 /branches/testing_cleanup:1-3662 From scipy-svn at scipy.org Sun Jan 27 02:37:54 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 27 Jan 2008 01:37:54 -0600 (CST) Subject: [Scipy-svn] r3870 - branches/build_with_scons Message-ID: <20080127073754.38E8E39C233@new.scipy.org> Author: cdavid Date: 2008-01-27 01:37:51 -0600 (Sun, 27 Jan 2008) New Revision: 3870 Modified: branches/build_with_scons/ Log: Initialized merge tracking via "svnmerge" with revisions "1-3869" from http://svn.scipy.org/svn/scipy/trunk Property changes on: branches/build_with_scons ___________________________________________________________________ Name: svnmerge-integrated - /branches/scipy.scons:1-3533 /branches/testing_cleanup:1-3662 + /branches/scipy.scons:1-3533 /branches/testing_cleanup:1-3662 /trunk:1-3869 From scipy-svn at scipy.org Sun Jan 27 02:46:21 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 27 Jan 2008 01:46:21 -0600 (CST) Subject: [Scipy-svn] r3871 - branches/build_with_scons/scipy Message-ID: <20080127074621.F076C39C24B@new.scipy.org> Author: cdavid Date: 2008-01-27 01:46:17 -0600 (Sun, 27 Jan 2008) New Revision: 3871 Added: branches/build_with_scons/scipy/setupscons.py Log: Start branch to build scipy with scons: add top setupscons.py Added: branches/build_with_scons/scipy/setupscons.py =================================================================== --- branches/build_with_scons/scipy/setupscons.py 2008-01-27 07:37:51 UTC (rev 3870) +++ branches/build_with_scons/scipy/setupscons.py 2008-01-27 07:46:17 UTC (rev 3871) @@ -0,0 +1,31 @@ + +def configuration(parent_package='',top_path=None, setup_name = 'setupscons.py'): + from numpy.distutils.misc_util import Configuration + config = Configuration('scipy',parent_package,top_path, setup_name = 'setupscons.py') + config.add_subpackage('cluster') + config.add_subpackage('fftpack') + config.add_subpackage('integrate') + config.add_subpackage('interpolate') + config.add_subpackage('io') + config.add_subpackage('lib') + config.add_subpackage('linalg') + config.add_subpackage('linsolve') + config.add_subpackage('maxentropy') + config.add_subpackage('misc') + config.add_subpackage('odr') + config.add_subpackage('optimize') + #config.add_subpackage('sandbox') + config.add_subpackage('signal') + config.add_subpackage('sparse') + config.add_subpackage('special') + config.add_subpackage('stats') + config.add_subpackage('ndimage') + #config.add_subpackage('stsci') + config.add_subpackage('weave') + config.make_svn_version_py() # installs __svn_version__.py + config.scons_make_config_py() # installs __config__.py + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) From scipy-svn at scipy.org Sun Jan 27 02:56:31 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 27 Jan 2008 01:56:31 -0600 (CST) Subject: [Scipy-svn] r3872 - in branches/build_with_scons/scipy: . cluster Message-ID: <20080127075631.CBAD739C233@new.scipy.org> Author: cdavid Date: 2008-01-27 01:56:20 -0600 (Sun, 27 Jan 2008) New Revision: 3872 Added: branches/build_with_scons/scipy/cluster/SConstruct branches/build_with_scons/scipy/cluster/setupscons.py Modified: branches/build_with_scons/scipy/setupscons.py Log: scipy.cluster build with numscons Added: branches/build_with_scons/scipy/cluster/SConstruct =================================================================== --- branches/build_with_scons/scipy/cluster/SConstruct 2008-01-27 07:46:17 UTC (rev 3871) +++ branches/build_with_scons/scipy/cluster/SConstruct 2008-01-27 07:56:20 UTC (rev 3872) @@ -0,0 +1,12 @@ +# Last Change: Thu Oct 18 09:00 PM 2007 J +# vim:syntax=python +from os.path import join + +from numpy.distutils.misc_util import get_numpy_include_dirs +from numpy.distutils.scons import GetNumpyEnvironment + +env = GetNumpyEnvironment(ARGUMENTS) + +env.AppendUnique(CPPPATH = get_numpy_include_dirs()) +env.NumpyPythonExtension('_vq', source = [join('src', 'vq_module.c'), + join('src', 'vq.c')]) Added: branches/build_with_scons/scipy/cluster/setupscons.py =================================================================== --- branches/build_with_scons/scipy/cluster/setupscons.py 2008-01-27 07:46:17 UTC (rev 3871) +++ branches/build_with_scons/scipy/cluster/setupscons.py 2008-01-27 07:56:20 UTC (rev 3872) @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +from os.path import join + +def configuration(parent_package = '', top_path = None): + from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs + config = Configuration('cluster', parent_package, top_path) + + config.add_data_dir('tests') + + #config.add_extension('_vq', + # sources=[join('src', 'vq_module.c'), join('src', 'vq.c')], + # include_dirs = [get_numpy_include_dirs()]) + config.add_sconscript('SConstruct') + + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(maintainer = "SciPy Developers", + author = "Eric Jones", + maintainer_email = "scipy-dev at scipy.org", + description = "Clustering Algorithms (Information Theory)", + url = "http://www.scipy.org", + license = "SciPy License (BSD Style)", + **configuration(top_path='').todict() + ) Property changes on: branches/build_with_scons/scipy/cluster/setupscons.py ___________________________________________________________________ Name: svn:executable + * Modified: branches/build_with_scons/scipy/setupscons.py =================================================================== --- branches/build_with_scons/scipy/setupscons.py 2008-01-27 07:46:17 UTC (rev 3871) +++ branches/build_with_scons/scipy/setupscons.py 2008-01-27 07:56:20 UTC (rev 3872) @@ -4,24 +4,26 @@ config = Configuration('scipy',parent_package,top_path, setup_name = 'setupscons.py') config.add_subpackage('cluster') config.add_subpackage('fftpack') - config.add_subpackage('integrate') - config.add_subpackage('interpolate') - config.add_subpackage('io') - config.add_subpackage('lib') - config.add_subpackage('linalg') - config.add_subpackage('linsolve') - config.add_subpackage('maxentropy') - config.add_subpackage('misc') - config.add_subpackage('odr') - config.add_subpackage('optimize') + #config.add_subpackage('integrate') + #config.add_subpackage('interpolate') + #config.add_subpackage('io') + #config.add_subpackage('lib') + #config.add_subpackage('linalg') + #config.add_subpackage('linsolve') + #config.add_subpackage('maxentropy') + #config.add_subpackage('misc') + #config.add_subpackage('odr') + #config.add_subpackage('optimize') #config.add_subpackage('sandbox') - config.add_subpackage('signal') - config.add_subpackage('sparse') - config.add_subpackage('special') - config.add_subpackage('stats') - config.add_subpackage('ndimage') + #config.add_subpackage('signal') + #config.add_subpackage('sparse') + #config.add_subpackage('special') + #config.add_subpackage('splinalg') + #config.add_subpackage('stats') + #config.add_subpackage('ndimage') #config.add_subpackage('stsci') - config.add_subpackage('weave') + #config.add_subpackage('weave') + #config.add_subpackage('testing') config.make_svn_version_py() # installs __svn_version__.py config.scons_make_config_py() # installs __config__.py return config From scipy-svn at scipy.org Mon Jan 28 12:02:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 28 Jan 2008 11:02:40 -0600 (CST) Subject: [Scipy-svn] r3873 - trunk/scipy/fftpack/src Message-ID: <20080128170240.25C1439C245@new.scipy.org> Author: rkern Date: 2008-01-28 11:02:36 -0600 (Mon, 28 Jan 2008) New Revision: 3873 Modified: trunk/scipy/fftpack/src/zfft_fftw3.c trunk/scipy/fftpack/src/zfftnd_fftpack.c Log: Remove // comments from C code. Modified: trunk/scipy/fftpack/src/zfft_fftw3.c =================================================================== --- trunk/scipy/fftpack/src/zfft_fftw3.c 2008-01-27 07:56:20 UTC (rev 3872) +++ trunk/scipy/fftpack/src/zfft_fftw3.c 2008-01-28 17:02:36 UTC (rev 3873) @@ -1,5 +1,5 @@ -// This cache uses FFTW_MEASURE for the plans, and do not copy the data. +/* This cache uses FFTW_MEASURE for the plans, and do not copy the data. */ GEN_CACHE(zfftw3,(int n,int d) ,int direction; fftw_plan plan; @@ -7,19 +7,17 @@ ,((caches_zfftw3[i].n==n) && (caches_zfftw3[i].direction==d)) ,caches_zfftw3[id].direction = d; - // This working buffer is only used to compute the plan: we need it - // since FFTW_MEASURE destroys its input when computing a plan + /* This working buffer is only used to compute the plan: we need it + since FFTW_MEASURE destroys its input when computing a plan */ caches_zfftw3[id].wrk = fftw_malloc(n * sizeof(double) * 2); caches_zfftw3[id].plan = fftw_plan_dft_1d(n, caches_zfftw3[id].wrk, caches_zfftw3[id].wrk, (d>0?FFTW_FORWARD:FFTW_BACKWARD), FFTW_ESTIMATE | FFTW_UNALIGNED); - ,//fftw_print_plan(caches_zfftw3[id].plan); + , fftw_destroy_plan(caches_zfftw3[id].plan); fftw_free(caches_zfftw3[id].wrk); - //fflush(stdout); - //fprintf(stderr, "aligned count %d\n", countaligned); ,10) static void zfft_fftw3(complex_double * inout, int n, int dir, int @@ -56,8 +54,6 @@ for (i = n * howmany - 1; i >= 0; --i) { *((double *) (ptr)) *= factor; *((double *) (ptr++) + 1) *= factor; - //*((double *) (ptr)) /= n; - //*((double *) (ptr++) + 1) /= n; } } } Modified: trunk/scipy/fftpack/src/zfftnd_fftpack.c =================================================================== --- trunk/scipy/fftpack/src/zfftnd_fftpack.c 2008-01-27 07:56:20 UTC (rev 3872) +++ trunk/scipy/fftpack/src/zfftnd_fftpack.c 2008-01-28 17:02:36 UTC (rev 3873) @@ -89,8 +89,6 @@ for (i = 0; i < rank; ++i) { sz *= dims[i]; } - //zfft_fftpack(ptr, dims[rank - 1], direction, howmany * sz / dims[rank - 1], - // normalize); zfft(ptr, dims[rank - 1], direction, howmany * sz / dims[rank - 1], normalize); @@ -112,7 +110,6 @@ } } flatten(tmp, ptr, rank, itmp[axis], dims[axis], 0, itmp); - //zfft_fftpack(tmp, dims[axis], direction, sz / dims[axis], normalize); zfft(tmp, dims[axis], direction, sz / dims[axis], normalize); flatten(ptr, tmp, rank, itmp[axis], dims[axis], 1, itmp); } From scipy-svn at scipy.org Tue Jan 29 17:24:08 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 29 Jan 2008 16:24:08 -0600 (CST) Subject: [Scipy-svn] r3874 - trunk/scipy/sparse/tests Message-ID: <20080129222408.5D9E339C3FD@new.scipy.org> Author: wnbell Date: 2008-01-29 16:24:05 -0600 (Tue, 29 Jan 2008) New Revision: 3874 Modified: trunk/scipy/sparse/tests/test_spfuncs.py Log: updated testing main() Modified: trunk/scipy/sparse/tests/test_spfuncs.py =================================================================== --- trunk/scipy/sparse/tests/test_spfuncs.py 2008-01-28 17:02:36 UTC (rev 3873) +++ trunk/scipy/sparse/tests/test_spfuncs.py 2008-01-29 22:24:05 UTC (rev 3874) @@ -102,5 +102,5 @@ if __name__ == "__main__": - unittests.main() + nose.run(argv=['', __file__]) From scipy-svn at scipy.org Tue Jan 29 20:17:50 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 29 Jan 2008 19:17:50 -0600 (CST) Subject: [Scipy-svn] r3875 - in trunk/scipy/sandbox/multigrid: . tests Message-ID: <20080130011750.46F0E39C07E@new.scipy.org> Author: wnbell Date: 2008-01-29 19:17:40 -0600 (Tue, 29 Jan 2008) New Revision: 3875 Added: trunk/scipy/sandbox/multigrid/tests/test_rs.py Modified: trunk/scipy/sandbox/multigrid/__init__.py trunk/scipy/sandbox/multigrid/multilevel.py trunk/scipy/sandbox/multigrid/rs.py Log: added RS unittest moved RS to rs.py Modified: trunk/scipy/sandbox/multigrid/__init__.py =================================================================== --- trunk/scipy/sandbox/multigrid/__init__.py 2008-01-29 22:24:05 UTC (rev 3874) +++ trunk/scipy/sandbox/multigrid/__init__.py 2008-01-30 01:17:40 UTC (rev 3875) @@ -2,7 +2,9 @@ from info import __doc__ -from multilevel import * +from multilevel import multilevel_solver +from rs import ruge_stuben_solver +from sa import smoothed_aggregation_solver from gallery import * __all__ = filter(lambda s:not s.startswith('_'),dir()) Modified: trunk/scipy/sandbox/multigrid/multilevel.py =================================================================== --- trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-29 22:24:05 UTC (rev 3874) +++ trunk/scipy/sandbox/multigrid/multilevel.py 2008-01-30 01:17:40 UTC (rev 3875) @@ -1,51 +1,20 @@ -__all__ = ['ruge_stuben_solver','multilevel_solver'] +__all__ = ['multilevel_solver'] import scipy import numpy -from numpy import ones,zeros,zeros_like,array,asarray,empty +from numpy import ones, zeros, zeros_like, array, asarray, empty from numpy.linalg import norm from scipy.splinalg import spsolve -from scipy.sparse import dia_matrix -from rs import rs_interpolation from relaxation import gauss_seidel,jacobi,sor from utils import symmetric_rescaling, diag_sparse - -def ruge_stuben_solver(A,max_levels=10,max_coarse=500): - """ - Create a multilevel solver using Ruge-Stuben coarsening (Classical AMG) - - References: - "Multigrid" - Trottenberg, U., C. W. Oosterlee, and Anton Schuller. - San Diego: Academic Press, 2001. - Appendix A - - """ - As = [A] - Ps = [] - - while len(As) < max_levels and A.shape[0] > max_coarse: - P = rs_interpolation(A) - - A = (P.T.tocsr() * A) * P #galerkin operator - - As.append(A) - Ps.append(P) - - return multilevel_solver(As,Ps) - - - - - class multilevel_solver: - def __init__(self,As,Ps,Rs=None,preprocess=None,postprocess=None): + def __init__(self, As, Ps, Rs=None, preprocess=None, postprocess=None): self.As = As self.Ps = Ps - self.preprocess = preprocess + self.preprocess = preprocess self.postprocess = postprocess if Rs is None: Modified: trunk/scipy/sandbox/multigrid/rs.py =================================================================== --- trunk/scipy/sandbox/multigrid/rs.py 2008-01-29 22:24:05 UTC (rev 3874) +++ trunk/scipy/sandbox/multigrid/rs.py 2008-01-30 01:17:40 UTC (rev 3875) @@ -1,9 +1,40 @@ from scipy.sparse import csr_matrix,isspmatrix_csr +from multilevel import multilevel_solver import multigridtools -__all__ = ['rs_strong_connections','rs_interpolation'] +__all__ = ['ruge_stuben_solver','rs_strong_connections','rs_interpolation'] + +def ruge_stuben_solver(A, max_levels=10, max_coarse=500): + """ + Create a multilevel solver using Ruge-Stuben coarsening (Classical AMG) + + References: + "Multigrid" + Trottenberg, U., C. W. Oosterlee, and Anton Schuller. + San Diego: Academic Press, 2001. + Appendix A + + """ + As = [A] + Ps = [] + Rs = [] + + while len(As) < max_levels and A.shape[0] > max_coarse: + P = rs_interpolation(A) + R = P.T.tocsr() + + A = R * A * P #galerkin operator + + As.append(A) + Ps.append(P) + Rs.append(R) + + return multilevel_solver(As,Ps,Rs=Rs) + + + def rs_strong_connections(A,theta): """Return a strength of connection matrix using the method of Ruge and Stuben Added: trunk/scipy/sandbox/multigrid/tests/test_rs.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_rs.py 2008-01-29 22:24:05 UTC (rev 3874) +++ trunk/scipy/sandbox/multigrid/tests/test_rs.py 2008-01-30 01:17:40 UTC (rev 3875) @@ -0,0 +1,38 @@ +from scipy.testing import * +from scipy import rand +from scipy.sparse import spdiags,csr_matrix,lil_matrix, \ + isspmatrix_csr,isspmatrix_csc,isspmatrix_coo, \ + isspmatrix_lil +import numpy + +from scipy.sandbox.multigrid.rs import ruge_stuben_solver +from scipy.sandbox.multigrid.gallery import poisson + +class TestRugeStubenSolver(TestCase): + def test_poisson(self): + cases = [] + + cases.append( (1000,) ) + cases.append( (500,500) ) + cases.append( (50,50,50) ) + + for case in cases: + A = poisson( case, format='csr' ) + + numpy.random.seed(0) #make tests repeatable + + x = rand(A.shape[0]) + b = A*rand(A.shape[0]) #zeros_like(x) + + ml = ruge_stuben_solver(A) + + x_sol,residuals = ml.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) + + avg_convergence_ratio = (residuals[-1]/residuals[0])**(1.0/len(residuals)) + + print "avg",avg_convergence_ratio + + assert(avg_convergence_ratio < 0.15) + +if __name__ == '__main__': + nose.run(argv=['', __file__]) From scipy-svn at scipy.org Wed Jan 30 12:05:45 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 30 Jan 2008 11:05:45 -0600 (CST) Subject: [Scipy-svn] r3876 - in trunk/scipy/sandbox/multigrid: . tests Message-ID: <20080130170545.01CA239C0EB@new.scipy.org> Author: wnbell Date: 2008-01-30 11:05:38 -0600 (Wed, 30 Jan 2008) New Revision: 3876 Modified: trunk/scipy/sandbox/multigrid/adaptive.py trunk/scipy/sandbox/multigrid/sa.py trunk/scipy/sandbox/multigrid/tests/test_rs.py trunk/scipy/sandbox/multigrid/tests/test_sa.py Log: reverted back to older SA approach Modified: trunk/scipy/sandbox/multigrid/adaptive.py =================================================================== --- trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-30 01:17:40 UTC (rev 3875) +++ trunk/scipy/sandbox/multigrid/adaptive.py 2008-01-30 17:05:38 UTC (rev 3876) @@ -40,7 +40,7 @@ for AggOp in AggOps: P,B = sa_fit_candidates(AggOp,B) - I = sa_smoothed_prolongator(A,A,P) + I = sa_smoothed_prolongator(A,P) A = I.T.asformat(I.format) * A * I As.append(A) Ts.append(P) @@ -164,7 +164,7 @@ else: W_l = aggregation[len(AggOps)] P_l,x = sa_fit_candidates(W_l,x) #step 4c - I_l = sa_smoothed_prolongator(A_l,A_l,P_l) #step 4d + I_l = sa_smoothed_prolongator(A_l,P_l) #step 4d A_l = I_l.T.asformat(I_l.format) * A_l * I_l #step 4e #TODO change variable names I_l -> P, P_l -> T Modified: trunk/scipy/sandbox/multigrid/sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/sa.py 2008-01-30 01:17:40 UTC (rev 3875) +++ trunk/scipy/sandbox/multigrid/sa.py 2008-01-30 17:05:38 UTC (rev 3876) @@ -168,7 +168,7 @@ return Q,R -def sa_smoothed_prolongator(A,C,T,epsilon=0.0,omega=4.0/3.0): +def sa_smoothed_prolongator(A,T,epsilon=0.0,omega=4.0/3.0): """For a given matrix A and tentative prolongator T return the smoothed prolongator P @@ -185,7 +185,7 @@ A_filtered = sa_filtered_matrix(A,epsilon) #use filtered matrix for anisotropic problems # TODO use scale_rows() - D = diag_sparse(A_filtered) + D = A_filtered.diagonal() D_inv = 1.0 / D D_inv[D == 0] = 0 @@ -290,7 +290,7 @@ C = strength(A) AggOp = aggregate(C) T,B = tentative(AggOp,B) - P = smooth(A,C,T) + P = smooth(A,T) R = P.T.asformat(P.format) Modified: trunk/scipy/sandbox/multigrid/tests/test_rs.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_rs.py 2008-01-30 01:17:40 UTC (rev 3875) +++ trunk/scipy/sandbox/multigrid/tests/test_rs.py 2008-01-30 17:05:38 UTC (rev 3876) @@ -30,9 +30,7 @@ avg_convergence_ratio = (residuals[-1]/residuals[0])**(1.0/len(residuals)) - print "avg",avg_convergence_ratio + assert(avg_convergence_ratio < 0.10) - assert(avg_convergence_ratio < 0.15) - if __name__ == '__main__': nose.run(argv=['', __file__]) Modified: trunk/scipy/sandbox/multigrid/tests/test_sa.py =================================================================== --- trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-30 01:17:40 UTC (rev 3875) +++ trunk/scipy/sandbox/multigrid/tests/test_sa.py 2008-01-30 17:05:38 UTC (rev 3876) @@ -18,7 +18,7 @@ import scipy.sandbox.multigrid from scipy.sandbox.multigrid.sa import * from scipy.sandbox.multigrid.utils import diag_sparse -from scipy.sandbox.multigrid.gallery import poisson +from scipy.sandbox.multigrid.gallery import poisson, linear_elasticity #def sparsity(A): # A = A.copy() @@ -57,15 +57,6 @@ assert_almost_equal(S_result.todense(),S_expected.todense()) #assert_array_equal(sparsity(S_result).todense(),sparsity(S_expected).todense()) - ## two aggregates in 1D - #A = poisson( (6,), format='csr') - #AggOp = csr_matrix((ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) - #candidates = ones((6,1)) - - #T_result,coarse_candidates_result = sa_fit_candidates(AggOp,candidates) - #T_expected = csr_matrix((sqrt(1.0/3.0)*ones(6),array([0,0,0,1,1,1]),arange(7)),shape=(6,2)) - #assert_almost_equal(T_result.todense(),T_expected.todense()) - ##check simple block examples #A = csr_matrix(arange(16).reshape(4,4)) #A = A + A.T @@ -90,9 +81,6 @@ S_result = sa_standard_aggregation(C) assert_array_equal(S_result.todense(),S_expected.todense()) - #A = A.tobsr( blocksize=(1,1) ) - #S_result = sa_constant_interpolation(A,epsilon) - #assert_array_equal(S_result.todense(),S_expected.todense()) # def test_user_aggregation(self): @@ -180,6 +168,7 @@ self.cases.append(( poisson( (10000,), format='csr'), None)) self.cases.append(( poisson( (100,100), format='csr'), None)) + self.cases.append( linear_elasticity( (100,100), format='bsr') ) # TODO add unstructured tests @@ -194,14 +183,14 @@ x = rand(A.shape[0]) b = A*rand(A.shape[0]) #zeros_like(x) - x_sol,residuals = ml.solve(b,x0=x,maxiter=20,tol=1e-12,return_residuals=True) + x_sol,residuals = ml.solve(b,x0=x,maxiter=20,tol=1e-10,return_residuals=True) avg_convergence_ratio = (residuals[-1]/residuals[0])**(1.0/len(residuals)) - assert(avg_convergence_ratio < 0.25) + assert(avg_convergence_ratio < 0.3) def test_DAD(self): - A = poisson( (100,100), format='csr' ) + A = poisson( (200,200), format='csr' ) x = rand(A.shape[0]) b = rand(A.shape[0]) @@ -215,11 +204,9 @@ #TODO force 2 level method and check that result is the same - #sa1 = smoothed_aggregation_solver(A, B, max_levels=2, rescale=False) - sa2 = smoothed_aggregation_solver(D*A*D, D_inv * B, max_levels=2) + sa = smoothed_aggregation_solver(D*A*D, D_inv * B, max_levels=2) - #assert_almost_equal( sa2.Ps[0], sa1.Ps[0] - x_sol,residuals = sa2.solve(b,x0=x,maxiter=10,tol=1e-12,return_residuals=True) + x_sol,residuals = sa.solve(b,x0=x,maxiter=10,tol=1e-12,return_residuals=True) avg_convergence_ratio = (residuals[-1]/residuals[0])**(1.0/len(residuals)) From scipy-svn at scipy.org Wed Jan 30 21:44:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 30 Jan 2008 20:44:36 -0600 (CST) Subject: [Scipy-svn] r3877 - in trunk/scipy: sparse splinalg splinalg/isolve splinalg/tests Message-ID: <20080131024436.504BE39C153@new.scipy.org> Author: wnbell Date: 2008-01-30 20:44:28 -0600 (Wed, 30 Jan 2008) New Revision: 3877 Added: trunk/scipy/splinalg/interface.py trunk/scipy/splinalg/isolve/minres.py trunk/scipy/splinalg/tests/ trunk/scipy/splinalg/tests/test_interface.py Modified: trunk/scipy/sparse/compressed.py trunk/scipy/splinalg/__init__.py trunk/scipy/splinalg/setup.py Log: added LinearOperator added draft MINRES implementation Modified: trunk/scipy/sparse/compressed.py =================================================================== --- trunk/scipy/sparse/compressed.py 2008-01-30 17:05:38 UTC (rev 3876) +++ trunk/scipy/sparse/compressed.py 2008-01-31 02:44:28 UTC (rev 3877) @@ -8,7 +8,7 @@ import numpy from numpy import array, matrix, asarray, asmatrix, zeros, rank, intc, \ empty, hstack, isscalar, ndarray, shape, searchsorted, empty_like, \ - where, concatenate + where, concatenate, transpose from base import spmatrix, isspmatrix, SparseEfficiencyWarning from data import _data_matrix @@ -364,9 +364,9 @@ def rmatvec(self, other, conjugate=True): if conjugate: - return self.transpose().conj() * other + return transpose( self.transpose().conj().matvec(transpose(other)) ) else: - return self.transpose() * other + return transpose( self.transpose().matvec(transpose(other)) ) def getdata(self, ind): return self.data[ind] Modified: trunk/scipy/splinalg/__init__.py =================================================================== --- trunk/scipy/splinalg/__init__.py 2008-01-30 17:05:38 UTC (rev 3876) +++ trunk/scipy/splinalg/__init__.py 2008-01-31 02:44:28 UTC (rev 3877) @@ -4,6 +4,7 @@ from isolve import * from dsolve import * +from interface import * __all__ = filter(lambda s:not s.startswith('_'),dir()) from scipy.testing.pkgtester import Tester Added: trunk/scipy/splinalg/interface.py =================================================================== --- trunk/scipy/splinalg/interface.py 2008-01-30 17:05:38 UTC (rev 3876) +++ trunk/scipy/splinalg/interface.py 2008-01-31 02:44:28 UTC (rev 3877) @@ -0,0 +1,87 @@ +import numpy as np +from scipy.sparse.sputils import isshape +from scipy.sparse import isspmatrix + +__all__ = ['LinearOperator', 'aslinearoperator'] + +class LinearOperator: + def __init__( self, shape, matvec, rmatvec=None, dtype=None ): + """Common interface for performing matrix vector products + """ + shape = tuple(shape) + + if not isshape(shape): + raise ValueError('invalid shape') + + self.shape = shape + self.matvec = matvec + + if rmatvec is None: + def rmatvec(x): + raise NotImplementedError('rmatvec is not defined') + self.rmatvec = rmatvec + else: + self.rmatvec = rmatvec + + if dtype is not None: + self.dtype = np.dtype(dtype) + + def __repr__(self): + M,N = self.shape + if hasattr(self,'dtype'): + dt = 'dtype=' + str(self.dtype) + else: + dt = 'unspecified dtype' + + return '<%dx%d LinearOperator with %s>' % (M,N,dt) + +def aslinearoperator(A): + """Return A as a LinearOperator + + 'A' may be any of the following types + - ndarray + - matrix + - sparse matrix (e.g. csr_matrix, lil_matrix, etc.) + - LinearOperator + - An object with .shape and .matvec attributes + + See the LinearOperator documentation for additonal information. + + Examples + ======== + + >>> from scipy import matrix + >>> M = matrix( [[1,2,3],[4,5,6]], dtype='int32' ) + >>> aslinearoperator( M ) + <2x3 LinearOperator with dtype=int32> + + """ + + if isinstance(A, LinearOperator): + return A + + elif isinstance(A, np.ndarray) or isinstance(A,np.matrix): + def matvec(x): + return np.dot(np.asarray(A),x) + def rmatvec(x): + return np.dot(x,np.asarray(A)) + return LinearOperator( A.shape, matvec, rmatvec=rmatvec, dtype=A.dtype ) + + elif isspmatrix(A): + return LinearOperator( A.shape, A.matvec, rmatvec=A.rmatvec, dtype=A.dtype ) + + else: + if hasattr(A,'shape') and hasattr(A,'matvec'): + rmatvec = None + dtype = None + + if hasattr(A,'rmatvec'): + rmatvec = A.rmatvec + if hasattr(A,'dtype'): + dtype = A.dtype + return LinearOperator(A.shape, A.matvec, rmatvec=rmatvec, dtype=dtype) + + else: + raise TypeError('type not understood') + + Added: trunk/scipy/splinalg/isolve/minres.py =================================================================== --- trunk/scipy/splinalg/isolve/minres.py 2008-01-30 17:05:38 UTC (rev 3876) +++ trunk/scipy/splinalg/isolve/minres.py 2008-01-31 02:44:28 UTC (rev 3877) @@ -0,0 +1,297 @@ +from numpy import sqrt, inner, finfo +from numpy.linalg import norm + +def psolve(x): return x +def check_sizes(A,x,b): pass + +def minres(A, b, x0=None, shift=0.0, tol=1e-5, maxiter=None, xtype=None, + precond=None, callback=None, show=False, check=False): + """Use the Minimum Residual Method (MINRES) to solve Ax=b + + MINRES minimizes norm(A*x - b) for the symmetric matrix A. Unlike + the Conjugate Gradient method, A can be indefinite or singular. + + If shift != 0 then the method solves (A - shift*I)x = b + + + Parameters + ========== + TODO + + References + ========== + + Solution of sparse indefinite systems of linear equations, + C. C. Paige and M. A. Saunders (1975), + SIAM J. Numer. Anal. 12(4), pp. 617-629. + http://www.stanford.edu/group/SOL/software/minres.html + + This file is a translation of the following MATLAB implementation: + http://www.stanford.edu/group/SOL/software/minres/matlab/ + + """ + + show = True #TODO remove + check = True #TODO remove + + first = 'Enter minres. ' + last = 'Exit minres. ' + + assert(A.shape[0] == A.shape[1]) + assert(A.shape[1] == len(b)) + + b = asarray(b).ravel() + n = A.shape[0] + + if maxiter is None: + maxiter = 5 * n + + matvec = A.matvec + + msg =[' beta2 = 0. If M = I, b and x are eigenvectors ', # -1 + ' beta1 = 0. The exact solution is x = 0 ', # 0 + ' A solution to Ax = b was found, given rtol ', # 1 + ' A least-squares solution was found, given rtol ', # 2 + ' Reasonable accuracy achieved, given eps ', # 3 + ' x has converged to an eigenvector ', # 4 + ' acond has exceeded 0.1/eps ', # 5 + ' The iteration limit was reached ', # 6 + ' Aname does not define a symmetric matrix ', # 7 + ' Mname does not define a symmetric matrix ', # 8 + ' Mname does not define a pos-def preconditioner '] # 9 + + + if show: + print first + 'Solution of symmetric Ax = b' + print first + 'n = %3g shift = %23.14e' % (n,shift) + print first + 'itnlim = %3g rtol = %11.2e' % (maxiter,tol) + print + + istop = 0; itn = 0; Anorm = 0; Acond = 0; + rnorm = 0; ynorm = 0; + + xtype = A.dtype #TODO update + + eps = finfo(xtype).eps + + x = zeros( n, dtype=xtype ) + + # Set up y and v for the first Lanczos vector v1. + # y = beta1 P' v1, where P = C**(-1). + # v is really P' v1. + + y = b + r1 = b + + y = psolve(b) + + beta1 = inner(b,y) + + if beta1 < 0: + raise ValueError('indefinite preconditioner') + elif beta1 == 0: + return x + + beta1 = sqrt( beta1 ) + + if check: + # see if M is symmetric + r2 = psolve(y) + s = inner(y,y) + t = inner(r1,r2) + z = abs( s - t ) + epsa = (s + eps) * eps**(1.0/3.0) + if z > epsa: + raise ValueError('non-symmetric preconditioner') + + # see if A is symmetric + w = matvec(y) + r2 = matvec(w) + s = inner(w,w) + t = inner(y,r2) + epsa = (s + eps) * eps**(1.0/3.0) + if z > epsa: + raise ValueError('non-symmetric matrix') + + + # Initialize other quantities + oldb = 0; beta = beta1; dbar = 0; epsln = 0; + qrnorm = beta1; phibar = beta1; rhs1 = beta1; + rhs2 = 0; tnorm2 = 0; ynorm2 = 0; + cs = -1; sn = 0; + w = zeros(n, dtype=xtype) + w2 = zeros(n, dtype=xtype) + r2 = r1 + + if show: + print + print + print ' Itn x(1) Compatible LS norm(A) cond(A) gbar/|A|' + + while itn < maxiter: + itn += 1 + + s = 1.0/beta + v = s*y + + y = matvec(v) + y = y - shift * v + + if itn >= 2: + y = y - (beta/oldb)*r1 + + alfa = inner(v,y) + y = y - (alfa/beta)*r2 + r1 = r2 + r2 = y + y = psolve(r2) + oldb = beta + beta = inner(r2,y) + if beta < 0: + raise ValueError('non-symmetric matrix') + beta = sqrt(beta) + tnorm2 += alfa**2 + oldb**2 + beta**2 + + if itn == 1: + if beta/beta1 <= 10*eps: + istop = -1 # Terminate later + #tnorm2 = alfa**2 ?? + gmax = abs(alfa) + gmin = gmax + + # Apply previous rotation Qk-1 to get + # [deltak epslnk+1] = [cs sn][dbark 0 ] + # [gbar k dbar k+1] [sn -cs][alfak betak+1]. + + oldeps = epsln + delta = cs * dbar + sn * alfa # delta1 = 0 deltak + gbar = sn * dbar - cs * alfa # gbar 1 = alfa1 gbar k + epsln = sn * beta # epsln2 = 0 epslnk+1 + dbar = - cs * beta # dbar 2 = beta2 dbar k+1 + root = norm([gbar, dbar]) + Arnorm = phibar * root + + # Compute the next plane rotation Qk + + gamma = norm([gbar, beta]) # gammak + gamma = max(gamma, eps) + cs = gbar / gamma # ck + sn = beta / gamma # sk + phi = cs * phibar # phik + phibar = sn * phibar # phibark+1 + + # Update x. + + denom = 1.0/gamma + w1 = w2 + w2 = w + w = (v - oldeps*w1 - delta*w2) * denom + x = x + phi*w + + # Go round again. + + gmax = max(gmax, gamma) + gmin = min(gmin, gamma) + z = rhs1 / gamma + ynorm2 = z**2 + ynorm2 + rhs1 = rhs2 - delta*z + rhs2 = - epsln*z + + # Estimate various norms and test for convergence. + + Anorm = sqrt( tnorm2 ) + ynorm = sqrt( ynorm2 ) + epsa = Anorm * eps + epsx = Anorm * ynorm * eps + epsr = Anorm * ynorm * tol + diag = gbar + + if diag == 0: diag = epsa + + qrnorm = phibar + rnorm = qrnorm + test1 = rnorm / (Anorm*ynorm) # ||r|| / (||A|| ||x||) + test2 = root / Anorm # ||Ar|| / (||A|| ||r||) + + # Estimate cond(A). + # In this version we look at the diagonals of R in the + # factorization of the lower Hessenberg matrix, Q * H = R, + # where H is the tridiagonal matrix from Lanczos with one + # extra row, beta(k+1) e_k^T. + + Acond = gmax/gmin + + # See if any of the stopping criteria are satisfied. + # In rare cases, istop is already -1 from above (Abar = const*I). + + if istop == 0: + t1 = 1 + test1 # These tests work if tol < eps + t2 = 1 + test2 + if t2 <= 1 : istop = 2 + if t1 <= 1 : istop = 1 + + if itn >= maxiter : istop = 6 + if Acond >= 0.1/eps : istop = 4 + if epsx >= beta1 : istop = 3 + #if rnorm <= epsx : istop = 2 + #if rnorm <= epsr : istop = 1 + if test2 <= tol : istop = 2 + if test1 <= tol : istop = 1 + + # See if it is time to print something. + + prnt = False + if n <= 40 : prnt = True + if itn <= 10 : prnt = True + if itn >= maxiter-10 : prnt = True + if itn % 10 == 0 : prnt = True + if qrnorm <= 10*epsx : prnt = True + if qrnorm <= 10*epsr : prnt = True + if Acond <= 1e-2/eps : prnt = True + if istop != 0 : prnt = True + + if show and prnt: + str1 = '%6g %12.5e %10.3e' % (itn, x[0], test1) + str2 = ' %10.3e' % (test2,) + str3 = ' %8.1e %8.1e %8.1e' % (Anorm, Acond, gbar/Anorm) + + print str1 + str2 + str3 + + if itn % 10 == 0: print + + if callback is not None: + callback(x) + + if istop > 0: break + + + if show: + print + print last + ' istop = %3g itn =%5g' % (istop,itn) + print last + ' Anorm = %12.4e Acond = %12.4e' % (Anorm,Acond) + print last + ' rnorm = %12.4e ynorm = %12.4e' % (rnorm,ynorm) + print last + ' Arnorm = %12.4e' % (Arnorm,) + print last + msg[istop+1] + + return x + + +if __name__ == '__main__': + from scipy import * + from scipy.sparse import * + from scipy.splinalg import * + from scipy.sandbox.multigrid import * + + n = 100 + + residuals = [] + + def cb(x): + residuals.append(norm(b - A*x)) + + #A = poisson((10,),format='csr') + A = spdiags( [arange(1,n+1,dtype=float)], [0], n, n, format='csr') + b = ones( A.shape[0] ) + #x = minres(A,b,tol=1e-12,maxiter=None,callback=cb) + x = cg(A,b,x0=b,tol=1e-12,maxiter=None,callback=cb)[0] + Modified: trunk/scipy/splinalg/setup.py =================================================================== --- trunk/scipy/splinalg/setup.py 2008-01-30 17:05:38 UTC (rev 3876) +++ trunk/scipy/splinalg/setup.py 2008-01-31 02:44:28 UTC (rev 3877) @@ -8,6 +8,8 @@ config.add_subpackage(('isolve')) config.add_subpackage(('dsolve')) + config.add_data_dir('tests') + return config if __name__ == '__main__': Added: trunk/scipy/splinalg/tests/test_interface.py =================================================================== --- trunk/scipy/splinalg/tests/test_interface.py 2008-01-30 17:05:38 UTC (rev 3876) +++ trunk/scipy/splinalg/tests/test_interface.py 2008-01-31 02:44:28 UTC (rev 3877) @@ -0,0 +1,64 @@ +#!/usr/bin/env python +""" Test functions for the splinalg.interface module +""" + +from scipy.testing import * + +import numpy +from numpy import array, matrix, ones, ravel +from scipy.sparse import csr_matrix + +from scipy.splinalg.interface import * + + +class TestInterface(TestCase): + def test_aslinearoperator(self): + cases = [] + + cases.append( matrix([[1,2,3],[4,5,6]]) ) + cases.append( array([[1,2,3],[4,5,6]]) ) + cases.append( csr_matrix([[1,2,3],[4,5,6]]) ) + + class matlike: + def __init__(self): + self.dtype = numpy.dtype('int') + self.shape = (2,3) + def matvec(self,x): + y = array([ 1*x[0] + 2*x[1] + 3*x[2], + 4*x[0] + 5*x[1] + 6*x[2]]) + if len(x.shape) == 2: + y = y.reshape(-1,1) + return y + + def rmatvec(self,x): + if len(x.shape) == 1: + y = array([ 1*x[0] + 4*x[1], + 2*x[0] + 5*x[1], + 3*x[0] + 6*x[1]]) + return y + else: + y = array([ 1*x[0,0] + 4*x[0,1], + 2*x[0,0] + 5*x[0,1], + 3*x[0,0] + 6*x[0,1]]) + return y.reshape(1,-1) + + return y + + cases.append( matlike() ) + + + for M in cases: + A = aslinearoperator(M) + M,N = A.shape + + assert_equal(A.matvec(array([1,2,3])), [14,32]) + assert_equal(A.matvec(array([[1],[2],[3]])),[[14],[32]]) + + assert_equal(A.rmatvec(array([1,2])), [9,12,15]) + assert_equal(A.rmatvec(array([[1,2]])),[[9,12,15]]) + + if hasattr(M,'dtype'): + assert_equal(A.dtype, M.dtype) + +if __name__ == "__main__": + nose.run(argv=['', __file__]) From scipy-svn at scipy.org Thu Jan 31 12:31:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 31 Jan 2008 11:31:47 -0600 (CST) Subject: [Scipy-svn] r3878 - trunk/scipy/splinalg/isolve/tests Message-ID: <20080131173147.096E939C038@new.scipy.org> Author: wnbell Date: 2008-01-31 11:31:42 -0600 (Thu, 31 Jan 2008) New Revision: 3878 Modified: trunk/scipy/splinalg/isolve/tests/test_iterative.py Log: revised isolve unittests Modified: trunk/scipy/splinalg/isolve/tests/test_iterative.py =================================================================== --- trunk/scipy/splinalg/isolve/tests/test_iterative.py 2008-01-31 02:44:28 UTC (rev 3877) +++ trunk/scipy/splinalg/isolve/tests/test_iterative.py 2008-01-31 17:31:42 UTC (rev 3878) @@ -1,73 +1,112 @@ #!/usr/bin/env python -""" Test functions for the splinalg.isolve.iterative module +""" Test functions for the splinalg.isolve module """ -import sys +from scipy.testing import * -from numpy import zeros, dot, diag, ones -from scipy.testing import * +from numpy import zeros, dot, diag, ones, arange, array from numpy.random import rand -#from numpy import arange, add, array, dot, zeros, identity, conjugate, transpose +from scipy.linalg import norm +from scipy.sparse import spdiags -from scipy.linalg import norm from scipy.splinalg.isolve import cg, cgs, bicg, bicgstab, gmres, qmr +#def callback(x): +# global A, b +# res = b-dot(A,x) +# #print "||A.x - b|| = " + str(norm(dot(A,x)-b)) -def callback(x): - global A, b - res = b-dot(A,x) - #print "||A.x - b|| = " + str(norm(dot(A,x)-b)) -class TestIterativeSolvers(TestCase): - def __init__(self, *args, **kwds): - TestCase.__init__(self, *args, **kwds) - self.setUp() - def setUp (self): - global A, b - n = 10 - self.tol = 1e-5 - self.x0 = zeros(n, float) - A = rand(n, n)+diag(4*ones(n)) - self.A = 0.5 * (A+A.T) - A = self.A - self.b = rand(n) - b = self.b +data = ones((3,10)) +data[0,:] = 2 +data[1,:] = -1 +data[2,:] = -1 +Poisson1D = spdiags( data, [0,-1,1], 10, 10, format='csr') - def test_cg(self): - bx0 = self.x0.copy() - x, info = cg(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol +data = array([[6, -5, 2, 7, -1, 10, 4, -3, -8, 9]],dtype='d') +RandDiag = spdiags( data, [0], 10, 10, format='csr' ) - def test_bicg(self): - bx0 = self.x0.copy() - x, info = bicg(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol +class TestIterative(TestCase): + def setUp(self): + # list of tuples (solver, symmetric, positive_definite ) + self.solvers = [] + self.solvers.append( (cg, True, True) ) + self.solvers.append( (cgs, False, False) ) + self.solvers.append( (bicg, False, False) ) + self.solvers.append( (bicgstab, False, False) ) + self.solvers.append( (gmres, False, False) ) + self.solvers.append( (qmr, False, False) ) + #self.solvers.append( (minres, True, False) ) + + # list of tuples (A, symmetric, positive_definite ) + self.cases = [] - def test_cgs(self): - bx0 = self.x0.copy() - x, info = cgs(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol + # Symmetric and Positive Definite + self.cases.append( (Poisson1D,True,True) ) - def test_bicgstab(self): - bx0 = self.x0.copy() - x, info = bicgstab(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol + # Symmetric and Negative Definite + self.cases.append( (-Poisson1D,True,False) ) - def test_gmres(self): - bx0 = self.x0.copy() - x, info = gmres(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol + # Symmetric and Indefinite + self.cases.append( (RandDiag,True,False) ) - def test_qmr(self): - bx0 = self.x0.copy() - x, info = qmr(self.A, self.b, self.x0, callback=callback) - assert_array_equal(bx0, self.x0) - assert norm(dot(self.A, x) - self.b) < 5*self.tol + # Non-symmetric and Positive Definite + # bicg and cgs fail to converge on this one + #data = ones((2,10)) + #data[0,:] = 2 + #data[1,:] = -1 + #A = spdiags( data, [0,-1], 10, 10, format='csr') + #self.cases.append( (A,False,True) ) + + + def test_convergence(self): + """test whether all methods converge""" + + tol = 1e-8 + + for solver,req_sym,req_pos in self.solvers: + for A,sym,pos in self.cases: + if req_sym and not sym: continue + if req_pos and not pos: continue + + b = arange(A.shape[0], dtype=float) + x0 = 0*b + + x, info = solver(A, b, x0=x0, tol=tol) + + assert_array_equal(x0, 0*b) #ensure that x0 is not overwritten + assert_equal(info,0) + + assert( norm(b - A*x) < tol*norm(b) ) + + def test_precond(self): + """test whether all methods accept a preconditioner""" + + tol = 1e-8 + + for solver,req_sym,req_pos in self.solvers: + for A,sym,pos in self.cases: + if req_sym and not sym: continue + if req_pos and not pos: continue + + M,N = A.shape + D = spdiags( [1.0/A.diagonal()], [0], M, N) + def precond(b,which=None): + return D*b + + A = A.copy() + A.psolve = precond + A.rpsolve = precond + + b = arange(A.shape[0], dtype=float) + x0 = 0*b + + x, info = solver(A, b, x0=x0, tol=tol) + + assert_equal(info,0) + assert( norm(b - A*x) < tol*norm(b) ) + + if __name__ == "__main__": nose.run(argv=['', __file__]) From scipy-svn at scipy.org Thu Jan 31 19:24:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 31 Jan 2008 18:24:38 -0600 (CST) Subject: [Scipy-svn] r3879 - in trunk/scipy/ndimage: . register Message-ID: <20080201002438.86F7A39C02A@new.scipy.org> Author: tom.waite Date: 2008-01-31 18:24:16 -0600 (Thu, 31 Jan 2008) New Revision: 3879 Added: trunk/scipy/ndimage/register/ trunk/scipy/ndimage/register/Register_EXT.c trunk/scipy/ndimage/register/Register_IMPL.c trunk/scipy/ndimage/register/__init__.py trunk/scipy/ndimage/register/setup.py trunk/scipy/ndimage/register/setup.pyc Log: Initial registration code for NIPY Added: trunk/scipy/ndimage/register/Register_EXT.c =================================================================== --- trunk/scipy/ndimage/register/Register_EXT.c 2008-01-31 17:31:42 UTC (rev 3878) +++ trunk/scipy/ndimage/register/Register_EXT.c 2008-02-01 00:24:16 UTC (rev 3879) @@ -0,0 +1,157 @@ +/* Python extension interface code */ + +#include "Python.h" +#include "numpy/arrayobject.h" + +static PyObject *Register_Histogram(PyObject *self, PyObject *args) +{ + /* + joint histogram memory is created in python to avoid memory leak problem + */ + + int num; + int numM; + int nd; + int type; + int itype; + int nd_histo; + int nd_rotmatrix; + int nd_S; + npy_intp *dimsF; + npy_intp *dimsG; + npy_intp *dims_histo; + npy_intp *dims_rotmatrix; + npy_intp *dims_S; + unsigned char *imageG; + unsigned char *imageF; + double *pHisto; + double *M; + int *S; + PyObject *imgArray1 = NULL; + PyObject *imgArray2 = NULL; + PyObject *rotArray = NULL; + PyObject *SArray = NULL; + PyObject *hArray = NULL; + + if(!PyArg_ParseTuple(args, "OOOOO", &imgArray1, &imgArray2, &rotArray, &SArray, &hArray)) + goto exit; + + /* check in the Python code that F and G are the same dims, type */ + imageG = (unsigned char *)PyArray_DATA(imgArray1); + imageF = (unsigned char *)PyArray_DATA(imgArray2); + nd = PyArray_NDIM(imgArray1); + /* reads dims as 0 = layers, 1 = rows, 2 = cols */ + dimsF = PyArray_DIMS(imgArray1); + dimsG = PyArray_DIMS(imgArray2); + type = PyArray_TYPE(imgArray1); + num = PyArray_SIZE(imgArray1); + + M = (double *)PyArray_DATA(rotArray); + nd_rotmatrix = PyArray_NDIM(rotArray); + dims_rotmatrix = PyArray_DIMS(rotArray); + numM = PyArray_SIZE(rotArray); + + S = (int *)PyArray_DATA(SArray); + nd_S = PyArray_NDIM(SArray); + dims_S = PyArray_DIMS(SArray); + + pHisto = (double *)PyArray_DATA(hArray); + nd_histo = PyArray_NDIM(hArray); + dims_histo = PyArray_DIMS(hArray); + /* check to make sure this is 256x256 */ + + if(!NI_Histogram2D((int)dimsF[0], (int)dimsF[1], (int)dimsF[2], + (int)dimsG[0], (int)dimsG[1], (int)dimsG[2], + S, M, imageG, imageF, pHisto)) + goto exit; + +exit: + + /* return the 2D histogram */ + return PyErr_Occurred() ? NULL : (PyObject*)Py_BuildValue(""); + +} + + +static PyObject *Register_HistogramLite(PyObject *self, PyObject *args) +{ + /* + joint histogram memory is created in python to avoid memory leak problem + */ + + int num; + int nd; + int type; + int itype; + int nd_histo; + int nd_rotmatrix; + int nd_S; + npy_intp *dimsF; + npy_intp *dimsG; + npy_intp *dims_histo; + npy_intp *dims_rotmatrix; + npy_intp *dims_S; + unsigned char *imageG; + unsigned char *imageF; + double *pHisto; + double *M; + int *S; + PyObject *imgArray1 = NULL; + PyObject *imgArray2 = NULL; + PyObject *rotArray = NULL; + PyObject *SArray = NULL; + PyObject *hArray = NULL; + + if(!PyArg_ParseTuple(args, "OOOOO", &imgArray1, &imgArray2, &rotArray, &SArray, &hArray)) + goto exit; + + /* check in the Python code that F and G are the same dims, type */ + imageG = (unsigned char *)PyArray_DATA(imgArray1); + imageF = (unsigned char *)PyArray_DATA(imgArray2); + /* reads dims as 0 = layers, 1 = rows, 2 = cols */ + nd = PyArray_NDIM(imgArray1); + dimsF = PyArray_DIMS(imgArray1); + dimsG = PyArray_DIMS(imgArray2); + type = PyArray_TYPE(imgArray1); + num = PyArray_SIZE(imgArray1); + + M = (double *)PyArray_DATA(rotArray); + nd_rotmatrix = PyArray_NDIM(rotArray); + dims_rotmatrix = PyArray_DIMS(rotArray); + + S = (int *)PyArray_DATA(SArray); + nd_S = PyArray_NDIM(SArray); + dims_S = PyArray_DIMS(SArray); + + pHisto = (double *)PyArray_DATA(hArray); + nd_histo = PyArray_NDIM(hArray); + dims_histo = PyArray_DIMS(hArray); + /* check to make sure this is 256x256 */ + + if(!NI_Histogram2DLite((int)dimsF[0], (int)dimsF[1], (int)dimsF[2], + (int)dimsG[0], (int)dimsG[1], (int)dimsG[2], + S, M, imageG, imageF, pHisto)) + goto exit; + +exit: + + /* return the 2D histogram */ + return PyErr_Occurred() ? NULL : (PyObject*)Py_BuildValue("O", hArray); + +} + + +static PyMethodDef RegisterMethods[] = +{ + { "register_histogram", Register_Histogram, METH_VARARGS, NULL }, + { "register_histogram_lite", Register_HistogramLite, METH_VARARGS, NULL }, + { NULL, NULL, 0, NULL}, +}; + +void init_register(void) +{ + Py_InitModule("_register", RegisterMethods); + import_array(); +} + + Added: trunk/scipy/ndimage/register/Register_IMPL.c =================================================================== --- trunk/scipy/ndimage/register/Register_IMPL.c 2008-01-31 17:31:42 UTC (rev 3878) +++ trunk/scipy/ndimage/register/Register_IMPL.c 2008-02-01 00:24:16 UTC (rev 3879) @@ -0,0 +1,305 @@ +#include +#include + +float trilinear_A(unsigned char *pVolume, int x, int y, int z, float dx, float dy, float dz, int dims[]){ + + // Vxyz for [0,1] values of x, y, z + int V000; + int V100; + int V010; + int V001; + int V011; + int V101; + int V110; + int V111; + + int ptr_x0; + int ptr_y0; + int ptr_z0; + + int ptr_x1; + int ptr_y1; + int ptr_z1; + + float valueXYZ; + + ptr_x0 = x; + ptr_y0 = y * dims[0]; + ptr_z0 = z * dims[1]; + + ptr_x1 = ptr_x0 + 1; + ptr_y1 = ptr_y0 + dims[0]; + ptr_z1 = ptr_z0 + dims[1]; + + V000 = pVolume[ptr_x0+ptr_y0+ptr_z0]; + V100 = pVolume[ptr_x1+ptr_y0+ptr_z0]; + V010 = pVolume[ptr_x0+ptr_y1+ptr_z0]; + V001 = pVolume[ptr_x0+ptr_y0+ptr_z1]; + V011 = pVolume[ptr_x0+ptr_y1+ptr_z1]; + V101 = pVolume[ptr_x1+ptr_y0+ptr_z1]; + V110 = pVolume[ptr_x1+ptr_y1+ptr_z0]; + V111 = pVolume[ptr_x1+ptr_y1+ptr_z1]; + + // dx, dy, dz are increments in x, y, z + // dx = 0 is x = 1 as x, y and z are [0, 1] in range + + valueXYZ = + V000 * (1.0-dx) * (1.0 - dy) * (1.0 - dz) + + V100 * (dx) * (1.0 - dy) * (1.0 - dz) + + V010 * (1.0-dx) * (dy) * (1.0 - dz) + + V001 * (1.0-dx) * (1.0 - dy) * (dz) + + V101 * (dx) * (1.0 - dy) * (dz) + + V011 * (1.0-dx) * (dy) * (dz) + + V110 * (dx) * (dy) * (1.0 - dz) + + V111 * (dx) * (dy) * (dz); + + + return(valueXYZ); + +} + +float trilinear_B(unsigned char *pVolume, float dx, float dy, float dz, int corners[]){ + + // Vxyz for [0,1] values of x, y, z + int V000; + int V100; + int V010; + int V001; + int V011; + int V101; + int V110; + int V111; + + int ptr_x0 = corners[0]; + int ptr_y0 = corners[1]; + int ptr_z0 = corners[2]; + + int ptr_x1 = corners[3]; + int ptr_y1 = corners[4]; + int ptr_z1 = corners[5]; + + float valueXYZ; + + V000 = pVolume[ptr_x0+ptr_y0+ptr_z0]; + V100 = pVolume[ptr_x1+ptr_y0+ptr_z0]; + V010 = pVolume[ptr_x0+ptr_y1+ptr_z0]; + V001 = pVolume[ptr_x0+ptr_y0+ptr_z1]; + V011 = pVolume[ptr_x0+ptr_y1+ptr_z1]; + V101 = pVolume[ptr_x1+ptr_y0+ptr_z1]; + V110 = pVolume[ptr_x1+ptr_y1+ptr_z0]; + V111 = pVolume[ptr_x1+ptr_y1+ptr_z1]; + + // dx, dy, dz are increments in x, y, z + // dx = 0 is x = 1 as x, y and z are [0, 1] in range + + valueXYZ = + V000 * (1.0-dx) * (1.0 - dy) * (1.0 - dz) + + V100 * (dx) * (1.0 - dy) * (1.0 - dz) + + V010 * (1.0-dx) * (dy) * (1.0 - dz) + + V001 * (1.0-dx) * (1.0 - dy) * (dz) + + V101 * (dx) * (1.0 - dy) * (dz) + + V011 * (1.0-dx) * (dy) * (dz) + + V110 * (dx) * (dy) * (1.0 - dz) + + V111 * (dx) * (dy) * (dz); + + + return(valueXYZ); + +} + +int NI_Histogram2D(int layersF, int rowsF, int colsF, int layersG, int rowsG, int colsG, + int *dimSteps, double *M, unsigned char *imageG, unsigned char *imageF, double *H) +{ + + int status; + int seed; + int dimsF[3]; + int dimsG[3]; + int dims_F[2]; + int dims_G[2]; + int ivf, ivg; + float ran_x, ran_y, ran_z; + float vf, delta; + float x, y, z; + float dx, dy, dz; + float xp, yp, zp; + float rx, ry, rz; + + dimsF[0] = colsF; + dimsF[1] = rowsF; + dimsF[2] = layersF; + dimsG[0] = colsG; + dimsG[1] = rowsG; + dimsG[2] = layersG; + + dims_G[0] = dimsG[0]; + dims_G[1] = dimsG[0]*dimsG[1]; + dims_F[0] = dimsF[0]; + dims_F[1] = dimsF[0]*dimsF[1]; + + seed = 1000; + srand(seed); + + /* because of stochastic sampling, subtract 1 from upper bounds */ + for(z = 0.0; z < layersG-dimSteps[2]-1; z += dimSteps[2]){ + for(y = 0.0; y < rowsG-dimSteps[1]-1; y += dimSteps[1]){ + for(x = 0.0; x < colsG-dimSteps[0]-1; x += dimSteps[0]){ + /* positive jitter the x, y, z values */ + ran_x = 1.0 * rand()/((float)RAND_MAX); + ran_y = 1.0 * rand()/((float)RAND_MAX); + ran_z = 1.0 * rand()/((float)RAND_MAX); + dx = x + ran_x*dimSteps[0]; + dy = y + ran_y*dimSteps[1]; + dz = z + ran_z*dimSteps[2]; + + /* get the 'from' coordinates */ + xp = M[0]*dx + M[1]*dy + M[2]*dz + M[3]; + yp = M[4]*dx + M[5]*dy + M[6]*dz + M[7]; + zp = M[8]*dx + M[9]*dy + M[10]*dz + M[11]; + /* clip the resample window */ + if((zp >= 0.0 && zp < layersF-dimSteps[2]) && + (yp >= 0.0 && yp < rowsF-dimSteps[1]) && + (xp >= 0.0 && xp < colsF-dimSteps[0])){ + /* resample the coordinates using a trilinear interpolation */ + /* resample imageF using the rotated-jittered xyz coordinates */ + rx = xp - (int)xp; + ry = yp - (int)yp; + rz = zp - (int)zp; + vf = trilinear_A(imageF, (int)dx, (int)dy, (int)dz, rx, ry, rz, dims_F); + /* floor */ + ivf = (int)vf; + delta = vf - ivf; + /* resample imageG using the jittered xyz coordinates */ + rx = dx - (int)dx; + ry = dy - (int)dy; + rz = dz - (int)dz; + ivg = (int)trilinear_A(imageG, (int)xp, (int)yp, (int)zp, rx, ry, rz, dims_G); + /* ivf will be < 255 as 8 bit data and trilinear doesn't ring */ + H[ivf+256*ivg] += 1.0 - delta; + if(ivf < 255){ + H[ivf+1+256*ivg] += delta; + } + } + } + } + } + + status = 1; + + return status; + +} + + + +int NI_Histogram2DLite(int layersF, int rowsF, int colsF, int layersG, int rowsG, int colsG, + int *dimSteps, double *M, unsigned char *imageG, unsigned char *imageF, double *H) +{ + + int i; + int status; + int sliceG; + int rowG; + int sliceSizeG; + int dimsF[3]; + int dimsG[3]; + int dims[2]; + int ivf, ivg; + float vf, delta; + float x, y, z; + float xp, yp, zp; + float dx, dy, dz; + + int ptr_x0; + int ptr_y0; + int ptr_z0; + int ptr_x1; + int ptr_y1; + int ptr_z1; + // + // Vxyz for [0,1] values of x, y, z + // + int V000; + int V100; + int V010; + int V001; + int V011; + int V101; + int V110; + int V111; + float valueXYZ; + + // + // G is fixed; F is rotated + // + sliceSizeG = rowsG * colsG; + dimsF[0] = colsF; + dimsF[1] = rowsF; + dimsF[2] = layersF; + dimsG[0] = colsG; + dimsG[1] = rowsG; + dimsG[2] = layersG; + + dims[0] = dimsF[0]; + dims[1] = dimsF[0]*dimsF[1]; + + for(z = 0.0; z < layersG-dimSteps[2]-1; z += dimSteps[2]){ + sliceG = (int)z * sliceSizeG; + for(y = 0.0; y < rowsG-dimSteps[1]-1; y += dimSteps[1]){ + rowG = (int)y * colsG; + for(x = 0.0; x < colsG-dimSteps[0]-1; x += dimSteps[0]){ + // get the 'from' coordinates + xp = M[0]*x + M[1]*y + M[2]*z + M[3]; + yp = M[4]*x + M[5]*y + M[6]*z + M[7]; + zp = M[8]*x + M[9]*y + M[10]*z + M[11]; + // clip the resample window + if((zp >= 0.0 && zp < layersF-dimSteps[2]) && + (yp >= 0.0 && yp < rowsF-dimSteps[1]) && + (xp >= 0.0 && xp < colsF-dimSteps[0])){ + + // corners of the 3D unit volume cube + ptr_z0 = (int)zp * dims[1]; + ptr_z1 = ptr_z0 + dims[1]; + ptr_y0 = (int)yp * dims[0]; + ptr_y1 = ptr_y0 + dims[0]; + ptr_x0 = (int)xp; + ptr_x1 = ptr_x0 + 1; + dx = xp - (int)xp; + dy = yp - (int)yp; + dz = zp - (int)zp; + + // imageG is not rotated. sample the given x,y,z + ivg = imageG[sliceG+rowG+(int)x]; + // imageF IS rotated. sample the rotated xp,yp,zp + V000 = imageF[ptr_x0+ptr_y0+ptr_z0]; + V100 = imageF[ptr_x1+ptr_y0+ptr_z0]; + V010 = imageF[ptr_x0+ptr_y1+ptr_z0]; + V001 = imageF[ptr_x0+ptr_y0+ptr_z1]; + V011 = imageF[ptr_x0+ptr_y1+ptr_z1]; + V101 = imageF[ptr_x1+ptr_y0+ptr_z1]; + V110 = imageF[ptr_x1+ptr_y1+ptr_z0]; + V111 = imageF[ptr_x1+ptr_y1+ptr_z1]; + + vf = V000 * (1.0-dx) * (1.0 - dy) * (1.0 - dz) + + V100 * (dx) * (1.0 - dy) * (1.0 - dz) + + V010 * (1.0-dx) * (dy) * (1.0 - dz) + + V001 * (1.0-dx) * (1.0 - dy) * (dz) + + V101 * (dx) * (1.0 - dy) * (dz) + + V011 * (1.0-dx) * (dy) * (dz) + + V110 * (dx) * (dy) * (1.0 - dz) + + V111 * (dx) * (dy) * (dz); + + ivf = (int)(vf); + H[ivf+256*ivg] += 1.0; + } + } + } + } + + status = 1; + + return status; + +} + + Added: trunk/scipy/ndimage/register/__init__.py =================================================================== --- trunk/scipy/ndimage/register/__init__.py 2008-01-31 17:31:42 UTC (rev 3878) +++ trunk/scipy/ndimage/register/__init__.py 2008-02-01 00:24:16 UTC (rev 3879) @@ -0,0 +1,5 @@ +# Register package +# Author: Tom Waite, 2008 + +from _register import * + Added: trunk/scipy/ndimage/register/setup.py =================================================================== --- trunk/scipy/ndimage/register/setup.py 2008-01-31 17:31:42 UTC (rev 3878) +++ trunk/scipy/ndimage/register/setup.py 2008-02-01 00:24:16 UTC (rev 3879) @@ -0,0 +1,20 @@ + +#!/usr/bin/env python + +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + + config = Configuration('register', parent_package, top_path) + + config.add_extension('_register', + sources=['Register_EXT.c', + 'Register_IMPL.c'] + ) + + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) + + Added: trunk/scipy/ndimage/register/setup.pyc =================================================================== (Binary files differ) Property changes on: trunk/scipy/ndimage/register/setup.pyc ___________________________________________________________________ Name: svn:mime-type + application/octet-stream From scipy-svn at scipy.org Thu Jan 31 19:25:35 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 31 Jan 2008 18:25:35 -0600 (CST) Subject: [Scipy-svn] r3880 - trunk/scipy/ndimage Message-ID: <20080201002535.58AB239C26D@new.scipy.org> Author: tom.waite Date: 2008-01-31 18:25:13 -0600 (Thu, 31 Jan 2008) New Revision: 3880 Added: trunk/scipy/ndimage/registration.py Log: Initial registration code for NIPY Added: trunk/scipy/ndimage/registration.py =================================================================== --- trunk/scipy/ndimage/registration.py 2008-02-01 00:24:16 UTC (rev 3879) +++ trunk/scipy/ndimage/registration.py 2008-02-01 00:25:13 UTC (rev 3880) @@ -0,0 +1,428 @@ +import math +import os +import numpy as N +import scipy.ndimage.register as R +import scipy.special as SP +import scipy.ndimage as NDI +import scipy.optimize as OPT +import time + +# anatomical MRI to test with +# test registration on same image (optimal vector is (0,0,0,0,0,0) +inputname = 'ANAT1_V0001.img' +filename = os.path.join(os.path.split(__file__)[0], inputname) + +def python_coreg(ftype=2, smimage=0, lite=1, smhist=0, method='mi', opt_method='powell'): + # get_images is testing with 2 copies of anatomical MRI + image1, image2, imdata = get_images(ftype, smimage) + start = time.time() + parm_vector = multires_registration(image1, image2, imdata, lite, smhist, method, opt_method) + stop = time.time() + print 'Total Optimizer Time is ', (stop-start) + + return parm_vector + +def get_images(ftype, smimage): + image1 = load_image() + image2 = load_image() + imdata = build_structs() + image1['fwhm'] = build_fwhm(image1['mat'], imdata['step']) + image2['fwhm'] = build_fwhm(image2['mat'], imdata['step']) + if smimage: + image_F_xyz1 = filter_image_3D(image1['data'], image1['fwhm'], ftype) + image1['data'] = image_F_xyz1 + image_F_xyz2 = filter_image_3D(image2['data'], image2['fwhm'], ftype) + image2['data'] = image_F_xyz2 + + return image1, image2, imdata + +def multires_registration(image1, image2, imdata, lite, smhist, method, opt_method): + ret_histo=0 + # make the step a scalar to can put in a multi-res loop + loop = range(imdata['sample'].size) + x = imdata['parms'] + for i in loop: + step = imdata['sample'][i] + imdata['step'][:] = step + optfunc_args = (image1, image2, imdata['step'], imdata['fwhm'], lite, smhist, method, ret_histo) + p_args = (optfunc_args,) + if opt_method=='powell': + print 'POWELL multi-res registration step size ', step + print 'vector ', x + x = OPT.fmin_powell(optimize_function, x, args=p_args, callback=callback_powell) + elif opt_method=='cg': + print 'CG multi-res registration step size ', step + print 'vector ', x + x = OPT.fmin_cg(optimize_function, x, args=p_args, callback=callback_cg) + + return x + + +def test_image_filter(image, imdata, ftype=2): + image['fwhm'] = build_fwhm(image['mat'], imdata['step']) + filt_image = filter_image_3D(image['data'], image['fwhm'], ftype) + return filt_image + +def test_optimizers(step=2, smooth=0, shist=0): + opt_stats = {} + print 'powell with stochastic resampling' + x_0, p_time_0 = optimizer_powell(lite=0, smimage=smooth, smhist=shist, stepsize=step) + opt_stats[0] = {'parms' : x_0, 'time' : p_time_0, + 'label' : 'powell with stochastic resampling'} + print 'powell without stochastic resampling' + x_1, p_time_1 = optimizer_powell(lite=1, smimage=smooth, smhist=shist, stepsize=step) + opt_stats[1] = {'parms' : x_1, 'time' : p_time_1, + 'label' : 'powell without stochastic resampling'} + print 'conjugate gradient with stochastic resampling' + xcg_0, cg_time_0 = optimizer_cg(lite=0, smimage=smooth, smhist=shist, stepsize=step) + opt_stats[2] = {'parms' : xcg_0, 'time' : cg_time_0, + 'label' : 'conjugate gradient with stochastic resampling'} + print 'conjugate gradient without stochastic resampling' + xcg_1, cg_time_1 = optimizer_cg(lite=1, smimage=smooth, smhist=shist, stepsize=step) + opt_stats[3] = {'parms' : xcg_1, 'time' : cg_time_1, + 'label' : 'conjugate gradient without stochastic resampling'} + return opt_stats + +def callback_powell(x): + print 'Parameter Vector from Powell: - ' + print x + return + +def callback_cg(x): + print 'Parameter Vector from Conjugate Gradient: - ' + print x + return + +def optimizer_powell(lite=0, smhist=0, smimage=1, method='mi', ftype=2, stepsize=2): + # test the Powell registration on the anatomical MRI volume + image1 = load_image() + image2 = load_image() + imdata = build_structs(step=stepsize) + image1['fwhm'] = build_fwhm(image1['mat'], imdata['step']) + image2['fwhm'] = build_fwhm(image2['mat'], imdata['step']) + M = build_rotate_matrix(imdata['parms']) + if smimage: + image_F_xyz1 = filter_image_3D(image1['data'], image1['fwhm'], ftype) + image1['data'] = image_F_xyz1 + image_F_xyz2 = filter_image_3D(image2['data'], image2['fwhm'], ftype) + image2['data'] = image_F_xyz2 + + ret_histo=0 + optfunc_args = (image1, image2, imdata['step'], imdata['fwhm'], lite, smhist, method, ret_histo) + p_args = (optfunc_args,) + start = time.time() + x = OPT.fmin_powell(optimize_function, imdata['parms'], args=p_args, callback=callback_powell) + stop = time.time() + return x, (stop-start) + + +def optimizer_cg(lite=0, smhist=0, smimage=1, method='mi', ftype=2, stepsize=2): + # test the CG registration on the anatomical MRI volume + image1 = load_image() + image2 = load_image() + imdata = build_structs(step=stepsize) + image1['fwhm'] = build_fwhm(image1['mat'], imdata['step']) + image2['fwhm'] = build_fwhm(image2['mat'], imdata['step']) + M = build_rotate_matrix(imdata['parms']) + if smimage: + image_F_xyz1 = filter_image_3D(image1['data'], image1['fwhm'], ftype) + image1['data'] = image_F_xyz1 + image_F_xyz2 = filter_image_3D(image2['data'], image2['fwhm'], ftype) + image2['data'] = image_F_xyz2 + + ret_histo=0 + optfunc_args = (image1, image2, imdata['step'], imdata['fwhm'], lite, smhist, method, ret_histo) + p_args = (optfunc_args,) + start = time.time() + x = OPT.fmin_cg(optimize_function, imdata['parms'], args=p_args, callback=callback_cg) + stop = time.time() + return x, (stop-start) + + +def reg_single_pass(lite=0, smhist=0, smimage=0, method='mi', ftype=2, alpha=0.0, + beta=0.0, gamma=0.0, Tx=0.0, Ty=0.0, Tz=0.0, ret_histo=0, stepsize=2): + image1 = load_image() + image2 = load_image() + imdata = build_structs(step=stepsize) + imdata['parms'][0] = alpha + imdata['parms'][1] = beta + imdata['parms'][2] = gamma + imdata['parms'][3] = Tx + imdata['parms'][4] = Ty + imdata['parms'][5] = Tz + image1['fwhm'] = build_fwhm(image1['mat'], imdata['step']) + image2['fwhm'] = build_fwhm(image2['mat'], imdata['step']) + print 'image1[fwhm] ', image1['fwhm'] + print 'image2[fwhm] ', image2['fwhm'] + M = build_rotate_matrix(imdata['parms']) + if smimage: + image_F_xyz1 = filter_image_3D(image1['data'], image1['fwhm'], ftype) + image1['data'] = image_F_xyz1 + image_F_xyz2 = filter_image_3D(image2['data'], image2['fwhm'], ftype) + image2['data'] = image_F_xyz2 + + optfunc_args = (image1, image2, imdata['step'], imdata['fwhm'], lite, smhist, method, ret_histo) + + if ret_histo: + cost, joint_histogram = optimize_function(imdata['parms'], optfunc_args) + return cost, joint_histogram + else: + cost = optimize_function(imdata['parms'], optfunc_args) + return cost + + +def smooth_kernel(fwhm, x, ktype=1): + eps = 0.00001 + s = N.square((fwhm/math.sqrt(8.0*math.log(2.0)))) + eps + if ktype==1: + # from SPM: Gauss kernel convolved with 1st degree B spline + w1 = 0.5 * math.sqrt(2.0/s) + w2 = -0.5 / s + w3 = math.sqrt((s*math.pi) /2.0) + kernel = 0.5*(SP.erf(w1*(x+1))*(x+1) + SP.erf(w1*(x-1))*(x-1) - 2.0*SP.erf(w1*(x))*(x) + + w3*(N.exp(w2*N.square(x+1))) + N.exp(w2*(N.square(x-1))) - 2.0*N.exp(w2*N.square(x))) + kernel[kernel<0] = 0 + kernel = kernel / kernel.sum() + else: + # Gauss kernel + kernel = (1.0/math.sqrt(2.0*math.pi*s)) * N.exp(-N.square(x)/(2.0*s)) + kernel = kernel / kernel.sum() + + return kernel + +def filter_image_3D(imageRaw, fwhm, ftype=2): + p = N.ceil(2*fwhm[0]).astype(int) + x = N.array(range(-p, p+1)) + kernel_x = smooth_kernel(fwhm[0], x, ktype=ftype) + p = N.ceil(2*fwhm[1]).astype(int) + x = N.array(range(-p, p+1)) + kernel_y = smooth_kernel(fwhm[1], x, ktype=ftype) + p = N.ceil(2*fwhm[2]).astype(int) + x = N.array(range(-p, p+1)) + kernel_z = smooth_kernel(fwhm[2], x, ktype=ftype) + output=None + # 3D filter in 3 1D separable stages + axis = 0 + image_F_x = NDI.correlate1d(imageRaw, kernel_x, axis, output) + axis = 1 + image_F_xy = NDI.correlate1d(image_F_x, kernel_y, axis, output) + axis = 2 + image_F_xyz = NDI.correlate1d(image_F_xy, kernel_z, axis, output) + return image_F_xyz + +def build_fwhm(M, S): + view_3x3 = N.square(M[0:3, 0:3]) + vxg = N.sqrt(view_3x3.sum(axis=0)) + # assumes that sampling is the same for xyz + size = N.array([1,1,1])*S[0] + x = N.square(size) - N.square(vxg) + # clip + x[x<0] = 0 + fwhm = N.sqrt(x) / vxg + # pathology when stepsize = 1 for MAT equal to the identity matrix + fwhm[fwhm==0] = 1 + # return the 3D Gaussian kernel width (xyz) + return fwhm + +def load_image(imagename=filename, rows=256, cols=256, layers=90): + ImageVolume = N.fromfile(imagename, dtype=N.uint16).reshape(layers, rows, cols); + # clip to 8 bits. this will be rescale to 8 bits for fMRI + ImageVolume[ImageVolume>255] = 255 + # voxel to pixel is identity for this simulation using anatomical MRI volume + # 4x4 matrix + M = N.eye(4, dtype=N.float64); + # dimensions + D = N.zeros(3, dtype=N.int32); + # Gaussian kernel - fill in with build_fwhm() + F = N.zeros(3, dtype=N.float64); + D[0] = rows + D[1] = cols + D[2] = layers + # make sure the data type is uchar + ImageVolume = ImageVolume.astype(N.uint8) + image = {'data' : ImageVolume, 'mat' : M, 'dim' : D, 'fwhm' : F} + return image + + +def optimize_function(x, optfunc_args): + image_F = optfunc_args[0] + image_G = optfunc_args[1] + sample_vector = optfunc_args[2] + fwhm = optfunc_args[3] + do_lite = optfunc_args[4] + smooth = optfunc_args[5] + method = optfunc_args[6] + ret_histo = optfunc_args[7] + + rot_matrix = build_rotate_matrix(x) + cost = 0.0 + epsilon = 2.2e-16 + # image_F is base image + # image_G is the rotated image + # rot_matrix is the 4x4 constructed (current angles and translates) transform matrix + # sample_vector is the subsample vector for x-y-z + + F_inv = N.linalg.inv(image_F['mat']) + composite = N.dot(F_inv, rot_matrix) + composite = N.dot(composite, image_G['mat']) + + # allocate memory from Python as memory leaks when created in C-ext + joint_histogram = N.zeros([256, 256], dtype=N.float64); + + if do_lite: + R.register_histogram_lite(image_F['data'], image_G['data'], composite, sample_vector, joint_histogram) + else: + R.register_histogram(image_F['data'], image_G['data'], composite, sample_vector, joint_histogram) + + if smooth: + p = N.ceil(2*fwhm[0]).astype(int) + x = N.array(range(-p, p+1)) + kernel1 = smooth_kernel(fwhm[0], x) + p = N.ceil(2*fwhm[1]).astype(int) + x = N.array(range(-p, p+1)) + kernel2 = smooth_kernel(fwhm[1], x) + output=None + # 2D filter in 1D separable stages + axis = 0 + result = NDI.correlate1d(joint_histogram, kernel1, axis, output) + axis = 1 + joint_histogram = NDI.correlate1d(result, kernel1, axis, output) + + joint_histogram += epsilon # prevent log(0) + # normalize the joint histogram + joint_histogram /= joint_histogram.sum() + # get the marginals + marginal_col = joint_histogram.sum(axis=0) + marginal_row = joint_histogram.sum(axis=1) + + if method == 'mi': + # mutual information + marginal_outer = N.outer(marginal_col, marginal_row) + H = joint_histogram * N.log(joint_histogram / marginal_outer) + mutual_information = H.sum() + cost = -mutual_information + + elif method == 'ecc': + # entropy correlation coefficient + marginal_outer = N.outer(marginal_col, marginal_row) + H = joint_histogram * N.log(joint_histogram / marginal_outer) + mutual_information = H.sum() + row_entropy = marginal_row * N.log(marginal_row) + col_entropy = marginal_col * N.log(marginal_col) + ecc = -2.0*mutual_information/(row_entropy.sum() + col_entropy.sum()) + cost = -ecc + + elif method == 'nmi': + # normalized mutual information + row_entropy = marginal_row * N.log(marginal_row) + col_entropy = marginal_col * N.log(marginal_col) + H = joint_histogram * N.log(joint_histogram) + nmi = (row_entropy.sum() + col_entropy.sum()) / (H.sum()) + cost = -nmi + + elif method == 'ncc': + # cross correlation from the joint histogram + r, c = joint_histogram.shape + i = N.array(range(1,c+1)) + j = N.array(range(1,r+1)) + m1 = (marginal_row * i).sum() + m2 = (marginal_col * j).sum() + sig1 = N.sqrt((marginal_row*(N.square(i-m1))).sum()) + sig2 = N.sqrt((marginal_col*(N.square(j-m2))).sum()) + [a, b] = N.mgrid[1:c+1, 1:r+1] + a = a - m1 + b = b - m2 + # element multiplies in the joint histogram and grids + H = ((joint_histogram * a) * b).sum() + ncc = H / (N.dot(sig1, sig2)) + cost = -ncc + + if ret_histo: + return cost, joint_histogram + else: + return cost + + +def build_structs(step=2): + # build image data structures here + P = N.zeros(6, dtype=N.float64); + T = N.zeros(6, dtype=N.float64); + F = N.zeros(2, dtype=N.int32); + S = N.ones(3, dtype=N.int32); + sample = N.zeros(2, dtype=N.int32); + S[0] = step + S[1] = step + S[2] = step + # histogram smoothing + F[0] = 3 + F[1] = 3 + # subsample for multiresolution registration + sample[0] = 4 + sample[1] = 2 + # tolerances for angle (0-2) and translation (3-5) + T[0] = 0.02 + T[1] = 0.02 + T[2] = 0.02 + T[3] = 0.001 + T[4] = 0.001 + T[5] = 0.001 + # P[0] = alpha <=> pitch + # P[1] = beta <=> roll + # P[2] = gamma <=> yaw + # P[3] = Tx + # P[4] = Ty + # P[5] = Tz + img_data = {'parms' : P, 'step' : S, 'fwhm' : F, 'tol' : T, 'sample' : sample} + return img_data + + +def build_rotate_matrix(img_data_parms): + R1 = N.zeros([4,4], dtype=N.float64); + R2 = N.zeros([4,4], dtype=N.float64); + R3 = N.zeros([4,4], dtype=N.float64); + T = N.eye(4, dtype=N.float64); + + alpha = math.radians(img_data_parms[0]) + beta = math.radians(img_data_parms[1]) + gamma = math.radians(img_data_parms[2]) + + R1[0][0] = 1.0 + R1[1][1] = math.cos(alpha) + R1[1][2] = math.sin(alpha) + R1[2][1] = -math.sin(alpha) + R1[2][2] = math.cos(alpha) + R1[3][3] = 1.0 + + R2[0][0] = math.cos(beta) + R2[0][2] = math.sin(beta) + R2[1][1] = 1.0 + R2[2][0] = -math.sin(beta) + R2[2][2] = math.cos(beta) + R2[3][3] = 1.0 + + R3[0][0] = math.cos(gamma) + R3[0][1] = math.sin(gamma) + R3[1][0] = -math.sin(gamma) + R3[1][1] = math.cos(gamma) + R3[2][2] = 1.0 + R3[3][3] = 1.0 + + T[0][0] = 1.0 + T[1][1] = 1.0 + T[2][2] = 1.0 + T[3][3] = 1.0 + T[0][3] = img_data_parms[3] + T[1][3] = img_data_parms[4] + T[2][3] = img_data_parms[5] + + rot_matrix = N.dot(T, R1); + rot_matrix = N.dot(rot_matrix, R2); + rot_matrix = N.dot(rot_matrix, R3); + + return rot_matrix + + + + + + From scipy-svn at scipy.org Thu Jan 31 19:26:34 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 31 Jan 2008 18:26:34 -0600 (CST) Subject: [Scipy-svn] r3881 - trunk/scipy/ndimage Message-ID: <20080201002634.8E93239C13A@new.scipy.org> Author: tom.waite Date: 2008-01-31 18:26:17 -0600 (Thu, 31 Jan 2008) New Revision: 3881 Modified: trunk/scipy/ndimage/setup.py Log: Updated for the registration C extension codes Modified: trunk/scipy/ndimage/setup.py =================================================================== --- trunk/scipy/ndimage/setup.py 2008-02-01 00:25:13 UTC (rev 3880) +++ trunk/scipy/ndimage/setup.py 2008-02-01 00:26:17 UTC (rev 3881) @@ -16,6 +16,7 @@ config.add_subpackage('segment') config.add_data_dir('tests') + config.add_subpackage('register') return config From scipy-svn at scipy.org Thu Jan 31 21:03:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 31 Jan 2008 20:03:40 -0600 (CST) Subject: [Scipy-svn] r3882 - in trunk/scipy: ndimage/register sparse sparse/benchmarks sparse/sparsetools sparse/tests Message-ID: <20080201020340.4FD8139C0A2@new.scipy.org> Author: wnbell Date: 2008-01-31 20:03:12 -0600 (Thu, 31 Jan 2008) New Revision: 3882 Modified: trunk/scipy/ndimage/register/setup.pyc trunk/scipy/sparse/benchmarks/bench_sparse.py trunk/scipy/sparse/compressed.py trunk/scipy/sparse/coo.py trunk/scipy/sparse/sparsetools/sparsetools.h trunk/scipy/sparse/sparsetools/sparsetools.i trunk/scipy/sparse/sparsetools/sparsetools.py trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx trunk/scipy/sparse/tests/test_base.py Log: added coo_todense to sparsetools removed csr/csc matvec output parameter (for now) Modified: trunk/scipy/ndimage/register/setup.pyc =================================================================== (Binary files differ) Modified: trunk/scipy/sparse/benchmarks/bench_sparse.py =================================================================== --- trunk/scipy/sparse/benchmarks/bench_sparse.py 2008-02-01 00:26:17 UTC (rev 3881) +++ trunk/scipy/sparse/benchmarks/bench_sparse.py 2008-02-01 02:03:12 UTC (rev 3882) @@ -157,11 +157,12 @@ start = time.clock() iter = 0 while iter < 5 or time.clock() < start + 1: - try: - #avoid creating y if possible - A.matvec(x,y) - except: - y = A*x + y = A*x + #try: + # #avoid creating y if possible + # A.matvec(x,y) + #except: + # y = A*x iter += 1 end = time.clock() Modified: trunk/scipy/sparse/compressed.py =================================================================== --- trunk/scipy/sparse/compressed.py 2008-02-01 00:26:17 UTC (rev 3881) +++ trunk/scipy/sparse/compressed.py 2008-02-01 02:03:12 UTC (rev 3882) @@ -316,11 +316,11 @@ 'other' may be a rank 1 array of length N or a rank 2 array or matrix with shape (N,1). - If the optional 'output' parameter is defined, it will - be used to store the result. Otherwise, a new vector - will be allocated. - """ + #If the optional 'output' parameter is defined, it will + #be used to store the result. Otherwise, a new vector + #will be allocated. + if isdense(other): M,N = self.shape @@ -331,19 +331,21 @@ fn = getattr(sparsetools,self.format + '_matvec') #output array - if output is None: - y = empty( self.shape[0], dtype=upcast(self.dtype,other.dtype) ) - else: - if output.shape != (M,) and output.shape != (M,1): - raise ValueError, "output array has improper dimensions" - if not output.flags.c_contiguous: - raise ValueError, "output array must be contiguous" - if output.dtype != upcast(self.dtype,other.dtype): - raise ValueError, "output array has dtype=%s "\ - "dtype=%s is required" % \ - (output.dtype,upcast(self.dtype,other.dtype)) - y = output + y = zeros( self.shape[0], dtype=upcast(self.dtype,other.dtype) ) + #if output is None: + # y = empty( self.shape[0], dtype=upcast(self.dtype,other.dtype) ) + #else: + # if output.shape != (M,) and output.shape != (M,1): + # raise ValueError, "output array has improper dimensions" + # if not output.flags.c_contiguous: + # raise ValueError, "output array must be contiguous" + # if output.dtype != upcast(self.dtype,other.dtype): + # raise ValueError, "output array has dtype=%s "\ + # "dtype=%s is required" % \ + # (output.dtype,upcast(self.dtype,other.dtype)) + # y = output + fn(self.shape[0], self.shape[1], \ self.indptr, self.indices, self.data, numpy.ravel(other), y) Modified: trunk/scipy/sparse/coo.py =================================================================== --- trunk/scipy/sparse/coo.py 2008-02-01 00:26:17 UTC (rev 3881) +++ trunk/scipy/sparse/coo.py 2008-02-01 02:03:12 UTC (rev 3882) @@ -9,7 +9,7 @@ unique, searchsorted, atleast_2d, lexsort, cumsum, concatenate, \ empty_like, arange -from sparsetools import coo_tocsr, coo_tocsc +from sparsetools import coo_tocsr, coo_tocsc, coo_todense from base import isspmatrix from data import _data_matrix from sputils import upcast, to_native, isshape, getdtype @@ -223,10 +223,10 @@ return coo_matrix((self.data,(self.col,self.row)),(N,M),copy=copy) def toarray(self): - A = self.tocsr().tocoo(copy=False) #eliminate (i,j) duplicates - M = zeros(self.shape, dtype=self.dtype) - M[A.row, A.col] = A.data - return M + B = zeros(self.shape, dtype=self.dtype) + M,N = self.shape + coo_todense(M, N, self.nnz, self.row, self.col, self.data, B.ravel() ) + return B def tocsc(self,sum_duplicates=True): """Return a copy of this matrix in Compressed Sparse Column format Modified: trunk/scipy/sparse/sparsetools/sparsetools.h =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.h 2008-02-01 00:26:17 UTC (rev 3881) +++ trunk/scipy/sparse/sparsetools/sparsetools.h 2008-02-01 02:03:12 UTC (rev 3882) @@ -1277,7 +1277,7 @@ /* - * Compute Y = A*X for CSR matrix A and dense vectors X,Y + * Compute Y += A*X for CSR matrix A and dense vectors X,Y * * * Input Arguments: @@ -1307,7 +1307,7 @@ T Yx[]) { for(I i = 0; i < n_row; i++){ - T sum = 0; + T sum = Yx[i]; for(I jj = Ap[i]; jj < Ap[i+1]; jj++){ sum += Ax[jj] * Xx[Aj[jj]]; } @@ -1318,7 +1318,7 @@ /* - * Compute Y = A*X for CSC matrix A and dense vectors X,Y + * Compute Y += A*X for CSC matrix A and dense vectors X,Y * * * Input Arguments: @@ -1347,16 +1347,12 @@ const T Xx[], T Yx[]) { - for(I i = 0; i < n_row; i++){ - Yx[i] = 0; - } - for(I j = 0; j < n_col; j++){ I col_start = Ap[j]; I col_end = Ap[j+1]; for(I ii = col_start; ii < col_end; ii++){ - I row = Ai[ii]; + I row = Ai[ii]; Yx[row] += Ax[ii] * Xx[j]; } } @@ -1484,10 +1480,37 @@ +/* + * Compute B += A for COO matrix A, dense matrix B + * + * Input Arguments: + * I n_row - number of rows in A + * I n_col - number of columns in A + * I nnz - number of nonzeros in A + * I Ai[nnz(A)] - row indices + * I Aj[nnz(A)] - column indices + * T Ax[nnz(A)] - nonzeros + * T Bx[n_row*n_col] - dense matrix + * + */ +template +void coo_todense(const I n_row, + const I n_col, + const I nnz, + const I Ai[], + const I Aj[], + const T Ax[], + T Bx[]) +{ + for(I n = 0; n < nnz; n++){ + Bx[ n_col * Ai[n] + Aj[n] ] += Ax[n]; + } +} + template void get_csr_submatrix(const I n_row, const I n_col, @@ -1764,45 +1787,7 @@ // // // -///* -// * Compute A = M for CSR matrix A, dense matrix M -// * -// * Input Arguments: -// * I n_row - number of rows in A -// * I n_col - number of columns in A -// * T Mx[n_row*n_col] - dense matrix -// * I Ap[n_row+1] - row pointer -// * I Aj[nnz(A)] - column indices -// * T Ax[nnz(A)] - nonzeros -// * -// * Note: -// * Output arrays Ap, Aj, and Ax will be allocated within the method -// * -// */ -//template -//void dense_tocsr(const I n_row, -// const I n_col, -// const T Mx[], -// std::vector* Ap, -// std::vector* Aj, -// std::vector* Ax) -//{ -// const T* x_ptr = Mx; // -// Ap->push_back(0); -// for(I i = 0; i < n_row; i++){ -// for(I j = 0; j < n_col; j++){ -// if(*x_ptr != 0){ -// Aj->push_back(j); -// Ax->push_back(*x_ptr); -// } -// x_ptr++; -// } -// Ap->push_back(Aj->size()); -// } -//} -// -// ///* // * Compute M = A for CSR matrix A, dense matrix M // * Modified: trunk/scipy/sparse/sparsetools/sparsetools.i =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.i 2008-02-01 00:26:17 UTC (rev 3881) +++ trunk/scipy/sparse/sparsetools/sparsetools.i 2008-02-01 02:03:12 UTC (rev 3882) @@ -262,7 +262,7 @@ INSTANTIATE_ALL(bsr_minus_bsr) /* - * Sort indices. + * Sort indices */ %template(csr_has_sorted_indices) csr_has_sorted_indices; INSTANTIATE_ALL(csr_sort_indices) @@ -274,7 +274,7 @@ INSTANTIATE_ALL(csr_eliminate_zeros) /* - * Sum duplicate entries. + * Sum duplicate entries */ INSTANTIATE_ALL(csr_sum_duplicates) @@ -282,3 +282,9 @@ * Extract submatrices */ INSTANTIATE_ALL(get_csr_submatrix) + +/* + * To dense matrix + */ +INSTANTIATE_ALL(coo_todense) + Modified: trunk/scipy/sparse/sparsetools/sparsetools.py =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.py 2008-02-01 00:26:17 UTC (rev 3881) +++ trunk/scipy/sparse/sparsetools/sparsetools.py 2008-02-01 02:03:12 UTC (rev 3882) @@ -1301,3 +1301,36 @@ """ return _sparsetools.get_csr_submatrix(*args) +def coo_todense(*args): + """ + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, signed char Ax, + signed char Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned char Ax, + unsigned char Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, short Ax, + short Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned short Ax, + unsigned short Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, int Ax, + int Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned int Ax, + unsigned int Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, long long Ax, + long long Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned long long Ax, + unsigned long long Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, float Ax, + float Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, double Ax, + double Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, long double Ax, + long double Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, npy_cfloat_wrapper Ax, + npy_cfloat_wrapper Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, npy_cdouble_wrapper Ax, + npy_cdouble_wrapper Bx) + coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, npy_clongdouble_wrapper Ax, + npy_clongdouble_wrapper Bx) + """ + return _sparsetools.coo_todense(*args) + Modified: trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-02-01 00:26:17 UTC (rev 3881) +++ trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-02-01 02:03:12 UTC (rev 3882) @@ -93237,6 +93237,2109 @@ } +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + signed char *arg6 ; + signed char *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_BYTE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (signed char*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_BYTE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (signed char*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(signed char const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + unsigned char *arg6 ; + unsigned char *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_UBYTE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned char*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_UBYTE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned char*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(unsigned char const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + short *arg6 ; + short *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_SHORT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (short*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_SHORT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (short*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(short const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + unsigned short *arg6 ; + unsigned short *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_USHORT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned short*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_USHORT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned short*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(unsigned short const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + int *arg6 ; + int *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_INT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (int*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(int const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + unsigned int *arg6 ; + unsigned int *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_UINT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned int*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_UINT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned int*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(unsigned int const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + long long *arg6 ; + long long *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_LONGLONG, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (long long*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_LONGLONG); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (long long*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(long long const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + unsigned long long *arg6 ; + unsigned long long *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_ULONGLONG, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (unsigned long long*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_ULONGLONG); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (unsigned long long*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(unsigned long long const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + float *arg6 ; + float *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_FLOAT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (float*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_FLOAT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (float*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(float const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + double *arg6 ; + double *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_DOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (double*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_DOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (double*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(double const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + long double *arg6 ; + long double *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_LONGDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (long double*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_LONGDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (long double*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(long double const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + npy_cfloat_wrapper *arg6 ; + npy_cfloat_wrapper *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CFLOAT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_cfloat_wrapper*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CFLOAT); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_cfloat_wrapper*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(npy_cfloat_wrapper const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + npy_cdouble_wrapper *arg6 ; + npy_cdouble_wrapper *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_cdouble_wrapper*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_cdouble_wrapper*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(npy_cdouble_wrapper const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int *arg4 ; + int *arg5 ; + npy_clongdouble_wrapper *arg6 ; + npy_clongdouble_wrapper *arg7 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyArrayObject *array4 = NULL ; + int is_new_object4 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *temp7 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:coo_todense",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "coo_todense" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "coo_todense" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "coo_todense" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + npy_intp size[1] = { + -1 + }; + array4 = obj_to_array_contiguous_allow_conversion(obj3, PyArray_INT, &is_new_object4); + if (!array4 || !require_dimensions(array4,1) || !require_size(array4,size,1) + || !require_contiguous(array4) || !require_native(array4)) SWIG_fail; + + arg4 = (int*) array4->data; + } + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_CLONGDOUBLE, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (npy_clongdouble_wrapper*) array6->data; + } + { + temp7 = obj_to_array_no_conversion(obj6,PyArray_CLONGDOUBLE); + if (!temp7 || !require_contiguous(temp7) || !require_native(temp7)) SWIG_fail; + arg7 = (npy_clongdouble_wrapper*) array_data(temp7); + } + coo_todense(arg1,arg2,arg3,(int const (*))arg4,(int const (*))arg5,(npy_clongdouble_wrapper const (*))arg6,arg7); + resultobj = SWIG_Py_Void(); + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return resultobj; +fail: + { + if (is_new_object4 && array4) Py_DECREF(array4); + } + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_coo_todense(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[8]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 7); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_1(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_2(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_3(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_4(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_5(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_6(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_7(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_8(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_9(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_10(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_11(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_12(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_13(self, args); + } + } + } + } + } + } + } + } + if (argc == 7) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[3]) && PyArray_CanCastSafely(PyArray_TYPE(argv[3]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_coo_todense__SWIG_14(self, args); + } + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'coo_todense'.\n Possible C/C++ prototypes are:\n"" coo_todense<(int,signed char)>(int const,int const,int const,int const [],int const [],signed char const [],signed char [])\n"" coo_todense<(int,unsigned char)>(int const,int const,int const,int const [],int const [],unsigned char const [],unsigned char [])\n"" coo_todense<(int,short)>(int const,int const,int const,int const [],int const [],short const [],short [])\n"" coo_todense<(int,unsigned short)>(int const,int const,int const,int const [],int const [],unsigned short const [],unsigned short [])\n"" coo_todense<(int,int)>(int const,int const,int const,int const [],int const [],int const [],int [])\n"" coo_todense<(int,unsigned int)>(int const,int const,int const,int const [],int const [],unsigned int const [],unsigned int [])\n"" coo_todense<(int,long long)>(int const,int const,int const,int const [],int const [],long long const [],long long [])\n"" coo_todense<(int,unsigned long long)>(int const,int const,int const,int const [],int const [],unsigned long long const [],unsigned long long [])\n"" coo_todense<(int,float)>(int const,int const,int const,int const [],int const [],float const [],float [])\n"" coo_todense<(int,double)>(int const,int const,int const,int const [],int const [],double const [],double [])\n"" coo_todense<(int,long double)>(int const,int const,int const,int const [],int const [],long double const [],long double [])\n"" coo_todense<(int,npy_cfloat_wrapper)>(int const,int const,int const,int const [],int const [],npy_cfloat_wrapper const [],npy_cfloat_wrapper [])\n"" coo_todense<(int,npy_cdouble_wrapper)>(int const,int const,int const,int const [],int const [],npy_cdouble_wrapper const [],npy_cdouble_wrapper [])\n"" coo_todense<(int,npy_clongdouble_wrapper)>(int const,int const,int const,int const [],int const [],npy_clongdouble_wrapper const [],npy_clongdouble_wrapper [])\n"); + return NULL; +} + + static PyMethodDef SwigMethods[] = { { (char *)"csr_diagonal", _wrap_csr_diagonal, METH_VARARGS, (char *)"\n" "csr_diagonal(int n_row, int n_col, int Ap, int Aj, signed char Ax, \n" @@ -94375,6 +96478,36 @@ " std::vector<(int)> Bp, std::vector<(int)> Bj, \n" " std::vector<(npy_clongdouble_wrapper)> Bx)\n" ""}, + { (char *)"coo_todense", _wrap_coo_todense, METH_VARARGS, (char *)"\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, signed char Ax, \n" + " signed char Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned char Ax, \n" + " unsigned char Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, short Ax, \n" + " short Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned short Ax, \n" + " unsigned short Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, int Ax, \n" + " int Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned int Ax, \n" + " unsigned int Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, long long Ax, \n" + " long long Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned long long Ax, \n" + " unsigned long long Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, float Ax, \n" + " float Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, double Ax, \n" + " double Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, long double Ax, \n" + " long double Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, npy_cfloat_wrapper Ax, \n" + " npy_cfloat_wrapper Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, npy_cdouble_wrapper Ax, \n" + " npy_cdouble_wrapper Bx)\n" + "coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, npy_clongdouble_wrapper Ax, \n" + " npy_clongdouble_wrapper Bx)\n" + ""}, { NULL, NULL, 0, NULL } }; Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-02-01 00:26:17 UTC (rev 3881) +++ trunk/scipy/sparse/tests/test_base.py 2008-02-01 02:03:12 UTC (rev 3882) @@ -474,42 +474,44 @@ class _TestMatvecOutput: """test using the matvec() output parameter""" def test_matvec_output(self): - #flat array - x = array([1.25, -6.5, 0.125, -3.75],dtype='d') - y = zeros(3,dtype='d') - - self.datsp.matvec(x,y) - assert_array_equal(self.datsp*x,y) - - #column vector - x = array([1.25, -6.5, 0.125, -3.75],dtype='d') - x = x.reshape(4,1) - y = zeros((3,1),dtype='d') + pass #Currently disabled - self.datsp.matvec(x,y) - assert_array_equal(self.datsp*x,y) - - # improper output type - x = array([1.25, -6.5, 0.125, -3.75],dtype='d') - y = zeros(3,dtype='i') - - self.assertRaises( ValueError, self.datsp.matvec, x, y ) - - # improper output shape - x = array([1.25, -6.5, 0.125, -3.75],dtype='d') - y = zeros(2,dtype='d') - - self.assertRaises( ValueError, self.datsp.matvec, x, y ) +# #flat array +# x = array([1.25, -6.5, 0.125, -3.75],dtype='d') +# y = zeros(3,dtype='d') +# +# self.datsp.matvec(x,y) +# assert_array_equal(self.datsp*x,y) +# +# #column vector +# x = array([1.25, -6.5, 0.125, -3.75],dtype='d') +# x = x.reshape(4,1) +# y = zeros((3,1),dtype='d') +# +# self.datsp.matvec(x,y) +# assert_array_equal(self.datsp*x,y) +# +# # improper output type +# x = array([1.25, -6.5, 0.125, -3.75],dtype='d') +# y = zeros(3,dtype='i') +# +# self.assertRaises( ValueError, self.datsp.matvec, x, y ) +# +# # improper output shape +# x = array([1.25, -6.5, 0.125, -3.75],dtype='d') +# y = zeros(2,dtype='d') +# +# self.assertRaises( ValueError, self.datsp.matvec, x, y ) +# +# # proper upcast output type +# x = array([1.25, -6.5, 0.125, -3.75],dtype='complex64') +# x.imag = [1,2,3,4] +# y = zeros(3,dtype='complex128') +# +# self.datsp.matvec(x,y) +# assert_array_equal(self.datsp*x,y) +# assert_equal((self.datsp*x).dtype,y.dtype) - # proper upcast output type - x = array([1.25, -6.5, 0.125, -3.75],dtype='complex64') - x.imag = [1,2,3,4] - y = zeros(3,dtype='complex128') - - self.datsp.matvec(x,y) - assert_array_equal(self.datsp*x,y) - assert_equal((self.datsp*x).dtype,y.dtype) - class _TestGetSet: def test_setelement(self): a = self.spmatrix((3,4)) From scipy-svn at scipy.org Thu Jan 31 21:04:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 31 Jan 2008 20:04:28 -0600 (CST) Subject: [Scipy-svn] r3883 - trunk/scipy/ndimage/register Message-ID: <20080201020428.824FF39C0A2@new.scipy.org> Author: wnbell Date: 2008-01-31 20:04:23 -0600 (Thu, 31 Jan 2008) New Revision: 3883 Removed: trunk/scipy/ndimage/register/setup.pyc Log: remove pyc file from SVN Deleted: trunk/scipy/ndimage/register/setup.pyc =================================================================== (Binary files differ) From scipy-svn at scipy.org Thu Jan 31 22:06:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 31 Jan 2008 21:06:46 -0600 (CST) Subject: [Scipy-svn] r3884 - in trunk/scipy/sparse: . sparsetools Message-ID: <20080201030646.2E7CC39C0A2@new.scipy.org> Author: wnbell Date: 2008-01-31 21:06:35 -0600 (Thu, 31 Jan 2008) New Revision: 3884 Modified: trunk/scipy/sparse/csr.py trunk/scipy/sparse/sparsetools/sparsetools.h trunk/scipy/sparse/sparsetools/sparsetools.i trunk/scipy/sparse/sparsetools/sparsetools.py trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx Log: implemented CSR->BSR in sparsetools Modified: trunk/scipy/sparse/csr.py =================================================================== --- trunk/scipy/sparse/csr.py 2008-02-01 02:04:23 UTC (rev 3883) +++ trunk/scipy/sparse/csr.py 2008-02-01 03:06:35 UTC (rev 3884) @@ -11,10 +11,11 @@ concatenate from base import spmatrix, isspmatrix -from sparsetools import csr_tocsc +from sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks from sputils import upcast, to_native, isdense, isshape, getdtype, \ isscalarlike, isintlike + from compressed import _cs_matrix class csr_matrix(_cs_matrix): @@ -148,15 +149,32 @@ return A def tobsr(self,blocksize=None,copy=True): - if blocksize == (1,1): - from bsr import bsr_matrix + from bsr import bsr_matrix + + if blocksize is None: + from spfuncs import estimate_blocksize + return self.tobsr(blocksize=estimate_blocksize(self)) + elif blocksize == (1,1): arg1 = (self.data.reshape(-1,1,1),self.indices,self.indptr) return bsr_matrix( arg1, shape=self.shape, copy=copy ) else: - #TODO make this more efficient - return self.tocoo(copy=False).tobsr(blocksize=blocksize) + R,C = blocksize + M,N = self.shape + + if R < 1 or C < 1 or M % R != 0 or N % C != 0: + raise ValueError('invalid blocksize %s' % blocksize) + + blks = csr_count_blocks(M,N,R,C,self.indptr,self.indices) + + indptr = empty( M/R + 1, dtype=intc ) + indices = empty( blks, dtype=intc ) + data = zeros( (blks,R,C), dtype=self.dtype) + + csr_tobsr(M, N, R, C, self.indptr, self.indices, self.data, \ + indptr, indices, data.ravel() ) + + return bsr_matrix( (data,indices,indptr), shape=self.shape ) - def get_submatrix( self, slice0, slice1 ): """Return a submatrix of this matrix (new matrix is created). Contigous range of rows and columns can be selected using: Modified: trunk/scipy/sparse/sparsetools/sparsetools.h =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.h 2008-02-01 02:04:23 UTC (rev 3883) +++ trunk/scipy/sparse/sparsetools/sparsetools.h 2008-02-01 03:06:35 UTC (rev 3884) @@ -297,7 +297,84 @@ } +/* + * Convert a CSR matrix to BSR format + * + * Input Arguments: + * I n_row - number of rows in A + * I n_col - number of columns in A + * I R - row blocksize + * I C - column blocksize + * I Ap[n_row+1] - row pointer + * I Aj[nnz(A)] - column indices + * T Ax[nnz(A)] - nonzero values + * + * Output Arguments: + * I Bp[n_row/R + 1] - block row pointer + * I Bj[nnz(B)] - column indices + * T Bx[nnz(B)] - nonzero blocks + * + * Note: + * Complexity: Linear + * Output arrays must be preallocated (with Bx initialized to zero) + * + * + */ +template +void csr_tobsr(const I n_row, + const I n_col, + const I R, + const I C, + const I Ap[], + const I Aj[], + const T Ax[], + I Bp[], + I Bj[], + T Bx[]) +{ + std::vector blocks(n_col/C + 1, (T*)0 ); + + assert( n_row % R == 0 ); + assert( n_col % C == 0 ); + + I n_brow = n_row / R; + //I n_bcol = n_col / C; + + I RC = R*C; + I n_blks = 0; + + Bp[0] = 0; + + for(I bi = 0; bi < n_brow; bi++){ + for(I r = 0; r < R; r++){ + I i = R*bi + r; //row index + for(I jj = Ap[i]; jj < Ap[i+1]; jj++){ + I j = Aj[jj]; //column index + + I bj = j / C; + I c = j % C; + + if( blocks[bj] == 0 ){ + blocks[bj] = Bx + RC*n_blks; + Bj[n_blks] = bj; + n_blks++; + } + + *(blocks[bj] + C*r + c) += Ax[jj]; + } + } + + for(I jj = Ap[R*bi]; jj < Ap[R*(bi+1)]; jj++){ + blocks[Aj[jj] / C] = 0; + } + + Bp[bi+1] = n_blks; + } +} + + + /* * Sort CSR column indices inplace * @@ -1359,7 +1436,6 @@ } - //template //void bsr_tocsr(const I n_brow, // const I n_bcol, Modified: trunk/scipy/sparse/sparsetools/sparsetools.i =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.i 2008-02-01 02:04:23 UTC (rev 3883) +++ trunk/scipy/sparse/sparsetools/sparsetools.i 2008-02-01 03:06:35 UTC (rev 3884) @@ -208,10 +208,11 @@ /* - * CSR->CSC or CSC->CSR or CSR = CSR^T or CSC = CSC^T + * CSR->CSC or CSC->CSR or CSR = CSR^T or CSC = CSC^T or CSR->BSR */ INSTANTIATE_ALL(csr_tocsc) INSTANTIATE_ALL(csc_tocsr) +INSTANTIATE_ALL(csr_tobsr) /* * CSR<->COO and CSC<->COO Modified: trunk/scipy/sparse/sparsetools/sparsetools.py =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools.py 2008-02-01 02:04:23 UTC (rev 3883) +++ trunk/scipy/sparse/sparsetools/sparsetools.py 2008-02-01 03:06:35 UTC (rev 3884) @@ -357,6 +357,40 @@ """ return _sparsetools.csc_tocsr(*args) +def csr_tobsr(*args): + """ + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + signed char Ax, int Bp, int Bj, signed char Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + unsigned char Ax, int Bp, int Bj, unsigned char Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + short Ax, int Bp, int Bj, short Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + unsigned short Ax, int Bp, int Bj, unsigned short Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + int Ax, int Bp, int Bj, int Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + unsigned int Ax, int Bp, int Bj, unsigned int Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + long long Ax, int Bp, int Bj, long long Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + unsigned long long Ax, int Bp, int Bj, unsigned long long Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + float Ax, int Bp, int Bj, float Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + double Ax, int Bp, int Bj, double Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + long double Ax, int Bp, int Bj, long double Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + npy_cfloat_wrapper Ax, int Bp, int Bj, npy_cfloat_wrapper Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + npy_cdouble_wrapper Ax, int Bp, int Bj, npy_cdouble_wrapper Bx) + csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, + npy_clongdouble_wrapper Ax, int Bp, int Bj, + npy_clongdouble_wrapper Bx) + """ + return _sparsetools.csr_tobsr(*args) + def coo_tocsr(*args): """ coo_tocsr(int n_row, int n_col, int nnz, int Ai, int Aj, signed char Ax, Modified: trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx =================================================================== --- trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-02-01 02:04:23 UTC (rev 3883) +++ trunk/scipy/sparse/sparsetools/sparsetools_wrap.cxx 2008-02-01 03:06:35 UTC (rev 3884) @@ -22127,6 +22127,2683 @@ } +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + signed char *arg7 ; + int *arg8 ; + int *arg9 ; + signed char *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_BYTE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (signed char*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_BYTE); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (signed char*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(signed char const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned char *arg7 ; + int *arg8 ; + int *arg9 ; + unsigned char *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_UBYTE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (unsigned char*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_UBYTE); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (unsigned char*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(unsigned char const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + short *arg7 ; + int *arg8 ; + int *arg9 ; + short *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_SHORT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (short*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_SHORT); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (short*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(short const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned short *arg7 ; + int *arg8 ; + int *arg9 ; + unsigned short *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_USHORT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (unsigned short*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_USHORT); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (unsigned short*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(unsigned short const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_5(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + int *arg7 ; + int *arg8 ; + int *arg9 ; + int *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_INT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (int*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_INT); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (int*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(int const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_6(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned int *arg7 ; + int *arg8 ; + int *arg9 ; + unsigned int *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_UINT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (unsigned int*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_UINT); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (unsigned int*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(unsigned int const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_7(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + long long *arg7 ; + int *arg8 ; + int *arg9 ; + long long *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_LONGLONG, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (long long*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_LONGLONG); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (long long*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(long long const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_8(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + unsigned long long *arg7 ; + int *arg8 ; + int *arg9 ; + unsigned long long *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_ULONGLONG, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (unsigned long long*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_ULONGLONG); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (unsigned long long*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(unsigned long long const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_9(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + float *arg7 ; + int *arg8 ; + int *arg9 ; + float *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_FLOAT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (float*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_FLOAT); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (float*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(float const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_10(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + double *arg7 ; + int *arg8 ; + int *arg9 ; + double *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_DOUBLE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (double*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_DOUBLE); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (double*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(double const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_11(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + long double *arg7 ; + int *arg8 ; + int *arg9 ; + long double *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_LONGDOUBLE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (long double*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_LONGDOUBLE); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (long double*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(long double const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_12(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_cfloat_wrapper *arg7 ; + int *arg8 ; + int *arg9 ; + npy_cfloat_wrapper *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_CFLOAT, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (npy_cfloat_wrapper*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_CFLOAT); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (npy_cfloat_wrapper*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(npy_cfloat_wrapper const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_13(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_cdouble_wrapper *arg7 ; + int *arg8 ; + int *arg9 ; + npy_cdouble_wrapper *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_CDOUBLE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (npy_cdouble_wrapper*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_CDOUBLE); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (npy_cdouble_wrapper*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(npy_cdouble_wrapper const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr__SWIG_14(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int arg2 ; + int arg3 ; + int arg4 ; + int *arg5 ; + int *arg6 ; + npy_clongdouble_wrapper *arg7 ; + int *arg8 ; + int *arg9 ; + npy_clongdouble_wrapper *arg10 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyArrayObject *array5 = NULL ; + int is_new_object5 ; + PyArrayObject *array6 = NULL ; + int is_new_object6 ; + PyArrayObject *array7 = NULL ; + int is_new_object7 ; + PyArrayObject *temp8 = NULL ; + PyArrayObject *temp9 = NULL ; + PyArrayObject *temp10 = NULL ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PyObject * obj4 = 0 ; + PyObject * obj5 = 0 ; + PyObject * obj6 = 0 ; + PyObject * obj7 = 0 ; + PyObject * obj8 = 0 ; + PyObject * obj9 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOO:csr_tobsr",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "csr_tobsr" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "csr_tobsr" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "csr_tobsr" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_int(obj3, &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "csr_tobsr" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + npy_intp size[1] = { + -1 + }; + array5 = obj_to_array_contiguous_allow_conversion(obj4, PyArray_INT, &is_new_object5); + if (!array5 || !require_dimensions(array5,1) || !require_size(array5,size,1) + || !require_contiguous(array5) || !require_native(array5)) SWIG_fail; + + arg5 = (int*) array5->data; + } + { + npy_intp size[1] = { + -1 + }; + array6 = obj_to_array_contiguous_allow_conversion(obj5, PyArray_INT, &is_new_object6); + if (!array6 || !require_dimensions(array6,1) || !require_size(array6,size,1) + || !require_contiguous(array6) || !require_native(array6)) SWIG_fail; + + arg6 = (int*) array6->data; + } + { + npy_intp size[1] = { + -1 + }; + array7 = obj_to_array_contiguous_allow_conversion(obj6, PyArray_CLONGDOUBLE, &is_new_object7); + if (!array7 || !require_dimensions(array7,1) || !require_size(array7,size,1) + || !require_contiguous(array7) || !require_native(array7)) SWIG_fail; + + arg7 = (npy_clongdouble_wrapper*) array7->data; + } + { + temp8 = obj_to_array_no_conversion(obj7,PyArray_INT); + if (!temp8 || !require_contiguous(temp8) || !require_native(temp8)) SWIG_fail; + arg8 = (int*) array_data(temp8); + } + { + temp9 = obj_to_array_no_conversion(obj8,PyArray_INT); + if (!temp9 || !require_contiguous(temp9) || !require_native(temp9)) SWIG_fail; + arg9 = (int*) array_data(temp9); + } + { + temp10 = obj_to_array_no_conversion(obj9,PyArray_CLONGDOUBLE); + if (!temp10 || !require_contiguous(temp10) || !require_native(temp10)) SWIG_fail; + arg10 = (npy_clongdouble_wrapper*) array_data(temp10); + } + csr_tobsr(arg1,arg2,arg3,arg4,(int const (*))arg5,(int const (*))arg6,(npy_clongdouble_wrapper const (*))arg7,arg8,arg9,arg10); + resultobj = SWIG_Py_Void(); + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return resultobj; +fail: + { + if (is_new_object5 && array5) Py_DECREF(array5); + } + { + if (is_new_object6 && array6) Py_DECREF(array6); + } + { + if (is_new_object7 && array7) Py_DECREF(array7); + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_csr_tobsr(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[11]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = (int)PyObject_Length(args); + for (ii = 0; (ii < argc) && (ii < 10); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_BYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_1(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_UBYTE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_2(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_SHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_3(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_USHORT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_4(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_5(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_UINT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_6(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_LONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_7(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_ULONGLONG)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_8(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_FLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_9(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_DOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_10(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_LONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_11(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_CFLOAT)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_12(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_CDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_13(self, args); + } + } + } + } + } + } + } + } + } + } + } + if (argc == 10) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + int res = SWIG_AsVal_int(argv[3], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + { + _v = (is_array(argv[4]) && PyArray_CanCastSafely(PyArray_TYPE(argv[4]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[5]) && PyArray_CanCastSafely(PyArray_TYPE(argv[5]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[6]) && PyArray_CanCastSafely(PyArray_TYPE(argv[6]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[7]) && PyArray_CanCastSafely(PyArray_TYPE(argv[7]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[8]) && PyArray_CanCastSafely(PyArray_TYPE(argv[8]),PyArray_INT)) ? 1 : 0; + } + if (_v) { + { + _v = (is_array(argv[9]) && PyArray_CanCastSafely(PyArray_TYPE(argv[9]),PyArray_CLONGDOUBLE)) ? 1 : 0; + } + if (_v) { + return _wrap_csr_tobsr__SWIG_14(self, args); + } + } + } + } + } + } + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'csr_tobsr'.\n Possible C/C++ prototypes are:\n"" csr_tobsr<(int,signed char)>(int const,int const,int const,int const,int const [],int const [],signed char const [],int [],int [],signed char [])\n"" csr_tobsr<(int,unsigned char)>(int const,int const,int const,int const,int const [],int const [],unsigned char const [],int [],int [],unsigned char [])\n"" csr_tobsr<(int,short)>(int const,int const,int const,int const,int const [],int const [],short const [],int [],int [],short [])\n"" csr_tobsr<(int,unsigned short)>(int const,int const,int const,int const,int const [],int const [],unsigned short const [],int [],int [],unsigned short [])\n"" csr_tobsr<(int,int)>(int const,int const,int const,int const,int const [],int const [],int const [],int [],int [],int [])\n"" csr_tobsr<(int,unsigned int)>(int const,int const,int const,int const,int const [],int const [],unsigned int const [],int [],int [],unsigned int [])\n"" csr_tobsr<(int,long long)>(int const,int const,int const,int const,int const [],int const [],long long const [],int [],int [],long long [])\n"" csr_tobsr<(int,unsigned long long)>(int const,int const,int const,int const,int const [],int const [],unsigned long long const [],int [],int [],unsigned long long [])\n"" csr_tobsr<(int,float)>(int const,int const,int const,int const,int const [],int const [],float const [],int [],int [],float [])\n"" csr_tobsr<(int,double)>(int const,int const,int const,int const,int const [],int const [],double const [],int [],int [],double [])\n"" csr_tobsr<(int,long double)>(int const,int const,int const,int const,int const [],int const [],long double const [],int [],int [],long double [])\n"" csr_tobsr<(int,npy_cfloat_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_cfloat_wrapper const [],int [],int [],npy_cfloat_wrapper [])\n"" csr_tobsr<(int,npy_cdouble_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_cdouble_wrapper const [],int [],int [],npy_cdouble_wrapper [])\n"" csr_tobsr<(int,npy_clongdouble_wrapper)>(int const,int const,int const,int const,int const [],int const [],npy_clongdouble_wrapper const [],int [],int [],npy_clongdouble_wrapper [])\n"); + return NULL; +} + + SWIGINTERN PyObject *_wrap_expandptr(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int arg1 ; @@ -95595,6 +98272,37 @@ "csc_tocsr(int n_row, int n_col, int Ap, int Ai, npy_clongdouble_wrapper Ax, \n" " int Bp, int Bj, npy_clongdouble_wrapper Bx)\n" ""}, + { (char *)"csr_tobsr", _wrap_csr_tobsr, METH_VARARGS, (char *)"\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " signed char Ax, int Bp, int Bj, signed char Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " unsigned char Ax, int Bp, int Bj, unsigned char Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " short Ax, int Bp, int Bj, short Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " unsigned short Ax, int Bp, int Bj, unsigned short Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " int Ax, int Bp, int Bj, int Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " unsigned int Ax, int Bp, int Bj, unsigned int Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " long long Ax, int Bp, int Bj, long long Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " unsigned long long Ax, int Bp, int Bj, unsigned long long Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " float Ax, int Bp, int Bj, float Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " double Ax, int Bp, int Bj, double Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " long double Ax, int Bp, int Bj, long double Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " npy_cfloat_wrapper Ax, int Bp, int Bj, npy_cfloat_wrapper Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " npy_cdouble_wrapper Ax, int Bp, int Bj, npy_cdouble_wrapper Bx)\n" + "csr_tobsr(int n_row, int n_col, int R, int C, int Ap, int Aj, \n" + " npy_clongdouble_wrapper Ax, int Bp, int Bj, \n" + " npy_clongdouble_wrapper Bx)\n" + ""}, { (char *)"expandptr", _wrap_expandptr, METH_VARARGS, (char *)"expandptr(int n_row, int Ap, int Bi)"}, { (char *)"coo_tocsr", _wrap_coo_tocsr, METH_VARARGS, (char *)"\n" "coo_tocsr(int n_row, int n_col, int nnz, int Ai, int Aj, signed char Ax, \n" From scipy-svn at scipy.org Thu Jan 31 22:13:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 31 Jan 2008 21:13:32 -0600 (CST) Subject: [Scipy-svn] r3885 - trunk/scipy/sparse Message-ID: <20080201031332.C1D4239C0A2@new.scipy.org> Author: wnbell Date: 2008-01-31 21:13:28 -0600 (Thu, 31 Jan 2008) New Revision: 3885 Modified: trunk/scipy/sparse/bsr.py trunk/scipy/sparse/coo.py trunk/scipy/sparse/csc.py trunk/scipy/sparse/spfuncs.py Log: make CSR the default for ->BSR conversions Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-02-01 03:06:35 UTC (rev 3884) +++ trunk/scipy/sparse/bsr.py 2008-02-01 03:13:28 UTC (rev 3885) @@ -395,7 +395,7 @@ def tobsr(self,blocksize=None,copy=False): if blocksize not in [None, self.blocksize]: - return self.tocoo(copy=False).tobsr(blocksize=blocksize) + return self.tocsr().tobsr(blocksize=blocksize) if copy: return self.copy() else: Modified: trunk/scipy/sparse/coo.py =================================================================== --- trunk/scipy/sparse/coo.py 2008-02-01 03:06:35 UTC (rev 3884) +++ trunk/scipy/sparse/coo.py 2008-02-01 03:13:28 UTC (rev 3885) @@ -314,63 +314,7 @@ return dok -# def tobsc(self,blocksize=None): -# if blocksize in [None, (1,1)]: -# return self.tocsc().tobsc(blocksize) -# else: -# return self.transpose().tobsr().transpose() - def tobsr(self,blocksize=None): - from bsr import bsr_matrix - - if self.nnz == 0: - return bsr_matrix(self.shape,blocksize=blocksize,dtype=self.dtype) - - if blocksize is None: - blocksize = estimate_blocksize(self) - elif blocksize in (1,1): - return self.tocsr().tobsr(blocksize) - - M,N = self.shape - X,Y = blocksize - - if (M % X) != 0 or (N % Y) != 0: - raise ValueError, 'shape must be multiple of blocksize' - - i_block,i_sub = divmod(self.row, X) - j_block,j_sub = divmod(self.col, Y) - - perm = lexsort( keys=[j_block,i_block] ) - - i_block = i_block[perm] - j_block = j_block[perm] - - mask = (i_block[1:] != i_block[:-1]) + (j_block[1:] != j_block[:-1]) - mask = concatenate((array([True]),mask)) - - #map self.data[n] -> data[map[n],i_sub[n],j_sub[n]] - map = cumsum(mask) - num_blocks = map[-1] - map -= 1 - - iperm = empty_like(perm) #inverse permutation - iperm[perm] = arange(len(perm)) - - data = zeros( (num_blocks,X,Y), dtype=self.dtype ) - data[map[iperm],i_sub,j_sub] = self.data - - row = i_block[mask] - col = j_block[mask] - - # now row,col,data form BOO format - - temp = cumsum(bincount(row)) - indptr = zeros( M/X + 1, dtype=intc ) - indptr[1:len(temp)+1] = temp - indptr[len(temp)+1:] = temp[-1] - - return bsr_matrix((data,col,indptr),shape=self.shape) - # needed by _data_matrix def _with_data(self,data,copy=True): """Returns a matrix with the same sparsity structure as self, Modified: trunk/scipy/sparse/csc.py =================================================================== --- trunk/scipy/sparse/csc.py 2008-02-01 03:06:35 UTC (rev 3884) +++ trunk/scipy/sparse/csc.py 2008-02-01 03:13:28 UTC (rev 3885) @@ -131,16 +131,6 @@ A.has_sorted_indices = True return A - def tobsr(self, blocksize=None): - if blocksize == (1,1): - from bsr import bsr_matrix - csr = self.tocsr() - arg1 = (csr.data.reshape(-1,1,1),csr.indices,csr.indptr) - return bsr_matrix( arg1, shape=self.shape ) - else: - #TODO make this more efficient - return self.tocoo(copy=False).tobsr(blocksize=blocksize) - def get_submatrix( self, slice0, slice1 ): """Return a submatrix of this matrix (new matrix is created). Contigous range of rows and columns can be selected using: Modified: trunk/scipy/sparse/spfuncs.py =================================================================== --- trunk/scipy/sparse/spfuncs.py 2008-02-01 03:06:35 UTC (rev 3884) +++ trunk/scipy/sparse/spfuncs.py 2008-02-01 03:13:28 UTC (rev 3885) @@ -44,6 +44,9 @@ if not (isspmatrix_csr(A) or isspmatrix_csc(A)): A = csr_matrix(A) + if A.nnz == 0: + return (1,1) + if not 0 < efficiency < 1.0: raise ValueError,'efficiency must satisfy 0.0 < efficiency < 1.0'