[Scipy-svn] r4544 - in trunk/scipy/sparse: . tests
scipy-svn at scipy.org
scipy-svn at scipy.org
Tue Jul 15 08:22:41 EDT 2008
Author: wnbell
Date: 2008-07-15 07:22:24 -0500 (Tue, 15 Jul 2008)
New Revision: 4544
Added:
trunk/scipy/sparse/extract.py
trunk/scipy/sparse/tests/test_extract.py
Modified:
trunk/scipy/sparse/__init__.py
trunk/scipy/sparse/base.py
trunk/scipy/sparse/construct.py
trunk/scipy/sparse/tests/test_base.py
trunk/scipy/sparse/tests/test_construct.py
Log:
added tril and triu to scipy.sparse
Modified: trunk/scipy/sparse/__init__.py
===================================================================
--- trunk/scipy/sparse/__init__.py 2008-07-14 21:33:03 UTC (rev 4543)
+++ trunk/scipy/sparse/__init__.py 2008-07-15 12:22:24 UTC (rev 4544)
@@ -12,6 +12,8 @@
from bsr import *
from construct import *
+from extract import *
+
#from spfuncs import *
__all__ = filter(lambda s:not s.startswith('_'),dir())
Modified: trunk/scipy/sparse/base.py
===================================================================
--- trunk/scipy/sparse/base.py 2008-07-14 21:33:03 UTC (rev 4543)
+++ trunk/scipy/sparse/base.py 2008-07-15 12:22:24 UTC (rev 4544)
@@ -485,6 +485,9 @@
# else:
# return other.matmat(self.transpose())
+ #def __array__(self):
+ # return self.toarray()
+
def todense(self):
return asmatrix(self.toarray())
Modified: trunk/scipy/sparse/construct.py
===================================================================
--- trunk/scipy/sparse/construct.py 2008-07-14 21:33:03 UTC (rev 4543)
+++ trunk/scipy/sparse/construct.py 2008-07-15 12:22:24 UTC (rev 4544)
@@ -7,11 +7,10 @@
'hstack', 'vstack', 'bmat' ]
-from itertools import izip
from warnings import warn
import numpy
-from numpy import ones, clip, array, arange, intc, asarray, rank, zeros, \
+from numpy import ones, arange, intc, asarray, rank, zeros, \
cumsum, concatenate, empty
from sputils import upcast
@@ -49,7 +48,6 @@
Example
-------
-
>>> data = array([[1,2,3,4],[1,2,3,4],[1,2,3,4]])
>>> diags = array([0,-1,2])
>>> spdiags(data, diags, 4, 4).todense()
@@ -62,7 +60,32 @@
return dia_matrix((data, diags), shape=(m,n)).asformat(format)
def identity(n, dtype='d', format=None):
- """identity(n) returns a sparse (n x n) identity matrix"""
+ """Identity matrix in sparse format
+
+ Returns an identity matrix with shape (n,n) using a given
+ sparse format and dtype.
+
+ Parameters
+ ----------
+ n : integer
+ Shape of the identity matrix.
+ dtype :
+ Data type of the matrix
+ format : string
+ Sparse format of the result, e.g. format="csr", etc.
+
+ Examples
+ --------
+ >>> identity(3).todense()
+ matrix([[ 1., 0., 0.],
+ [ 0., 1., 0.],
+ [ 0., 0., 1.]])
+ >>> identity(3, dtype='int8', format='dia')
+ <3x3 sparse matrix of type '<type 'numpy.int8'>'
+ with 3 stored elements (1 diagonals) in DIAgonal format>
+
+ """
+
if format in ['csr','csc']:
indptr = arange(n+1, dtype=intc)
indices = arange(n, dtype=intc)
@@ -74,6 +97,10 @@
col = arange(n, dtype=intc)
data = ones(n, dtype=dtype)
return coo_matrix((data,(row,col)),(n,n))
+ elif format == 'dia':
+ data = ones(n, dtype=dtype)
+ diags = [0]
+ return dia_matrix( (data,diags), shape=(n,n) )
else:
return identity( n, dtype=dtype, format='csr').asformat(format)
@@ -103,7 +130,6 @@
Examples
--------
-
>>> A = csr_matrix(array([[0,2],[5,0]]))
>>> B = csr_matrix(array([[1,2],[3,4]]))
>>> kron(A,B).todense()
@@ -200,7 +226,7 @@
if B.shape[0] != B.shape[1]:
raise ValueError('B is not square')
- dtype = upcast(A.dtype,B.dtype)
+ dtype = upcast(A.dtype, B.dtype)
L = kron(identity(B.shape[0],dtype=dtype), A, format=format)
R = kron(B, identity(A.shape[0],dtype=dtype), format=format)
@@ -213,7 +239,6 @@
Parameters
----------
-
blocks
sequence of sparse matrices with compatible shapes
format : string
@@ -223,7 +248,6 @@
Example
-------
-
>>> from scipy.sparse import coo_matrix, vstack
>>> A = coo_matrix([[1,2],[3,4]])
>>> B = coo_matrix([[5],[6]])
@@ -240,7 +264,6 @@
Parameters
----------
-
blocks
sequence of sparse matrices with compatible shapes
format : string
@@ -250,7 +273,6 @@
Example
-------
-
>>> from scipy.sparse import coo_matrix, vstack
>>> A = coo_matrix([[1,2],[3,4]])
>>> B = coo_matrix([[5,6]])
@@ -268,7 +290,6 @@
Parameters
----------
-
blocks
grid of sparse matrices with compatible shapes
an entry of None implies an all-zero matrix
@@ -278,7 +299,6 @@
Example
-------
-
>>> from scipy.sparse import coo_matrix, bmat
>>> A = coo_matrix([[1,2],[3,4]])
>>> B = coo_matrix([[5],[6]])
@@ -398,8 +418,9 @@
DeprecationWarning)
return eye(r,c,k,dtype=dtype,format='lil')
+from numpy import clip
+from itertools import izip
-
#TODO remove this function
def lil_diags(diags,offsets,(m,n),dtype='d'):
"""Generate a lil_matrix with the given diagonals.
Added: trunk/scipy/sparse/extract.py
===================================================================
--- trunk/scipy/sparse/extract.py 2008-07-14 21:33:03 UTC (rev 4543)
+++ trunk/scipy/sparse/extract.py 2008-07-15 12:22:24 UTC (rev 4544)
@@ -0,0 +1,143 @@
+"""Functions to extract parts of sparse matrices
+"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['tril', 'triu']
+
+
+from coo import coo_matrix
+
+def tril(A, k=0, format=None):
+ """Return the lower triangular portion of a matrix in sparse format
+
+ Returns the elements on or below the k-th diagonal of the matrix A.
+ - k = 0 corresponds to the main diagonal
+ - k > 0 is above the main diagonal
+ - k < 0 is below the main diagonal
+
+ Parameters
+ ----------
+ A : dense or sparse matrix
+ Matrix whose lower trianglar portion is desired.
+ k : integer : optional
+ The top-most diagonal of the lower triangle.
+ format : string
+ Sparse format of the result, e.g. format="csr", etc.
+
+ Returns
+ -------
+ L : sparse matrix
+ Lower triangular portion of A in sparse format.
+
+ See Also
+ --------
+ triu : upper triangle in sparse format
+
+ Examples
+ --------
+ >>> from scipy.sparse import csr_matrix
+ >>> A = csr_matrix( [[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]] )
+ >>> A.todense()
+ matrix([[1, 2, 0, 0, 3],
+ [4, 5, 0, 6, 7],
+ [0, 0, 8, 9, 0]])
+ >>> tril(A).todense()
+ matrix([[1, 0, 0, 0, 0],
+ [4, 5, 0, 0, 0],
+ [0, 0, 8, 0, 0]])
+ >>> tril(A).nnz
+ 4
+ >>> tril(A, k=1).todense()
+ matrix([[1, 2, 0, 0, 0],
+ [4, 5, 0, 0, 0],
+ [0, 0, 8, 9, 0]])
+ >>> tril(A, k=-1).todense()
+ matrix([[0, 0, 0, 0, 0],
+ [4, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0]])
+ >>> tril(A, format='csc')
+ <3x5 sparse matrix of type '<type 'numpy.int32'>'
+ with 4 stored elements in Compressed Sparse Column format>
+
+ """
+
+ # convert to COOrdinate format where things are easy
+ A = coo_matrix(A, copy=False)
+
+ mask = A.row + k >= A.col
+
+ row = A.row[mask]
+ col = A.col[mask]
+ data = A.data[mask]
+
+ return coo_matrix( (data,(row,col)), shape=A.shape ).asformat(format)
+
+
+def triu(A, k=0, format=None):
+ """Return the upper triangular portion of a matrix in sparse format
+
+ Returns the elements on or above the k-th diagonal of the matrix A.
+ - k = 0 corresponds to the main diagonal
+ - k > 0 is above the main diagonal
+ - k < 0 is below the main diagonal
+
+ Parameters
+ ----------
+ A : dense or sparse matrix
+ Matrix whose upper trianglar portion is desired.
+ k : integer : optional
+ The bottom-most diagonal of the upper triangle.
+ format : string
+ Sparse format of the result, e.g. format="csr", etc.
+
+ Returns
+ -------
+ L : sparse matrix
+ Upper triangular portion of A in sparse format.
+
+ See Also
+ --------
+ tril : lower triangle in sparse format
+
+ Examples
+ --------
+ >>> from scipy.sparse import csr_matrix
+ >>> A = csr_matrix( [[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]] )
+ >>> A.todense()
+ matrix([[1, 2, 0, 0, 3],
+ [4, 5, 0, 6, 7],
+ [0, 0, 8, 9, 0]])
+ >>> triu(A).todense()
+ matrix([[1, 2, 0, 0, 3],
+ [0, 5, 0, 6, 7],
+ [0, 0, 8, 9, 0]])
+ >>> triu(A).nnz
+ 8
+ >>> triu(A, k=1).todense()
+ matrix([[0, 2, 0, 0, 3],
+ [0, 0, 0, 6, 7],
+ [0, 0, 0, 9, 0]])
+ >>> triu(A, k=-1).todense()
+ matrix([[1, 2, 0, 0, 3],
+ [4, 5, 0, 6, 7],
+ [0, 0, 8, 9, 0]])
+ >>> triu(A, format='csc')
+ <3x5 sparse matrix of type '<type 'numpy.int32'>'
+ with 8 stored elements in Compressed Sparse Column format>
+
+ """
+
+ # convert to COOrdinate format where things are easy
+ A = coo_matrix(A, copy=False)
+
+ mask = A.row + k <= A.col
+
+ row = A.row[mask]
+ col = A.col[mask]
+ data = A.data[mask]
+
+ return coo_matrix( (data,(row,col)), shape=A.shape ).asformat(format)
+
+
+
Modified: trunk/scipy/sparse/tests/test_base.py
===================================================================
--- trunk/scipy/sparse/tests/test_base.py 2008-07-14 21:33:03 UTC (rev 4543)
+++ trunk/scipy/sparse/tests/test_base.py 2008-07-15 12:22:24 UTC (rev 4544)
@@ -149,6 +149,10 @@
A = [[1,0,0],[2,3,4],[0,5,0],[0,0,0]]
assert_array_equal(self.spmatrix(A).todense(), A)
+ #def test_array(self):
+ # """test array(A) where A is in sparse format"""
+ # assert_equal( array(self.datsp), self.dat )
+
def test_todense(self):
chk = self.datsp.todense()
assert_array_equal(chk,self.dat)
Modified: trunk/scipy/sparse/tests/test_construct.py
===================================================================
--- trunk/scipy/sparse/tests/test_construct.py 2008-07-14 21:33:03 UTC (rev 4543)
+++ trunk/scipy/sparse/tests/test_construct.py 2008-07-15 12:22:24 UTC (rev 4544)
@@ -9,6 +9,8 @@
from scipy.sparse.construct import *
+sparse_formats = ['csr','csc','coo','bsr','dia','lil','dok']
+
#TODO check whether format=XXX is respected
class TestConstructUtils(TestCase):
@@ -61,14 +63,18 @@
def test_identity(self):
- a = identity(3)
- b = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype='d')
- assert_array_equal(a.toarray(), b)
+ assert_equal(identity(1).toarray(), [[1]])
+ assert_equal(identity(2).toarray(), [[1,0],[0,1]])
- a = identity(1)
- b = array([[1]], dtype='d')
- assert_array_equal(a.toarray(), b)
+ I = identity(3, dtype='int8', format='dia')
+ assert_equal( I.dtype, 'int8' )
+ assert_equal( I.format, 'dia' )
+ for fmt in sparse_formats:
+ I = identity( 3, format=fmt )
+ assert_equal( I.format, fmt )
+ assert_equal( I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
+
def test_eye(self):
a = eye(2, 3 )
b = array([[1, 0, 0], [0, 1, 0]], dtype='d')
Added: trunk/scipy/sparse/tests/test_extract.py
===================================================================
--- trunk/scipy/sparse/tests/test_extract.py 2008-07-14 21:33:03 UTC (rev 4543)
+++ trunk/scipy/sparse/tests/test_extract.py 2008-07-15 12:22:24 UTC (rev 4544)
@@ -0,0 +1,42 @@
+"""test sparse matrix construction functions"""
+
+import numpy
+from numpy import array, matrix
+from scipy.testing import *
+
+from scipy.sparse import csr_matrix
+
+import numpy as np
+from scipy.sparse.extract import *
+
+
+class TestExtract(TestCase):
+ def setUp(self):
+ cases = []
+
+ cases.append( csr_matrix( [[1,2]] ) )
+ cases.append( csr_matrix( [[1,0]] ) )
+ cases.append( csr_matrix( [[0,0]] ) )
+ cases.append( csr_matrix( [[1],[2]] ) )
+ cases.append( csr_matrix( [[1],[0]] ) )
+ cases.append( csr_matrix( [[0],[0]] ) )
+ cases.append( csr_matrix( [[1,2],[3,4]] ) )
+ cases.append( csr_matrix( [[0,1],[0,0]] ) )
+ cases.append( csr_matrix( [[0,0],[1,0]] ) )
+ cases.append( csr_matrix( [[0,0],[0,0]] ) )
+ cases.append( csr_matrix( [[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]] ) )
+ cases.append( csr_matrix( [[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]] ).T )
+
+ self.cases = cases
+
+ def test_tril(self):
+ for A in self.cases:
+ B = A.toarray()
+ for k in [-3,-2,-1,0,1,2,3]:
+ assert_equal( tril(A,k=k).toarray(), np.tril(B,k=k))
+
+ def test_triu(self):
+ for A in self.cases:
+ B = A.toarray()
+ for k in [-3,-2,-1,0,1,2,3]:
+ assert_equal( triu(A,k=k).toarray(), np.triu(B,k=k))
More information about the Scipy-svn
mailing list