[Scipy-svn] r3652 - in trunk/scipy/sparse: . tests
scipy-svn at scipy.org
scipy-svn at scipy.org
Fri Dec 14 14:34:51 EST 2007
Author: wnbell
Date: 2007-12-14 13:34:41 -0600 (Fri, 14 Dec 2007)
New Revision: 3652
Modified:
trunk/scipy/sparse/compressed.py
trunk/scipy/sparse/construct.py
trunk/scipy/sparse/coo.py
trunk/scipy/sparse/csc.py
trunk/scipy/sparse/csr.py
trunk/scipy/sparse/dia.py
trunk/scipy/sparse/dok.py
trunk/scipy/sparse/info.py
trunk/scipy/sparse/lil.py
trunk/scipy/sparse/tests/test_base.py
Log:
deprecated dims argument in CSR/CSC/COO constructors
support coo_matrix( sparse ) initialization
Modified: trunk/scipy/sparse/compressed.py
===================================================================
--- trunk/scipy/sparse/compressed.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/compressed.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -3,6 +3,8 @@
__all__ = []
+from warnings import warn
+
import numpy
from numpy import array, matrix, asarray, asmatrix, zeros, rank, intc, \
empty, hstack, isscalar, ndarray, shape, searchsorted
@@ -24,9 +26,13 @@
class _cs_matrix(spmatrix):
"""base matrix class for compressed row and column oriented matrices"""
- def __init__(self, arg1, dims=None, dtype=None, copy=False):
+ def __init__(self, arg1, shape=None, dtype=None, copy=False, dims=None):
spmatrix.__init__(self)
+ if dims is not None:
+ warn("dims is deprecated, use shape instead", DeprecationWarning)
+ shape=dims
+
if isdense(arg1):
# Convert the dense array or matrix arg1 to sparse format
if rank(arg1) == 1:
@@ -58,7 +64,7 @@
# Try interpreting it as (data, ij)
(data, ij) = arg1
assert isinstance(ij, ndarray) and (rank(ij) == 2) \
- and (shape(ij) == (2, len(data)))
+ and (ij.shape == (2, len(data)))
except (AssertionError, TypeError, ValueError, AttributeError):
try:
# Try interpreting it as (data, indices, indptr)
@@ -73,7 +79,7 @@
else:
# (data, ij) format
from coo import coo_matrix
- other = coo_matrix((data, ij), dims=dims )
+ other = coo_matrix((data, ij), shape=shape )
other = self._tothis(other)
self._set_self( other )
@@ -82,8 +88,8 @@
" %s_matrix constructor" % self.format
# Read matrix dimensions given, if any
- if dims is not None:
- self.shape = dims # spmatrix will check for errors
+ if shape is not None:
+ self.shape = shape # spmatrix will check for errors
else:
if self.shape is None:
# shape not already set, try to infer dimensions
@@ -135,11 +141,11 @@
# index arrays should have integer data types
if self.indptr.dtype.kind != 'i':
- warnings.warn("indptr array has non-integer dtype (%s)" \
- % self.indptr.dtype.name )
+ warn("indptr array has non-integer dtype (%s)" \
+ % self.indptr.dtype.name )
if self.indices.dtype.kind != 'i':
- warnings.warn("indices array has non-integer dtype (%s)" \
- % self.indices.dtype.name )
+ warn("indices array has non-integer dtype (%s)" \
+ % self.indices.dtype.name )
# only support 32-bit ints for now
self.indptr = self.indptr.astype('intc')
@@ -381,7 +387,7 @@
def copy(self):
return self._with_data(self.data.copy(),copy=True)
- def _get_slice(self, i, start, stop, stride, dims):
+ def _get_slice(self, i, start, stop, stride, shape):
"""Returns a view of the elements [i, myslice.start:myslice.stop].
"""
if stride != 1:
@@ -398,7 +404,7 @@
index = self.indices[indices] - start
data = self.data[indices]
indptr = numpy.array([0, len(indices)])
- return self.__class__((data, index, indptr), dims=dims, \
+ return self.__class__((data, index, indptr), shape=shape, \
dtype=self.dtype)
@@ -454,9 +460,9 @@
def ensure_sorted_indices(self, inplace=False):
"""Return a copy of this matrix where the column indices are sorted
"""
- warnings.warn('ensure_sorted_indices is deprecated, ' \
- 'use sorted_indices() or sort_indices() instead', \
- DeprecationWarning)
+ warn('ensure_sorted_indices is deprecated, ' \
+ 'use sorted_indices() or sort_indices() instead', \
+ DeprecationWarning)
if inplace:
self.sort_indices()
@@ -531,10 +537,10 @@
"""
if copy:
return self.__class__((data,self.indices.copy(),self.indptr.copy()), \
- dims=self.shape,dtype=data.dtype)
+ shape=self.shape,dtype=data.dtype)
else:
return self.__class__((data,self.indices,self.indptr), \
- dims=self.shape,dtype=data.dtype)
+ shape=self.shape,dtype=data.dtype)
def _binopt(self, other, op, in_shape=None, out_shape=None):
"""apply the binary operation fn to two sparse matrices"""
@@ -551,6 +557,6 @@
indptr, ind, data = fn(in_shape[0], in_shape[1], \
self.indptr, self.indices, self.data,
other.indptr, other.indices, other.data)
- return self.__class__((data, ind, indptr), dims=out_shape)
+ return self.__class__((data, ind, indptr), shape=out_shape)
Modified: trunk/scipy/sparse/construct.py
===================================================================
--- trunk/scipy/sparse/construct.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/construct.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -5,7 +5,7 @@
__all__ = [ 'spdiags','speye','spidentity','spkron', 'lil_eye', 'lil_diags' ]
import itertools
-import warnings
+from warnings import warn
import numpy
from numpy import ones, clip, array, arange, intc
@@ -136,7 +136,7 @@
data = data.reshape(-1,B.nnz) * B.data
data = data.reshape(-1)
- return coo_matrix((data,(row,col)), dims=output_shape).asformat(format)
+ return coo_matrix((data,(row,col)), shape=output_shape).asformat(format)
@@ -155,7 +155,7 @@
Data-type of the output array.
"""
- warnings.warn("lil_eye is deprecated. use speye(... , format='lil') instead", \
+ warn("lil_eye is deprecated. use speye(... , format='lil') instead", \
DeprecationWarning)
return speye(r,c,k,dtype=dtype,format='lil')
Modified: trunk/scipy/sparse/coo.py
===================================================================
--- trunk/scipy/sparse/coo.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/coo.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -3,11 +3,12 @@
__all__ = ['coo_matrix', 'isspmatrix_coo']
from itertools import izip
+from warnings import warn
from numpy import array, asarray, empty, intc
from sparsetools import cootocsr, cootocsc
-from base import spmatrix
+from base import spmatrix, isspmatrix
from sputils import upcast, to_native, isshape, getdtype
class coo_matrix(spmatrix):
@@ -16,10 +17,12 @@
COO matrices are created either as:
A = coo_matrix( (m, n), [dtype])
for a zero matrix, or as:
+ A = coo_matrix(S)
+ where S is a sparse matrix, or as:
A = coo_matrix(M)
where M is a dense matrix or rank 2 ndarray, or as:
- A = coo_matrix((obj, ij), [dims])
- where the dimensions are optional. If supplied, we set (M, N) = dims.
+ A = coo_matrix((obj, ij), [shape])
+ where the dimensions are optional. If supplied, we set (M, N) = shape.
If not supplied, we infer these from the index arrays:
ij[0][:] and ij[1][:]
@@ -37,8 +40,13 @@
of finite element matrices and the like.
"""
- def __init__(self, arg1, dims=None, dtype=None):
+ def __init__(self, arg1, shape=None, dtype=None, copy=False, dims=None):
spmatrix.__init__(self)
+
+ if dims is not None:
+ warn("dims is deprecated, use shape instead", DeprecationWarning)
+ shape=dims
+
if isinstance(arg1, tuple):
if isshape(arg1):
M, N = arg1
@@ -58,44 +66,54 @@
except TypeError:
raise TypeError, "invalid input format"
- self.row = asarray(ij[0])
- self.col = asarray(ij[1])
- self.data = asarray(obj)
+ self.row = array(ij[0],copy=copy)
+ self.col = array(ij[1],copy=copy)
+ self.data = array(obj,copy=copy)
- if dims is None:
+ if shape is None:
if len(self.row) == 0 or len(self.col) == 0:
raise ValueError, "cannot infer dimensions from zero sized index arrays"
M = self.row.max() + 1
N = self.col.max() + 1
self.shape = (M, N)
else:
- # Use 2 steps to ensure dims has length 2.
- M, N = dims
+ # Use 2 steps to ensure shape has length 2.
+ M, N = shape
self.shape = (M, N)
elif arg1 is None:
# Initialize an empty matrix.
- if not isinstance(dims, tuple) or not isintlike(dims[0]):
+ if not isinstance(shape, tuple) or not isintlike(shape[0]):
raise TypeError, "dimensions not understood"
- warnings.warn('coo_matrix(None, dims=(M,N)) is deprecated, ' \
- 'use coo_matrix( (M,N) ) instead', \
- DeprecationWarning)
- self.shape = dims
+ warn('coo_matrix(None, shape=(M,N)) is deprecated, ' \
+ 'use coo_matrix( (M,N) ) instead', DeprecationWarning)
+ self.shape = shape
self.data = array([],getdtype(dtype, default=float))
self.row = array([],dtype=intc)
self.col = array([],dtype=intc)
else:
- #dense argument
- try:
- M = asarray(arg1)
- except:
- raise TypeError, "invalid input format"
+ if isspmatrix(arg1):
+ if isspmatrix_coo and copy:
+ A = arg1.copy()
+ else:
+ A = arg1.tocoo()
- if len(M.shape) != 2:
- raise TypeError, "expected rank 2 array or matrix"
- self.shape = M.shape
- self.row,self.col = (M != 0).nonzero()
- self.data = M[self.row,self.col]
+ self.row = A.row
+ self.col = A.col
+ self.data = A.data
+ self.shape = A.shape
+ else:
+ #dense argument
+ try:
+ M = asarray(arg1)
+ except:
+ raise TypeError, "invalid input format"
+
+ if len(M.shape) != 2:
+ raise TypeError, "expected rank 2 array or matrix"
+ self.shape = M.shape
+ self.row,self.col = (M != 0).nonzero()
+ self.data = M[self.row,self.col]
self._check()
@@ -116,11 +134,11 @@
# index arrays should have integer data types
if self.row.dtype.kind != 'i':
- warnings.warn("row index array has non-integer dtype (%s) " \
- % self.row.dtype.name )
+ warn("row index array has non-integer dtype (%s) " \
+ % self.row.dtype.name )
if self.col.dtype.kind != 'i':
- warnings.warn("col index array has non-integer dtype (%s) " \
- % self.col.dtype.name )
+ warn("col index array has non-integer dtype (%s) " \
+ % self.col.dtype.name )
# only support 32-bit ints for now
self.row = self.row.astype('intc')
@@ -147,6 +165,10 @@
def getdata(self, num):
return self.data[num]
+
+ def transpose(self,copy=False):
+ M,N = self.shape
+ return coo_matrix((self.data,(self.col,self.row)),(N,M),copy=copy)
def tocsc(self):
from csc import csc_matrix
Modified: trunk/scipy/sparse/csc.py
===================================================================
--- trunk/scipy/sparse/csc.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/csc.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -3,6 +3,7 @@
__all__ = ['csc_matrix', 'isspmatrix_csc']
+from warnings import warn
import numpy
from numpy import array, matrix, asarray, asmatrix, zeros, rank, intc, \
@@ -39,8 +40,8 @@
def __getattr__(self, attr):
if attr == 'rowind':
- warnings.warn("rowind attribute no longer in use. Use .indices instead",
- DeprecationWarning)
+ warn("rowind attribute no longer in use. Use .indices instead",
+ DeprecationWarning)
return self.indices
else:
return _cs_matrix.__getattr__(self, attr)
@@ -177,7 +178,7 @@
aux = _cs_matrix._get_submatrix( self, self.shape[1], self.shape[0],
slice1, slice0 )
nr, nc = aux[3:]
- return self.__class__( aux[:3], dims = (nc, nr) )
+ 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
@@ -186,6 +187,9 @@
"""
return (x[1],x[0])
+ def _otherformat(self):
+ return "csr"
+
def _toother(self):
return self.tocsr()
Modified: trunk/scipy/sparse/csr.py
===================================================================
--- trunk/scipy/sparse/csr.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/csr.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -4,6 +4,8 @@
__all__ = ['csr_matrix', 'isspmatrix_csr']
+from warnings import warn
+
import numpy
from numpy import array, matrix, asarray, asmatrix, zeros, rank, intc, \
empty, hstack, isscalar, ndarray, shape, searchsorted
@@ -28,18 +30,18 @@
to construct a container, where (M, N) are dimensions and
dtype is optional, defaulting to dtype='d'.
- - csr_matrix((data, ij), [dims=(M, N)])
+ - csr_matrix((data, ij), [shape=(M, N)])
where data, ij satisfy:
a[ij[0, k], ij[1, k]] = data[k]
- - csr_matrix((data, col, ptr), [dims=(M, N)])
+ - csr_matrix((data, col, ptr), [shape=(M, N)])
standard CSR representation
"""
def __getattr__(self, attr):
if attr == 'colind':
- warnings.warn("colind attribute no longer in use. Use .indices instead",
- DeprecationWarning)
+ warn("colind attribute no longer in use. Use .indices instead",
+ DeprecationWarning)
return self.indices
else:
return _cs_matrix.__getattr__(self, attr)
@@ -186,7 +188,7 @@
aux = _cs_matrix._get_submatrix( self, self.shape[0], self.shape[1],
slice0, slice1 )
nr, nc = aux[3:]
- return self.__class__( aux[:3], dims = (nr, nc) )
+ 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
@@ -195,6 +197,9 @@
"""
return (x[0],x[1])
+ def _otherformat(self):
+ return "csc"
+
def _toother(self):
return self.tocsc()
Modified: trunk/scipy/sparse/dia.py
===================================================================
--- trunk/scipy/sparse/dia.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/dia.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -180,7 +180,7 @@
row,col,data = row.reshape(-1),col.reshape(-1),data.reshape(-1)
from coo import coo_matrix
- return coo_matrix((data,(row,col)),dims=self.shape)
+ return coo_matrix((data,(row,col)),shape=self.shape)
Modified: trunk/scipy/sparse/dok.py
===================================================================
--- trunk/scipy/sparse/dok.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/dok.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -20,6 +20,8 @@
This can be a tuple of dimensions (M, N) or a (dense) array
to copy.
"""
+ #TODO deprecate argument A in favor of arg1 style
+
dict.__init__(self)
spmatrix.__init__(self,shape)
self.dtype = getdtype(dtype, A, default=float)
@@ -536,7 +538,7 @@
else:
data = asarray(self.values(), dtype=self.dtype)
indices = asarray(self.keys(), dtype=intc).T
- return coo_matrix((data,indices),dims=self.shape,dtype=self.dtype)
+ return coo_matrix((data,indices),shape=self.shape,dtype=self.dtype)
def todok(self,copy=False):
if copy:
Modified: trunk/scipy/sparse/info.py
===================================================================
--- trunk/scipy/sparse/info.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/info.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -59,7 +59,7 @@
>>> I = array([0,3,1,0])
>>> J = array([0,3,1,2])
>>> V = array([4,5,7,9])
- >>> A = sparse.coo_matrix((V,(I,J)),dims=(4,4))
+ >>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
Notice that the indices do not need to be sorted.
@@ -67,7 +67,7 @@
>>> I = array([0,0,1,3,1,0,0])
>>> J = array([0,2,1,3,1,0,0])
>>> V = array([1,1,1,1,1,1,1])
- >>> B = sparse.coo_matrix((V,(I,J)),dims=(4,4)).tocsr()
+ >>> B = sparse.coo_matrix((V,(I,J)),shape=(4,4)).tocsr()
This is useful for constructing finite-element stiffness and
mass matrices.
Modified: trunk/scipy/sparse/lil.py
===================================================================
--- trunk/scipy/sparse/lil.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/lil.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -376,11 +376,7 @@
return d
def transpose(self):
- """ Return the transpose as a csc_matrix.
- """
- # Overriding the spmatrix.transpose method here prevents an unnecessary
- # csr -> csc conversion
- return self.tocsr().transpose()
+ return self.tocsr().transpose().tolil()
def tolil(self, copy=False):
if copy:
@@ -408,7 +404,7 @@
data = asarray(data,dtype=self.dtype)
from csr import csr_matrix
- return csr_matrix((data, indices, indptr), dims=self.shape)
+ return csr_matrix((data, indices, indptr), shape=self.shape)
def tocsc(self):
""" Return Compressed Sparse Column format arrays for this matrix.
Modified: trunk/scipy/sparse/tests/test_base.py
===================================================================
--- trunk/scipy/sparse/tests/test_base.py 2007-12-14 18:30:20 UTC (rev 3651)
+++ trunk/scipy/sparse/tests/test_base.py 2007-12-14 19:34:41 UTC (rev 3652)
@@ -26,6 +26,9 @@
from scipy.linsolve import splu
restore_path()
+
+#TODO test spmatrix(DENSE) and spmatrix(SPARSE) for all combos
+#TODO check that invalid shape in constructor raises exception
class _TestCommon:
"""test common functionality shared by all sparse formats"""
@@ -732,7 +735,7 @@
## col = array( [1, 2, 1, 0, 0, 2], dtype='int64' )
## ptr = array( [0, 2, 4, 6], dtype='int64' )
##
-## a = csr_matrix( (data, col, ptr), dims = (3,3) )
+## a = csr_matrix( (data, col, ptr), shape = (3,3) )
##
## b = matrix([[0,1,2],
## [4,3,0],
@@ -766,7 +769,7 @@
data = arange( 5 )
indices = array( [7, 2, 1, 5, 4] )
indptr = array( [0, 3, 5] )
- asp = csr_matrix( (data, indices, indptr), dims = (2,10) )
+ asp = csr_matrix( (data, indices, indptr), shape=(2,10) )
bsp = asp.copy()
asp.sort_indices( )
assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
@@ -838,7 +841,7 @@
data = arange( 5 )
row = array( [7, 2, 1, 5, 4] )
ptr = [0, 3, 5]
- asp = csc_matrix( (data, row, ptr), dims = (10,2) )
+ asp = csc_matrix( (data, row, ptr), shape=(10,2) )
bsp = asp.copy()
asp.sort_indices()
assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
More information about the Scipy-svn
mailing list