[Scipy-svn] r4854 - in trunk/scipy/sparse: . benchmarks

scipy-svn at scipy.org scipy-svn at scipy.org
Sun Oct 26 23:08:09 EDT 2008


Author: wnbell
Date: 2008-10-26 22:08:05 -0500 (Sun, 26 Oct 2008)
New Revision: 4854

Modified:
   trunk/scipy/sparse/base.py
   trunk/scipy/sparse/benchmarks/bench_sparse.py
   trunk/scipy/sparse/bsr.py
   trunk/scipy/sparse/compressed.py
   trunk/scipy/sparse/coo.py
   trunk/scipy/sparse/dia.py
   trunk/scipy/sparse/dok.py
Log:
cleaned up dok_matrix imports
use native matrix * vector product in dok_matrix
renamed _mul_densematrix to _mul_multivector


Modified: trunk/scipy/sparse/base.py
===================================================================
--- trunk/scipy/sparse/base.py	2008-10-27 02:39:52 UTC (rev 4853)
+++ trunk/scipy/sparse/base.py	2008-10-27 03:08:05 UTC (rev 4854)
@@ -272,8 +272,8 @@
 
         self._mul_scalar()
         self._mul_vector()
+        self._mul_multivector()
         self._mul_sparse_matrix()
-        self._mul_dense_matrix()
         """
 
         M,N = self.shape
@@ -310,12 +310,12 @@
 
         elif len(other.shape) == 2:
             ##
-            # dense 2D array or matrix
+            # dense 2D array or matrix ("multivector")
 
             if other.shape[0] != self.shape[1]:
                 raise ValueError('dimension mismatch')
 
-            result = self._mul_dense_matrix(np.asarray(other))
+            result = self._mul_multivector(np.asarray(other))
 
             if isinstance(other, np.matrix):
                 result = np.asmatrix(result)
@@ -331,8 +331,8 @@
     def _mul_vector(self, other):
         return self.tocsr()._mul_vector(other)
 
-    def _mul_dense_matrix(self, other):
-        return self.tocsr()._mul_dense_matrix(other)
+    def _mul_multivector(self, other):
+        return self.tocsr()._mul_multivector(other)
 
     def _mul_sparse_matrix(self, other):
         return self.tocsr()._mul_sparse_matrix(other)

Modified: trunk/scipy/sparse/benchmarks/bench_sparse.py
===================================================================
--- trunk/scipy/sparse/benchmarks/bench_sparse.py	2008-10-27 02:39:52 UTC (rev 4853)
+++ trunk/scipy/sparse/benchmarks/bench_sparse.py	2008-10-27 03:08:05 UTC (rev 4854)
@@ -130,6 +130,8 @@
         matrices = []
         matrices.append(('Identity',   sparse.identity(10**4,format='dia')))
         matrices.append(('Identity',   sparse.identity(10**4,format='csr')))
+        matrices.append(('Poisson5pt', poisson2d(300,format='lil')))
+        matrices.append(('Poisson5pt', poisson2d(300,format='dok')))
         matrices.append(('Poisson5pt', poisson2d(300,format='dia')))
         matrices.append(('Poisson5pt', poisson2d(300,format='coo')))
         matrices.append(('Poisson5pt', poisson2d(300,format='csr')))

Modified: trunk/scipy/sparse/bsr.py
===================================================================
--- trunk/scipy/sparse/bsr.py	2008-10-27 02:39:52 UTC (rev 4853)
+++ trunk/scipy/sparse/bsr.py	2008-10-27 03:08:05 UTC (rev 4854)
@@ -298,7 +298,7 @@
 
         return result
 
-    def _mul_dense_matrix(self,other):
+    def _mul_multivector(self,other):
         R,C = self.blocksize
         M,N = self.shape
         n_vecs = other.shape[1] #number of column vectors

Modified: trunk/scipy/sparse/compressed.py
===================================================================
--- trunk/scipy/sparse/compressed.py	2008-10-27 02:39:52 UTC (rev 4853)
+++ trunk/scipy/sparse/compressed.py	2008-10-27 03:08:05 UTC (rev 4854)
@@ -266,7 +266,7 @@
         return result
 
 
-    def _mul_dense_matrix(self,other):
+    def _mul_multivector(self, other):
         M,N = self.shape
         n_vecs = other.shape[1] #number of column vectors
 

Modified: trunk/scipy/sparse/coo.py
===================================================================
--- trunk/scipy/sparse/coo.py	2008-10-27 02:39:52 UTC (rev 4853)
+++ trunk/scipy/sparse/coo.py	2008-10-27 03:08:05 UTC (rev 4854)
@@ -364,7 +364,7 @@
         coo_matvec(self.nnz, self.row, self.col, self.data, other, result)
         return result
 
-    def _mul_dense_matrix(self, other):
+    def _mul_multivector(self, other):
         return np.hstack( [ self._mul_vector(col).reshape(-1,1) for col in other.T ] )
 
 from sputils import _isinstance

Modified: trunk/scipy/sparse/dia.py
===================================================================
--- trunk/scipy/sparse/dia.py	2008-10-27 02:39:52 UTC (rev 4853)
+++ trunk/scipy/sparse/dia.py	2008-10-27 03:08:05 UTC (rev 4854)
@@ -152,7 +152,7 @@
 
         return y
 
-    def _mul_dense_matrix(self, other):
+    def _mul_multimatrix(self, other):
         return np.hstack( [ self._mul_vector(col).reshape(-1,1) for col in other.T ] )
 
     def todia(self,copy=False):

Modified: trunk/scipy/sparse/dok.py
===================================================================
--- trunk/scipy/sparse/dok.py	2008-10-27 02:39:52 UTC (rev 4853)
+++ trunk/scipy/sparse/dok.py	2008-10-27 03:08:05 UTC (rev 4854)
@@ -7,10 +7,10 @@
 import operator
 from itertools import izip
 
-from numpy import asarray, intc, isscalar
+import numpy as np
 
-from base import spmatrix,isspmatrix
-from sputils import isdense, getdtype, isshape, isintlike, isscalarlike
+from base import spmatrix, isspmatrix
+from sputils import isdense, getdtype, isshape, isintlike, isscalarlike, upcast
 
 class dok_matrix(spmatrix, dict):
     """Dictionary Of Keys based sparse matrix.
@@ -64,7 +64,7 @@
             self.dtype = arg1.dtype
         else: # Dense ctor
             try:
-                arg1 = asarray(arg1)
+                arg1 = np.asarray(arg1)
             except:
                 raise TypeError('invalid input format')
 
@@ -213,7 +213,7 @@
             if i < 0 or i >= self.shape[0] or j < 0 or j >= self.shape[1]:
                 raise IndexError, "index out of bounds"
 
-            if isscalar(value):
+            if np.isscalar(value):
                 if value==0:
                     del self[(i,j)]
                 else:
@@ -243,7 +243,7 @@
                     else:
                         raise NotImplementedError, "setting a 2-d slice of" \
                                 " a dok_matrix is not yet supported"
-                elif isscalar(value):
+                elif np.isscalar(value):
                     for element in seq:
                         self[element, j] = value
                 else:
@@ -282,7 +282,7 @@
                     else:
                         raise NotImplementedError, "setting a 2-d slice of" \
                                 " a dok_matrix is not yet supported"
-                elif isscalar(value):
+                elif np.isscalar(value):
                     for element in seq:
                         self[i, element] = value
                 else:
@@ -363,13 +363,28 @@
         return new
 
     def _mul_scalar(self, other):
-        new = dok_matrix(self.shape, dtype=self.dtype)
         # Multiply this scalar by every element.
+        new = dok_matrix(self.shape, dtype=self.dtype)
         for (key, val) in self.iteritems():
             new[key] = val * other
-        #new.dtype.char = self.dtype.char
         return new
 
+    def _mul_vector(self, other):
+        #matrix * vector
+        result = np.zeros( self.shape[0], dtype=upcast(self.dtype,other.dtype) )
+        for (i,j),v in self.iteritems():
+            result[i] += v * other[j]
+        return result
+    
+    def _mul_multivector(self, other):
+        #matrix * multivector
+        M,N = self.shape
+        n_vecs = other.shape[1] #number of column vectors
+        result = np.zeros( (M,n_vecs), dtype=upcast(self.dtype,other.dtype) )
+        for (i,j),v in self.iteritems():
+            result[i,:] += v * other[j,:]
+        return result
+
     def __imul__(self, other):
         if isscalarlike(other):
             # Multiply this scalar by every element.
@@ -427,7 +442,6 @@
     def copy(self):
         new = dok_matrix(self.shape, dtype=self.dtype)
         new.update(self)
-        new.shape = self.shape
         return new
 
     def take(self, cols_or_rows, columns=1):
@@ -475,51 +489,16 @@
                     newkey = (key[0]-num, key[1])
                     base[newkey] = self[key]
         return base, ext
-
-# TODO update these w/ new multiplication handlers
-#    def matvec(self, other):
-#        if isdense(other):
-#            if other.shape[0] != self.shape[1]:
-#                raise ValueError, "dimensions do not match"
-#            new = [0] * self.shape[0]
-#            for key in self.keys():
-#                new[int(key[0])] += self[key] * other[int(key[1])]
-#            new = array(new)
-#            if isinstance(other, matrix):
-#                new = asmatrix(new)
-#                # Do we need to return the transpose?
-#                if other.shape[1] == 1:
-#                    new = new.T
-#            return new
-#        else:
-#            raise TypeError, "need a dense vector"
-#
-#    def rmatvec(self, other, conjugate=True):
-#        if isdense(other):
-#            if other.shape[-1] != self.shape[0]:
-#                raise ValueError, "dimensions do not match"
-#            new = [0] * self.shape[1]
-#            for key in self.keys():
-#                new[int(key[1])] += other[int(key[0])] * conj(self[key])
-#            new = array(new)
-#            if isinstance(other, matrix):
-#                new = asmatrix(new)
-#                # Do we need to return the transpose?
-#                if other.shape[1] == 1:
-#                    new = new.T
-#            return new
-#        else:
-#            raise TypeError, "need a dense vector"
-
+    
     def tocoo(self):
         """ Return a copy of this matrix in COOrdinate format"""
         from coo import coo_matrix
         if self.nnz == 0:
             return coo_matrix(self.shape, dtype=self.dtype)
         else:
-            data    = asarray(self.values(), dtype=self.dtype)
-            indices = asarray(self.keys(), dtype=intc).T
-            return coo_matrix((data,indices),shape=self.shape,dtype=self.dtype)
+            data    = np.asarray(self.values(), dtype=self.dtype)
+            indices = np.asarray(self.keys(), dtype=np.intc).T
+            return coo_matrix((data,indices), shape=self.shape, dtype=self.dtype)
 
     def todok(self,copy=False):
         if copy:




More information about the Scipy-svn mailing list