Changeset 8127


Ignore:
Timestamp:
Mar 7, 2011, 5:32:19 PM (14 years ago)
Author:
steve
Message:

Moved kinematic code into a new directory called "operators"

Location:
trunk/anuga_core/source/anuga
Files:
5 added
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/anuga_core/source/anuga/utilities/sparse.py

    r8124 r8127  
    1 """Proof of concept sparse matrix code
     1"""
     2Proof of concept sparse matrix code
    23"""
    34
     
    1213        Usage:
    1314
    14         Sparse(A)     #Creates sparse matrix from dense matrix A 
     15        Sparse(A)     #Creates sparse matrix from dense matrix A
    1516        Sparse(M, N)  #Creates empty MxN sparse matrix
    1617        """
    1718
    1819        self.Data = {}
    19            
     20
    2021        if len(args) == 1:
    2122            try:
     
    2526
    2627            assert len(A.shape) == 2, 'Input must be a 2d matrix'
    27            
     28
    2829            self.M, self.N = A.shape
    2930            for i in range(self.M):
     
    3132                    if A[i, j] != 0.0:
    3233                        self.Data[i, j] = A[i, j]
    33                
    34            
     34
     35
    3536        elif len(args) == 2:
    3637            self.M = args[0]
     
    3839        else:
    3940            raise Exception('Invalid construction')
    40            
    41         self.shape = (self.M, self.N) 
     41
     42        self.shape = (self.M, self.N)
    4243
    4344
     
    5253    def nonzeros(self):
    5354        """Return number of nonzeros of A
    54         """       
     55        """
    5556        return len(self)
    56    
     57
    5758    def __setitem__(self, key, x):
    5859
     
    6061        # removing these asserts will not speed things up
    6162        assert 0 <= i < self.M
    62         assert 0 <= j < self.N       
     63        assert 0 <= j < self.N
    6364
    6465        if x != 0:
    6566            self.Data[key] = float(x)
    6667        else:
    67             if self.Data.has_key( key ):           
     68            if self.Data.has_key( key ):
    6869                del self.Data[key]
    6970
    7071    def __getitem__(self, key):
    71        
     72
    7273        i,j = key
    7374        # removing these asserts will not speed things up
    7475        assert 0 <= i < self.M
    75         assert 0 <= j < self.N               
     76        assert 0 <= j < self.N
    7677
    7778        if self.Data.has_key( key ):
     
    9495    def todense(self):
    9596        D = num.zeros( (self.M, self.N), num.float)
    96        
     97
    9798        for i in range(self.M):
    9899            for j in range(self.N):
    99                 if self.Data.has_key( (i,j) ):               
     100                if self.Data.has_key( (i,j) ):
    100101                    D[i, j] = self.Data[ (i,j) ]
    101102        return D
    102103
    103104
    104    
     105
    105106    def __mul__(self, other):
    106107        """Multiply this matrix onto 'other' which can either be
     
    113114            msg = 'FIXME: Only numeric types implemented so far'
    114115            raise Exception(msg)
    115            
     116
    116117
    117118        # Assume numeric types from now on
    118        
     119
    119120        if len(B.shape) == 0:
    120121            # Scalar - use __rmul__ method
    121122            R = B*self
    122            
     123
    123124        elif len(B.shape) == 1:
    124125            # Vector
     
    128129
    129130            R = num.zeros(self.M, num.float) #Result
    130            
     131
    131132            # Multiply nonzero elements
    132133            for key in self.Data.keys():
     
    135136                R[i] += self.Data[key]*B[j]
    136137        elif len(B.shape) == 2:
    137        
    138            
     138
     139
    139140            R = num.zeros((self.M, B.shape[1]), num.float) #Result matrix
    140141
     
    142143            for col in range(R.shape[1]):
    143144                # For each column
    144                
     145
    145146                for key in self.Data.keys():
    146147                    i, j = key
    147148
    148149                    R[i, col] += self.Data[key]*B[j, col]
    149            
    150            
     150
     151
    151152        else:
    152153            raise ValueError('Dimension too high: d=%d' %len(B.shape))
    153154
    154155        return R
    155    
     156
    156157
    157158    def __add__(self, other):
    158         """Add this matrix onto 'other' 
     159        """Add this matrix onto 'other'
    159160        """
    160161
     
    220221class Sparse_CSR:
    221222
    222     def __init__(self, A):
     223    def __init__(self, A=None, data=None, Colind=None, rowptr=None, m=None, n=None):
    223224        """Create sparse matrix in csr format.
    224225
     
    239240                 Regard it as a pointer into the colind array, for the ith row.
    240241
    241                  
     242
    242243        """
    243244
     
    264265                row_ptr[row] = nnz
    265266            #row_ptr[-1] = nnz
    266        
     267
    267268            self.data    = data
    268269            self.colind  = colind
     
    270271            self.M       = A.M
    271272            self.N       = A.N
    272         else:
    273             raise ValueError("Sparse_CSR(A) expects A == Sparse Matrix")
    274            
     273        elif isinstance(data,num.ndarray) and isinstance(Colind,num.ndarray) and isinstance(rowptr,num.ndarray) and isinstance(m,int) and isinstance(n,int):
     274            msg = "Sparse_CSR: data is array of wrong dimensions"
     275            #assert len(data.shape) == 1, msg
     276            nnz = data.size
     277
     278            msg = "Sparse_CSR: Colind is array of wrong dimensions"
     279            assert Colind.shape == (nnz,), msg
     280
     281            msg = "Sparse_CSR: rowptr is array of wrong dimensions"
     282            assert rowptr.shape == (m+1,), msg
     283
     284            self.data = data
     285            self.colind = Colind
     286            self.row_ptr = rowptr
     287            self.M = m
     288            self.N = n
     289        else:
     290            raise ValueError('Sparse_CSR(A) expects A == Sparse Matrix *or* data==array,colind==array,rowptr==array,m==int,n==int')
     291
    275292    def __repr__(self):
    276293        return '%d X %d sparse matrix:\n' %(self.M, self.N) + `self.data`
     
    283300    def nonzeros(self):
    284301        """Return number of nonzeros of A
    285         """       
     302        """
    286303        return len(self)
    287304
    288305    def todense(self):
    289306        D = num.zeros( (self.M, self.N), num.float)
    290        
     307
    291308        for i in range(self.M):
    292309            for ckey in range(self.row_ptr[i],self.row_ptr[i+1]):
     
    305322            print 'FIXME: Only numeric types implemented so far'
    306323
    307         return csr_mv(self,B) 
     324        return csr_mv(self,B)
    308325
    309326
     
    317334if __name__ == '__main__':
    318335    # A little selftest
    319    
     336
    320337    A = Sparse(3,3)
    321338
     
    329346
    330347    print A
    331     print A.todense()   
     348    print A.todense()
    332349
    333350    A[1,2] = 0
  • trunk/anuga_core/source/anuga/utilities/test_sparse.py

    r8124 r8127  
    199199        assert num.allclose(B*C2, [[15.0, 30.0],[10.0, 20.0],[8.0, 16.0],[0.0, 0.0]])
    200200
     201    def test_sparse_csr_init(self):
     202        A = num.array([[1.0,0.0,-1.0,0.0],[0.0,2.0,0.0,0.0],[0.0,0.0,0.0,-3.0],[0.0,0.0,4.0,0.0]])
     203        data = num.array([1.0,-1.0,2.0,-3.0,4.0])
     204        Colind = num.array([0,2,1,3,2])
     205        rowptr = num.array([0,2,3,4,5]) #the 5 does not correspond to any row, it is just there so we know how many nonzero entries there are!
     206        A_CSR = Sparse_CSR(None,data,Colind,rowptr,4,4)
     207        A_dense = A_CSR.todense()
     208        assert num.allclose(A, A_dense)
     209
    201210################################################################################
    202211
Note: See TracChangeset for help on using the changeset viewer.