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

scipy-svn@scip... scipy-svn@scip...
Sat Oct 25 17:19:52 CDT 2008


Author: wnbell
Date: 2008-10-25 17:19:48 -0500 (Sat, 25 Oct 2008)
New Revision: 4835

Modified:
   trunk/scipy/sparse/base.py
   trunk/scipy/sparse/dok.py
   trunk/scipy/sparse/lil.py
   trunk/scipy/sparse/sputils.py
   trunk/scipy/sparse/tests/test_base.py
   trunk/scipy/sparse/tests/test_sputils.py
Log:
sparse matrices now conform to spmatrix( (M,N) ) -> empty M-by-N matrix
added tests for invalid shapes in case above


Modified: trunk/scipy/sparse/base.py
===================================================================
--- trunk/scipy/sparse/base.py	2008-10-25 21:26:45 UTC (rev 4834)
+++ trunk/scipy/sparse/base.py	2008-10-25 22:19:48 UTC (rev 4835)
@@ -70,7 +70,7 @@
             raise TypeError('invalid shape')
 
         if not (shape[0] >= 1 and shape[1] >= 1):
-            raise TypeError('invalid shape')
+            raise ValueError('invalid shape')
 
         if (self._shape != shape) and (self._shape is not None):
             try:

Modified: trunk/scipy/sparse/dok.py
===================================================================
--- trunk/scipy/sparse/dok.py	2008-10-25 21:26:45 UTC (rev 4834)
+++ trunk/scipy/sparse/dok.py	2008-10-25 22:19:48 UTC (rev 4835)
@@ -13,8 +13,10 @@
 from sputils import isdense, getdtype, isshape, isintlike, isscalarlike
 
 class dok_matrix(spmatrix, dict):
-    """Dictionary Of Keys based matrix.  This is an efficient
-    structure for constructing sparse matrices incrementally.
+    """Dictionary Of Keys based sparse matrix.
+    
+    This is an efficient structure for constructing sparse 
+    matrices incrementally.
 
     This can be instatiated in several ways:
         dok_matrix(D)

Modified: trunk/scipy/sparse/lil.py
===================================================================
--- trunk/scipy/sparse/lil.py	2008-10-25 21:26:45 UTC (rev 4834)
+++ trunk/scipy/sparse/lil.py	2008-10-25 22:19:48 UTC (rev 4835)
@@ -16,23 +16,22 @@
 from sputils import getdtype,isshape,issequence,isscalarlike
 
 class lil_matrix(spmatrix):
-    """Row-based linked list matrix
+    """Row-based linked list sparse matrix
 
+    This is an efficient structure for constructing sparse 
+    matrices incrementally.
 
     This can be instantiated in several ways:
-        csc_matrix(D)
+        lil_matrix(D)
             with a dense matrix or rank-2 ndarray D
 
-        csc_matrix(S)
+        lil_matrix(S)
             with another sparse matrix S (equivalent to S.tocsc())
 
-        csc_matrix((M, N), [dtype])
+        lil_matrix((M, N), [dtype])
             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`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
-
     Notes
     -----
 
@@ -60,40 +59,25 @@
 
     """
 
-    def __init__(self, A=None, shape=None, dtype=None, copy=False):
-        """ Create a new list-of-lists sparse matrix.  An optional
-        argument A is accepted, which initializes the lil_matrix with it.
-        This can be a tuple of dimensions (M, N) or a dense array /
-        matrix to copy, or a sparse matrix.
-        """
+    def __init__(self, arg1, shape=None, dtype=None, copy=False):
         spmatrix.__init__(self)
-        self.dtype = getdtype(dtype, A, default=float)
+        self.dtype = getdtype(dtype, arg1, default=float)
 
         # First get the shape
-        if A is None:
-            if not isshape(shape):
-                raise TypeError("need a valid shape")
-            M, N = shape
-            self.shape = (M,N)
-            self.rows = numpy.empty((M,), dtype=object)
-            self.data = numpy.empty((M,), dtype=object)
-            for i in range(M):
-                self.rows[i] = []
-                self.data[i] = []
-        elif isspmatrix(A):
-            if isspmatrix_lil(A) and copy:
-                A = A.copy()
+        if isspmatrix(arg1):
+            if isspmatrix_lil(arg1) and copy:
+                A = arg1.copy()
             else:
-                A = A.tolil()
+                A = arg1.tolil()
             self.shape = A.shape
             self.dtype = A.dtype
             self.rows  = A.rows
             self.data  = A.data
-        elif isinstance(A,tuple):
-            if isshape(A):
+        elif isinstance(arg1,tuple):
+            if isshape(arg1):
                 if shape is not None:
                     raise ValueError('invalid use of shape parameter')
-                M, N = A
+                M, N = arg1
                 self.shape = (M,N)
                 self.rows = numpy.empty((M,), dtype=object)
                 self.data = numpy.empty((M,), dtype=object)
@@ -101,11 +85,11 @@
                     self.rows[i] = []
                     self.data[i] = []
             else:
-                raise TypeError,'unrecognized lil_matrix constructor usage'
+                raise TypeError('unrecognized lil_matrix constructor usage')
         else:
             #assume A is dense
             try:
-                A = asmatrix(A)
+                A = asmatrix(arg1)
             except TypeError:
                 raise TypeError, "unsupported matrix type"
             else:
@@ -334,7 +318,7 @@
     def _mul_scalar(self, other):
         if other == 0:
             # Multiply by zero: return the zero matrix
-            new = lil_matrix(shape=self.shape, dtype=self.dtype)
+            new = lil_matrix(self.shape, dtype=self.dtype)
         else:
             new = self.copy()
             # Multiply this scalar by every element.

Modified: trunk/scipy/sparse/sputils.py
===================================================================
--- trunk/scipy/sparse/sputils.py	2008-10-25 21:26:45 UTC (rev 4834)
+++ trunk/scipy/sparse/sputils.py	2008-10-25 22:19:48 UTC (rev 4835)
@@ -100,7 +100,7 @@
         # Assume it's a tuple of matrix dimensions (M, N)
         (M, N) = x
         assert isintlike(M) and isintlike(N)   # raises TypeError unless integers
-        assert M > 0 and N > 0
+        #assert M > 0 and N > 0
     except (ValueError, TypeError, AssertionError):
         return False
     else:

Modified: trunk/scipy/sparse/tests/test_base.py
===================================================================
--- trunk/scipy/sparse/tests/test_base.py	2008-10-25 21:26:45 UTC (rev 4834)
+++ trunk/scipy/sparse/tests/test_base.py	2008-10-25 22:19:48 UTC (rev 4835)
@@ -34,7 +34,6 @@
 warnings.simplefilter('ignore',SparseEfficiencyWarning)
 
 
-#TODO check that invalid shape in constructor raises exception
 #TODO check that spmatrix( ... , copy=X ) is respected
 #TODO test prune
 #TODO test has_sorted_indices
@@ -44,14 +43,25 @@
     def setUp(self):
         self.dat = matrix([[1,0,0,2],[3,0,1,0],[0,2,0,0]],'d')
         self.datsp = self.spmatrix(self.dat)
+    
+    def test_empty(self):
+        """create empty matrices"""
+        
+        assert_equal(self.spmatrix((3,3)).todense(), np.zeros((3,3)))
+        assert_equal(self.spmatrix((3,3)).nnz, 0)
 
+    def test_invalid_shapes(self):
+        assert_raises(ValueError, self.spmatrix, (-1,3) )
+        assert_raises(ValueError, self.spmatrix, (3,-1) )
+        assert_raises(ValueError, self.spmatrix, (-1,-1) )
+
     def test_repr(self):
         repr(self.datsp)
 
     def test_str(self):
         str(self.datsp)
 
-    def test_empty(self):
+    def test_empty_arithmetic(self):
         """Test manipulating empty matrices. Fails in SciPy SVN <= r1768
         """
         shape = (5, 5)
@@ -304,17 +314,11 @@
         assert(isinstance( M * array([1,2,3]), ndarray))
         assert(isinstance( M * matrix([1,2,3]).T, matrix))
 
-
         #ensure exception is raised for improper dimensions
         bad_vecs = [array([1,2]), array([1,2,3,4]), array([[1],[2]]),
                     matrix([1,2,3]), matrix([[1],[2]])]
-        caught = 0
         for x in bad_vecs:
-            try:
-                y = M * x
-            except ValueError:
-                caught += 1
-        assert_equal(caught,len(bad_vecs))
+            assert_raises(ValueError, M.__mul__, x)
 
         # Should this be supported or not?!
         #flat = array([1,2,3])
@@ -1371,8 +1375,8 @@
     def test_constructor4(self):
         """from dense matrix"""
         mat = array([[0,1,0,0],
-                           [7,0,3,0],
-                           [0,4,0,0]])
+                     [7,0,3,0],
+                     [0,4,0,0]])
         coo = coo_matrix(mat)
         assert_array_equal(coo.todense(),mat)
 
@@ -1386,10 +1390,16 @@
     spmatrix = dia_matrix
 
     def test_constructor1(self):
-        pass
-        #TODO add test
+        D = matrix([[1, 0, 3, 0],
+                    [1, 2, 0, 4],
+                    [0, 2, 3, 0],
+                    [0, 0, 3, 4]])
+        data    = np.array([[1,2,3,4]]).repeat(3,axis=0)
+        offsets = np.array([0,-1,2])
+        assert_equal(dia_matrix( (data,offsets), shape=(4,4)).todense(), D)
 
 
+
 class TestBSR(_TestCommon, _TestArithmetic, _TestInplaceArithmetic,
         _TestMatvecOutput, TestCase):
     spmatrix = bsr_matrix

Modified: trunk/scipy/sparse/tests/test_sputils.py
===================================================================
--- trunk/scipy/sparse/tests/test_sputils.py	2008-10-25 21:26:45 UTC (rev 4834)
+++ trunk/scipy/sparse/tests/test_sputils.py	2008-10-25 22:19:48 UTC (rev 4835)
@@ -47,10 +47,9 @@
         assert_equal(isshape( (1,2) ),True)
         assert_equal(isshape( (5,2) ),True)
 
-        assert_equal(isshape( (-1,4) ),False)
         assert_equal(isshape( (1.5,2) ),False)
-        assert_equal(isshape( (0,4) ),False)
         assert_equal(isshape( (2,2,2) ),False)
+        assert_equal(isshape( ([2],2) ),False)
 
     def test_issequence(self):
         assert_equal(issequence( (1,) ),True)



More information about the Scipy-svn mailing list