[Scipy-svn] r3721 - trunk/scipy/sparse

scipy-svn at scipy.org scipy-svn at scipy.org
Tue Dec 25 20:50:45 EST 2007


Author: wnbell
Date: 2007-12-25 19:50:00 -0600 (Tue, 25 Dec 2007)
New Revision: 3721

Modified:
   trunk/scipy/sparse/compressed.py
   trunk/scipy/sparse/csc.py
   trunk/scipy/sparse/csr.py
Log:
consolidated getitem


Modified: trunk/scipy/sparse/compressed.py
===================================================================
--- trunk/scipy/sparse/compressed.py	2007-12-26 00:03:49 UTC (rev 3720)
+++ trunk/scipy/sparse/compressed.py	2007-12-26 01:50:00 UTC (rev 3721)
@@ -7,13 +7,14 @@
 
 import numpy
 from numpy import array, matrix, asarray, asmatrix, zeros, rank, intc, \
-        empty, hstack, isscalar, ndarray, shape, searchsorted, empty_like
+        empty, hstack, isscalar, ndarray, shape, searchsorted, empty_like, \
+        where
 
 from base import spmatrix, isspmatrix
 from data import _data_matrix
 import sparsetools
 from sputils import upcast, to_native, isdense, isshape, getdtype, \
-        isscalarlike
+        isscalarlike, isintlike
 
 
 
@@ -389,7 +390,57 @@
             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 + row
+        if (col < 0):
+            col = N + col
+        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 __getitem__(self, key):
+        if isinstance(key, tuple):
+            row = key[0]
+            col = key[1]
+           
+            #TODO implement CSR[ [1,2,3], X ] with sparse matmat
+
+            if isintlike(row) and isintlike(col):
+                return self._get_single_element(row,col)
+            else:
+                major,minor = self._swap((row,col))
+                if isintlike(major) and isinstance(minor,slice):
+                    minor_shape = self._swap(self.shape)[1]
+                    start, stop, stride = minor.indices(minor_shape)
+                    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 )
+                else:
+                    raise NotImplementedError
+
+        elif isintlike(key):
+            return self[key, :]
+        else:
+            raise IndexError, "invalid index"
+
     def _get_slice(self, i, start, stop, stride, shape):
         """Returns a copy of the elements 
             [i, start:stop:string] for row-oriented matrices
@@ -400,6 +451,9 @@
         if stop <= start:
             raise ValueError, "slice width must be >= 1"
 
+        #TODO make [i,:] faster
+        #TODO implement [i,x:y:z]
+
         indices = []
 
         for ind in xrange(self.indptr[i], self.indptr[i+1]):

Modified: trunk/scipy/sparse/csc.py
===================================================================
--- trunk/scipy/sparse/csc.py	2007-12-26 00:03:49 UTC (rev 3720)
+++ trunk/scipy/sparse/csc.py	2007-12-26 01:50:00 UTC (rev 3721)
@@ -92,61 +92,6 @@
         for r in xrange(self.shape[0]):
             yield csr[r,:]
 
-    def __getitem__(self, key):
-        #TODO unify these in _cs_matrix
-        if isinstance(key, tuple):
-            row = key[0]
-            col = key[1]
-            
-            if isinstance(col, slice):
-                # Returns a new matrix!
-                return self.get_submatrix( row, col )
-            elif isinstance(row, slice):
-                return self._getslice(row, col)
-            
-            M, N = self.shape
-            if (row < 0):
-                row = M + row
-            if (col < 0):
-                col = N + col
-            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)
-        
-        elif isintlike(key):
-            # Was: return self.data[key]
-            # If this is allowed, it should return the relevant row, as for
-            # dense matrices (and __len__ should be supported again).
-            raise IndexError, "integer index not supported for csc_matrix"
-        else:
-            raise IndexError, "invalid index"
-    
-    def _getslice(self, i, myslice):
-        return self._getcolslice(i, myslice)
-
-    def _getcolslice(self, myslice, j):
-        """Returns a view of the elements [myslice.start:myslice.stop, j].
-        """
-        start, stop, stride = myslice.indices(self.shape[0])
-        return _cs_matrix._get_slice(self, j, start, stop, stride, (stop - start, 1))
-
-
-
     def __setitem__(self, key, val):
         if isinstance(key, tuple):
             row = key[0]

Modified: trunk/scipy/sparse/csr.py
===================================================================
--- trunk/scipy/sparse/csr.py	2007-12-26 00:03:49 UTC (rev 3720)
+++ trunk/scipy/sparse/csr.py	2007-12-26 01:50:00 UTC (rev 3721)
@@ -14,7 +14,7 @@
 from base import spmatrix,isspmatrix
 from sparsetools import csr_tocsc
 from sputils import upcast, to_native, isdense, isshape, getdtype, \
-        isscalarlike
+        isscalarlike, isintlike
 
 from compressed import _cs_matrix,resize1d
 
@@ -87,56 +87,7 @@
         M,N = self.shape
         return csc_matrix((self.data,self.indices,self.indptr),(N,M),copy=copy)
 
-    def __getitem__(self, key):
-        #TODO unify these in _cs_matrix
-        if isinstance(key, tuple):
-            row = key[0]
-            col = key[1]
-            
-            if isinstance(row, slice):
-                # Returns a new matrix!
-                return self.get_submatrix( row, col )
-            elif isinstance(col, slice):
-                return self._getslice(row, col)
-            
-            M, N = self.shape
-            if (row < 0):
-                row = M + row
-            if (col < 0):
-                col = N + col
-            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)
-
-        elif isintlike(key):
-            return self[key, :]
-        else:
-            raise IndexError, "invalid index"
-
-    def _getslice(self, i, myslice):
-        return self._getrowslice(i, myslice)
-
-    def _getrowslice(self, i, myslice):
-        """Returns a view of the elements [i, myslice.start:myslice.stop].
-        """
-        start, stop, stride = myslice.indices(self.shape[1])
-        return _cs_matrix._get_slice(self, i, start, stop, stride, (1, stop-start))
-
     def __setitem__(self, key, val):
         if isinstance(key, tuple):
             row = key[0]
@@ -235,15 +186,6 @@
             #TODO make this more efficient
             return self.tocoo(copy=False).tobsr(blocksize=blocksize)
     
-#    def tobsc(self,blocksize=None):
-#        if blocksize in [None, (1,1)]:
-#            from bsc import bsc_matrix
-#            csc = self.tocsc()
-#            arg1 = (csc.data.reshape(-1,1,1),csc.indices,csc.indptr)  
-#            return bsc_matrix( arg1, shape=self.shape )
-#        else:
-#            #TODO make this more efficient
-#            return self.tocoo(copy=False).tobsc(blocksize=blocksize)
     
     def get_submatrix( self, slice0, slice1 ):
         """Return a submatrix of this matrix (new matrix is created).
@@ -251,6 +193,7 @@
         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:]




More information about the Scipy-svn mailing list