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

scipy-svn at scipy.org scipy-svn at scipy.org
Thu Feb 14 01:00:16 EST 2008


Author: wnbell
Date: 2008-02-14 00:00:10 -0600 (Thu, 14 Feb 2008)
New Revision: 3937

Modified:
   trunk/scipy/sparse/compressed.py
   trunk/scipy/sparse/csc.py
   trunk/scipy/sparse/csr.py
   trunk/scipy/sparse/tests/test_base.py
Log:
begin cleanup of CSR/CSC __getitem__


Modified: trunk/scipy/sparse/compressed.py
===================================================================
--- trunk/scipy/sparse/compressed.py	2008-02-13 21:12:54 UTC (rev 3936)
+++ trunk/scipy/sparse/compressed.py	2008-02-14 06:00:10 UTC (rev 3937)
@@ -404,30 +404,9 @@
             return spmatrix.sum(self,axis)
             raise ValueError, "axis out of bounds"
 
-    def _get_single_element(self,row,col):
-        M, N = self.shape
-        if (row < 0):
-            row += M
-        if (col < 0):
-            col += N
-        if not (0<=row<M) or not (0<=col<N):
-            raise IndexError, "index out of bounds"
-        
-        major_index, minor_index = self._swap((row,col))
-
-        start = self.indptr[major_index]
-        end   = self.indptr[major_index+1]
-        indxs = where(minor_index == self.indices[start:end])[0]
-
-        num_matches = len(indxs)
-
-        if num_matches == 0:
-            # entry does not appear in the matrix
-            return 0
-        elif num_matches == 1:
-            return self.data[start:end][indxs[0]]
-        else:
-            raise ValueError,'nonzero entry (%d,%d) occurs more than once' % (row,col)
+    #######################
+    # Getting and Setting #
+    #######################
     
     def __getitem__(self, key):
         if isinstance(key, tuple):
@@ -447,7 +426,7 @@
                     out_shape   = self._swap( (1, stop-start) )
                     return self._get_slice( major, start, stop, stride, out_shape)
                 elif isinstance( row, slice) or isinstance(col, slice):
-                    return self.get_submatrix( row, col )
+                    return self._get_submatrix( row, col )
                 else:
                     raise NotImplementedError
 
@@ -455,7 +434,33 @@
             return self[key, :]
         else:
             raise IndexError, "invalid index"
+    
 
+    def _get_single_element(self,row,col):
+        M, N = self.shape
+        if (row < 0):
+            row += M
+        if (col < 0):
+            col += N
+        if not (0<=row<M) or not (0<=col<N):
+            raise IndexError, "index out of bounds"
+        
+        major_index, minor_index = self._swap((row,col))
+
+        start = self.indptr[major_index]
+        end   = self.indptr[major_index+1]
+        indxs = where(minor_index == self.indices[start:end])[0]
+
+        num_matches = len(indxs)
+
+        if num_matches == 0:
+            # entry does not appear in the matrix
+            return 0
+        elif num_matches == 1:
+            return self.data[start:end][indxs[0]]
+        else:
+            raise ValueError,'nonzero entry (%d,%d) occurs more than once' % (row,col)
+
     def _get_slice(self, i, start, stop, stride, shape):
         """Returns a copy of the elements 
             [i, start:stop:string] for row-oriented matrices
@@ -481,6 +486,57 @@
         return self.__class__((data, index, indptr), shape=shape, \
                               dtype=self.dtype)
 
+    def _get_submatrix( self, slice0, slice1 ):
+        """Return a submatrix of this matrix (new matrix is created)."""
+
+        slice0, slice1 = self._swap((slice0,slice1))
+        shape0, shape1 = self._swap(self.shape)
+        def _process_slice( sl, num ):
+            if isinstance( sl, slice ):
+                i0, i1 = sl.start, sl.stop
+                if i0 is None:
+                    i0 = 0
+                elif i0 < 0:
+                    i0 = num + i0
+
+                if i1 is None:
+                    i1 = num
+                elif i1 < 0:
+                    i1 = num + i1
+
+                return i0, i1
+
+            elif isscalar( sl ):
+                if sl < 0:
+                    sl += num
+
+                return sl, sl + 1
+
+            else:
+                return sl[0], sl[1]
+
+        def _in_bounds( i0, i1, num ):
+            if not (0<=i0<num) or not (0<i1<=num) or not (i0<i1):
+                raise IndexError,\
+                      "index out of bounds: 0<=%d<%d, 0<=%d<%d, %d<%d" %\
+                      (i0, num, i1, num, i0, i1)
+
+        i0, i1 = _process_slice( slice0, shape0 )
+        j0, j1 = _process_slice( slice1, shape1 )
+        _in_bounds( i0, i1, shape0 )
+        _in_bounds( j0, j1, shape1 )
+
+        aux = sparsetools.get_csr_submatrix( shape0, shape1,
+                                             self.indptr, self.indices,
+                                             self.data,
+                                             i0, i1, j0, j1 )
+
+        data, indices, indptr = aux[2], aux[1], aux[0]
+        shape = self._swap( (i1 - i0, j1 - j0) )
+
+        return self.__class__( (data,indices,indptr), shape=shape )
+
+
     def __setitem__(self, key, val):
         if isinstance(key, tuple):
             row,col = key
@@ -724,47 +780,4 @@
         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)."""
-        def _process_slice( sl, num ):
-            if isinstance( sl, slice ):
-                i0, i1 = sl.start, sl.stop
-                if i0 is None:
-                    i0 = 0
-                elif i0 < 0:
-                    i0 = num + i0
 
-                if i1 is None:
-                    i1 = num
-                elif i1 < 0:
-                    i1 = num + i1
-
-                return i0, i1
-
-            elif isscalar( sl ):
-                if sl < 0:
-                    sl += num
-
-                return sl, sl + 1
-
-            else:
-                return sl[0], sl[1]
-
-        def _in_bounds( i0, i1, num ):
-            if not (0<=i0<num) or not (0<i1<=num) or not (i0<i1):
-                raise IndexError,\
-                      "index out of bounds: 0<=%d<%d, 0<=%d<%d, %d<%d" %\
-                      (i0, num, i1, num, i0, i1)
-
-        i0, i1 = _process_slice( slice0, shape0 )
-        j0, j1 = _process_slice( slice1, shape1 )
-        _in_bounds( i0, i1, shape0 )
-        _in_bounds( j0, j1, shape1 )
-
-        aux = sparsetools.get_csr_submatrix( shape0, shape1,
-                                             self.indptr, self.indices,
-                                             self.data,
-                                             i0, i1, j0, j1 )
-        data, indices, indptr = aux[2], aux[1], aux[0]
-        return data, indices, indptr, i1 - i0, j1 - j0
-

Modified: trunk/scipy/sparse/csc.py
===================================================================
--- trunk/scipy/sparse/csc.py	2008-02-13 21:12:54 UTC (rev 3936)
+++ trunk/scipy/sparse/csc.py	2008-02-14 06:00:10 UTC (rev 3937)
@@ -131,16 +131,6 @@
         A.has_sorted_indices = True
         return A
 
-    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."""
-        aux = _cs_matrix._get_submatrix( self, self.shape[1], self.shape[0],
-                                         slice1, slice0 )
-        nr, nc = aux[3:]
-        return self.__class__( aux[:3], shape = (nc, nr) )
     
     # these functions are used by the parent class (_cs_matrix)
     # to remove redudancy between csc_matrix and csr_matrix

Modified: trunk/scipy/sparse/csr.py
===================================================================
--- trunk/scipy/sparse/csr.py	2008-02-13 21:12:54 UTC (rev 3936)
+++ trunk/scipy/sparse/csr.py	2008-02-14 06:00:10 UTC (rev 3937)
@@ -174,20 +174,6 @@
 
             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:
-          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:]
-        return self.__class__( aux[:3], shape = (nr, nc) )
-
     # these functions are used by the parent class (_cs_matrix)
     # to remove redudancy between csc_matrix and csr_matrix
     def _swap(self,x):

Modified: trunk/scipy/sparse/tests/test_base.py
===================================================================
--- trunk/scipy/sparse/tests/test_base.py	2008-02-13 21:12:54 UTC (rev 3936)
+++ trunk/scipy/sparse/tests/test_base.py	2008-02-14 06:00:10 UTC (rev 3937)
@@ -851,19 +851,7 @@
         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 )
-        i1 = ( 1, 3 )
-        b = a.get_submatrix( i0, i1 )
 
-        aa = a.toarray()
-        ab = b.toarray()
-
-        assert b.dtype == a.dtype
-        assert b.shape == (2,2)
-        assert_equal( ab, aa[i0,i1[0]:i1[1]] )
-
 class TestCSC(_TestCommon, _TestGetSet, _TestSolve,
         _TestInplaceArithmetic, _TestArithmetic, _TestMatvecOutput,
         _TestHorizSlicing, _TestVertSlicing, _TestBothSlicing,
@@ -935,19 +923,7 @@
         assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
         assert_array_equal(asp.todense(),bsp.todense())
 
-    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 )
-        b = a.get_submatrix( i0, i1 )
 
-        aa = a.toarray()
-        ab = b.toarray()
-
-        assert_equal(b.dtype, a.dtype)
-        assert_equal(b.shape, (2,2))
-        assert_equal( ab, aa[i0,i1[0]:i1[1]] )
-
 class TestDOK(_TestCommon, _TestGetSet, _TestSolve, TestCase):
     spmatrix = dok_matrix
 




More information about the Scipy-svn mailing list