[Scipy-svn] r3638 - in trunk/scipy/sparse: . tests

scipy-svn at scipy.org scipy-svn at scipy.org
Tue Dec 11 23:48:03 EST 2007


Author: wnbell
Date: 2007-12-11 22:47:56 -0600 (Tue, 11 Dec 2007)
New Revision: 3638

Modified:
   trunk/scipy/sparse/sparse.py
   trunk/scipy/sparse/tests/test_sparse.py
Log:
unified format for empty sparse matrices
fixed bug in dok_matrix.toarray()
moved empty unittest to _TestCS


Modified: trunk/scipy/sparse/sparse.py
===================================================================
--- trunk/scipy/sparse/sparse.py	2007-12-12 04:04:17 UTC (rev 3637)
+++ trunk/scipy/sparse/sparse.py	2007-12-12 04:47:56 UTC (rev 3638)
@@ -1951,9 +1951,12 @@
 
     def tocoo(self):
         """ Return a copy of this matrix in COOrdinate format"""
-        data = asarray(self.values(),dtype=self.dtype)
-        indices = asarray(self.keys(),dtype=intc).T
-        return coo_matrix((data,indices),dims=self.shape,dtype=self.dtype)
+        if self.getnnz() == 0:
+            return coo_matrix(self.shape,dtype=self.dtype)
+        else:
+            data    = asarray(self.values(), dtype=self.dtype)
+            indices = asarray(self.keys(), dtype=intc).T
+            return coo_matrix((data,indices),dims=self.shape,dtype=self.dtype)
 
     def todok(self,copy=False):
         if copy:
@@ -1967,18 +1970,10 @@
 
     def tocsc(self):
         """ Return a copy of this matrix in Compressed Sparse Column format"""
-        # Fast sort on columns using the Schwartzian transform
         return self.tocoo().tocsc()
 
     def toarray(self):
-        new = zeros(self.shape, dtype=self.dtype)
-        for key in self.keys():
-            ikey0 = int(key[0])
-            ikey1 = int(key[1])
-            new[ikey0, ikey1] = self[key]
-        if abs(new.imag).max() == 0:
-            new = new.real
-        return new
+        return self.tocsr().toarray()
 
     def resize(self, shape):
         """ Resize the matrix to dimensions given by 'shape', removing any
@@ -2002,7 +1997,7 @@
     """ A sparse matrix in coordinate list format.
 
     COO matrices are created either as:
-        A = coo_matrix(None, dims=(m, n), [dtype])
+        A = coo_matrix( (m, n), [dtype])
     for a zero matrix, or as:
         A = coo_matrix(M)
     where M is a dense matrix or rank 2 ndarray, or as:
@@ -2028,37 +2023,46 @@
     def __init__(self, arg1, dims=None, dtype=None):
         spmatrix.__init__(self)
         if isinstance(arg1, tuple):
-            try:
-                obj, ij = arg1
-            except:
-                raise TypeError, "invalid input format"
+            if isshape(arg1):
+                M, N = arg1
+                self.shape = (M,N)
+                self.row  = array([], dtype=intc)
+                self.col  = array([], dtype=intc)
+                self.data = array([],getdtype(dtype, default=float))
+            else:
+                try:
+                    obj, ij = arg1
+                except:
+                    raise TypeError, "invalid input format"
 
-            try:
-                if len(ij) != 2:
-                    raise TypeError
-            except TypeError:
-                raise TypeError, "invalid input format"
+                try:
+                    if len(ij) != 2:
+                        raise TypeError
+                except TypeError:
+                    raise TypeError, "invalid input format"
 
-            self.row = asarray(ij[0])
-            self.col = asarray(ij[1])
-            self.data = asarray(obj)
+                self.row = asarray(ij[0])
+                self.col = asarray(ij[1])
+                self.data = asarray(obj)
 
-            if dims is None:
-                if len(self.row) == 0 or len(self.col) == 0:
-                    raise ValueError, "cannot infer dimensions from zero sized index arrays"
-                M = self.row.max() + 1
-                N = self.col.max() + 1
-                self.shape = (M, N)
-            else:
-                # Use 2 steps to ensure dims has length 2.
-                M, N = dims
-                self.shape = (M, N)
+                if dims is None:
+                    if len(self.row) == 0 or len(self.col) == 0:
+                        raise ValueError, "cannot infer dimensions from zero sized index arrays"
+                    M = self.row.max() + 1
+                    N = self.col.max() + 1
+                    self.shape = (M, N)
+                else:
+                    # Use 2 steps to ensure dims has length 2.
+                    M, N = dims
+                    self.shape = (M, N)
 
-        elif arg1 is None:      # clumsy!  We should make ALL arguments
-                                # keyword arguments instead!
+        elif arg1 is None:
             # Initialize an empty matrix.
             if not isinstance(dims, tuple) or not isintlike(dims[0]):
                 raise TypeError, "dimensions not understood"
+            warnings.warn('coo_matrix(None, dims=(M,N)) is deprecated, ' \
+                            'use coo_matrix( (M,N) ) instead', \
+                            DeprecationWarning)
             self.shape = dims
             self.data = array([],getdtype(dtype, default=float))
             self.row = array([],dtype=intc)
@@ -2766,7 +2770,7 @@
 
     if a.nnz == 0 or b.nnz == 0:
         # kronecker product is the zero matrix
-        return coo_matrix(None, dims=output_shape)
+        return coo_matrix( output_shape )
 
 
     # expand entries of a into blocks

Modified: trunk/scipy/sparse/tests/test_sparse.py
===================================================================
--- trunk/scipy/sparse/tests/test_sparse.py	2007-12-12 04:04:17 UTC (rev 3637)
+++ trunk/scipy/sparse/tests/test_sparse.py	2007-12-12 04:47:56 UTC (rev 3638)
@@ -37,6 +37,23 @@
         assert_equal(self.datsp[0,1],0)
         assert_equal(self.datsp[1,0],3)
         assert_equal(self.datsp[2,1],2)
+    
+    def check_empty(self):
+        """Test manipulating empty matrices. Fails in SciPy SVN <= r1768
+        """
+        shape = (5, 5)
+        for mytype in ['int32', 'float32', 'float64', 'complex64', 'complex128']:
+            a = self.spmatrix(shape, dtype=mytype)
+            b = a + a
+            c = 2 * a
+            d = a * a.tocsc()
+            e = a * a.tocsr()
+            f = a * a.tocoo()
+            for m in [a,b,c,d,e,f]:
+                assert_equal(m.A, a.A*a.A)
+                # These fail in all revisions <= r1768:
+                assert_equal(m.dtype,mytype)
+                assert_equal(m.A.dtype,mytype)
 
     def check_abs(self):
         A = matrix([[-1, 0, 17],[0, -5, 0],[1, -4, 0],[0,0,0]],'d')
@@ -728,23 +745,6 @@
         csr = csr_matrix((data, indices, indptr))
         assert_array_equal(csr.shape,(3,6))
     
-    def check_empty(self):
-        """Test manipulating empty matrices. Fails in SciPy SVN <= r1768
-        """
-        # This test should be made global (in _TestCS), but first we
-        # need a uniform argument order / syntax for constructing an
-        # empty sparse matrix. (coo_matrix is currently different).
-        shape = (5, 5)
-        for mytype in ['int32', 'float32', 'float64', 'complex64', 'complex128']:
-            a = self.spmatrix(shape, dtype=mytype)
-            b = a + a
-            c = 2 * a
-            d = a + a.tocsc()
-            e = a * a.tocoo()
-            assert_equal(e.A, a.A*a.A)
-            # These fail in all revisions <= r1768:
-            assert_equal(e.dtype,mytype)
-            assert_equal(e.A.dtype,mytype)
 
     def check_sort_indices(self):
         data    = arange( 5 )
@@ -819,23 +819,6 @@
         csc = csc_matrix((data, indices, indptr))
         assert_array_equal(csc.shape,(6,3))
     
-    def check_empty(self):
-        """Test manipulating empty matrices. Fails in SciPy SVN <= r1768
-        """
-        # This test should be made global (in _TestCS), but first we
-        # need a uniform argument order / syntax for constructing an
-        # empty sparse matrix. (coo_matrix is currently different).
-        shape = (5, 5)
-        for mytype in ['int32', 'float32', 'float64', 'complex64', 'complex128']:
-            a = self.spmatrix(shape, dtype=mytype)
-            b = a + a
-            c = 2 * a
-            d = a + a.tocsc()
-            e = a * a.tocoo()
-            assert_equal(e.A, a.A*a.A)
-            assert_equal(e.dtype, mytype)
-            assert_equal(e.A.dtype, mytype)
-
     def check_sort_indices(self):
         data = arange( 5 )
         row = array( [7, 2, 1, 5, 4] )
@@ -1223,7 +1206,7 @@
 
     def check_constructor3(self):
         """empty matrix"""
-        coo = coo_matrix(None,dims=(4,3))
+        coo = coo_matrix( (4,3) )
 
         assert_array_equal(coo.shape,(4,3))
         assert_array_equal(coo.row,[])




More information about the Scipy-svn mailing list