[Scipy-svn] r3860 - in trunk/scipy: sandbox/multigrid sparse sparse/tests

scipy-svn@scip... scipy-svn@scip...
Thu Jan 24 16:11:49 CST 2008


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):



More information about the Scipy-svn mailing list