def __setitem__(self, key, val):
        if isinstance(key, tuple):
            row,col = key
            if not (isscalarlike(row) and isscalarlike(col)):
                raise NotImplementedError("Fancy indexing in assignment not "
                                          "supported for csr matrices.")
            M, N = self.shape
            if (row < 0):
                row += M
            if (col < 0):
                col += N
            if not (0<=row<M) or not (0<=col<N):
                raise IndexError, "index out of bounds"

            major_index, minor_index = self._swap((row,col))

            start = self.indptr[major_index]
            end   = self.indptr[major_index+1]
            indxs = np.where(minor_index == self.indices[start:end])[0]

            num_matches = len(indxs)
    
            
            if not np.isscalar(val):
                raise ValueError('setting an array element with a sequence')

            val = self.dtype.type(val) 

            if num_matches == 0:
                #entry not already present
                warn('changing the sparsity structure of a %s_matrix is expensive. ' \
                        'lil_matrix is more efficient.' % self.format, \
                        SparseEfficiencyWarning)

                if self.has_sorted_indices:
                    # preserve sorted order
                    newindx = start + self.indices[start:end].searchsorted(minor_index)
                else:
                    newindx = start

                val         = np.array([val],         dtype=self.data.dtype)
                minor_index = np.array([minor_index], dtype=self.indices.dtype)

                self.data    = np.concatenate((self.data[:newindx],    val,         self.data[newindx:]))
                self.indices = np.concatenate((self.indices[:newindx], minor_index, self.indices[newindx:]))
                self.indptr  = self.indptr.copy()

                self.indptr[major_index+1:] += 1

            elif num_matches == 1:
                #entry appears exactly once
                self.data[start:end][indxs[0]] = val
            else:
                #entry appears more than once
                raise ValueError,'nonzero entry (%d,%d) occurs more than once' % (row,col)

            self.check_format(full_check=True)
        else:
            # We should allow slices here!
            raise IndexError, "invalid index"
Exemple #2
0
    def __setitem__(self, key, val):
        if isinstance(key, tuple):
            row,col = key
            if not (isscalarlike(row) and isscalarlike(col)):
                raise NotImplementedError("Fancy indexing in assignment not "
                                          "supported for csr matrices.")
            M, N = self.shape
            if (row < 0):
                row += M
            if (col < 0):
                col += N
            if not (0<=row<M) or not (0<=col<N):
                raise IndexError, "index out of bounds"

            major_index, minor_index = self._swap((row,col))

            start = self.indptr[major_index]
            end   = self.indptr[major_index+1]
            indxs = np.where(minor_index == self.indices[start:end])[0]

            num_matches = len(indxs)
    
            
            if not np.isscalar(val):
                raise ValueError('setting an array element with a sequence')

            val = self.dtype.type(val) 

            if num_matches == 0:
                #entry not already present
                warn('changing the sparsity structure of a %s_matrix is expensive. ' \
                        'lil_matrix is more efficient.' % self.format, \
                        SparseEfficiencyWarning)

                if self.has_sorted_indices:
                    # preserve sorted order
                    newindx = start + self.indices[start:end].searchsorted(minor_index)
                else:
                    newindx = start

                val         = np.array([val],         dtype=self.data.dtype)
                minor_index = np.array([minor_index], dtype=self.indices.dtype)

                self.data    = np.concatenate((self.data[:newindx],    val,         self.data[newindx:]))
                self.indices = np.concatenate((self.indices[:newindx], minor_index, self.indices[newindx:]))
                self.indptr  = self.indptr.copy()

                self.indptr[major_index+1:] += 1

            elif num_matches == 1:
                #entry appears exactly once
                self.data[start:end][indxs[0]] = val
            else:
                #entry appears more than once
                raise ValueError,'nonzero entry (%d,%d) occurs more than once' % (row,col)

            self.check_format(full_check=True)
        else:
            # We should allow slices here!
            raise IndexError, "invalid index"
Exemple #3
0
    def __pow__(self, other):
        if self.shape[0] != self.shape[1]:
            raise TypeError('matrix is not square')

        if isintlike(other):
            other = int(other)
            if other < 0:
                raise ValueError('exponent must be >= 0')

            if other == 0:
                from construct import identity
                return identity( self.shape[0], dtype=self.dtype )
            elif other == 1:
                return self.copy()
            else:
                result = self
                for i in range(1,other):
                    result = result*self
                return result
        elif isscalarlike(other):
            raise ValueError('exponent must be an integer')
        elif isspmatrix(other):
            warn('Using ** for elementwise multiplication is deprecated.'\
                    'Use .multiply() instead', DeprecationWarning)
            return self.multiply(other)
        else:
            raise NotImplementedError
Exemple #4
0
    def __pow__(self, other):
        if self.shape[0] != self.shape[1]:
            raise TypeError('matrix is not square')

        if isintlike(other):
            other = int(other)
            if other < 0:
                raise ValueError('exponent must be >= 0')

            if other == 0:
                from construct import identity
                return identity( self.shape[0], dtype=self.dtype )
            elif other == 1:
                return self.copy()
            else:
                result = self
                for i in range(1,other):
                    result = result*self
                return result
        elif isscalarlike(other):
            raise ValueError('exponent must be an integer')
        elif isspmatrix(other):
            warn('Using ** for elementwise multiplication is deprecated.'\
                    'Use .multiply() instead', DeprecationWarning)
            return self.multiply(other)
        else:
            raise NotImplementedError
Exemple #5
0
 def __itruediv__(self, other): #self /= other
     if isscalarlike(other):
         recip = 1.0 / other
         self.data *= recip
         return self
     else:
         raise NotImplementedError
Exemple #6
0
Fichier : dok.py Projet : 87/scipy
 def __add__(self, other):
     # First check if argument is a scalar
     if isscalarlike(other):
         new = dok_matrix(self.shape, dtype=self.dtype)
         # Add this scalar to every element.
         M, N = self.shape
         for i in xrange(M):
             for j in xrange(N):
                 aij = self.get((i, j), 0) + other
                 if aij != 0:
                     new[i, j] = aij
         #new.dtype.char = self.dtype.char
     elif isinstance(other, dok_matrix):
         if other.shape != self.shape:
             raise ValueError("matrix dimensions are not equal")
         # We could alternatively set the dimensions to the the largest of
         # the two matrices to be summed.  Would this be a good idea?
         new = dok_matrix(self.shape, dtype=self.dtype)
         new.update(self)
         for key in other.keys():
             new[key] += other[key]
     elif isspmatrix(other):
         csc = self.tocsc()
         new = csc + other
     elif isdense(other):
         new = self.todense() + other
     else:
         raise TypeError("data type not understood")
     return new
Exemple #7
0
 def __itruediv__(self, other):  # self /= other
     if isscalarlike(other):
         recip = 1.0 / other
         self.data *= recip
         return self
     else:
         raise NotImplementedError
Exemple #8
0
Fichier : dok.py Projet : 87/scipy
 def __radd__(self, other):
     # First check if argument is a scalar
     if isscalarlike(other):
         new = dok_matrix(self.shape, dtype=self.dtype)
         # Add this scalar to every element.
         M, N = self.shape
         for i in xrange(M):
             for j in xrange(N):
                 aij = self.get((i, j), 0) + other
                 if aij != 0:
                     new[i, j] = aij
     elif isinstance(other, dok_matrix):
         if other.shape != self.shape:
             raise ValueError("matrix dimensions are not equal")
         new = dok_matrix(self.shape, dtype=self.dtype)
         new.update(self)
         for key in other:
             new[key] += other[key]
     elif isspmatrix(other):
         csc = self.tocsc()
         new = csc + other
     elif isdense(other):
         new = other + self.todense()
     else:
         raise TypeError("data type not understood")
     return new
Exemple #9
0
 def __add__(self, other):
     # First check if argument is a scalar
     if isscalarlike(other):
         new = dok_matrix(self.shape, dtype=self.dtype)
         # Add this scalar to every element.
         M, N = self.shape
         for i in xrange(M):
             for j in xrange(N):
                 aij = self.get((i, j), 0) + other
                 if aij != 0:
                     new[i, j] = aij
         #new.dtype.char = self.dtype.char
     elif isinstance(other, dok_matrix):
         if other.shape != self.shape:
             raise ValueError("matrix dimensions are not equal")
         # We could alternatively set the dimensions to the the largest of
         # the two matrices to be summed.  Would this be a good idea?
         new = dok_matrix(self.shape, dtype=self.dtype)
         new.update(self)
         for key in other.keys():
             new[key] += other[key]
     elif isspmatrix(other):
         csc = self.tocsc()
         new = csc + other
     elif isdense(other):
         new = self.todense() + other
     else:
         raise TypeError("data type not understood")
     return new
Exemple #10
0
 def __radd__(self, other):
     # First check if argument is a scalar
     if isscalarlike(other):
         new = dok_matrix(self.shape, dtype=self.dtype)
         # Add this scalar to every element.
         M, N = self.shape
         for i in xrange(M):
             for j in xrange(N):
                 aij = self.get((i, j), 0) + other
                 if aij != 0:
                     new[i, j] = aij
     elif isinstance(other, dok_matrix):
         if other.shape != self.shape:
             raise ValueError("matrix dimensions are not equal")
         new = dok_matrix(self.shape, dtype=self.dtype)
         new.update(self)
         for key in other:
             new[key] += other[key]
     elif isspmatrix(other):
         csc = self.tocsc()
         new = csc + other
     elif isdense(other):
         new = other + self.todense()
     else:
         raise TypeError("data type not understood")
     return new
Exemple #11
0
    def __mul__(self, other):
        """interpret other and call one of the following

        self._mul_scalar()
        self._mul_vector()
        self._mul_multivector()
        self._mul_sparse_matrix()
        """

        M,N = self.shape

        if isscalarlike(other):
            # scalar value
            return self._mul_scalar(other)

        if issparse(other):
            if self.shape[1] != other.shape[0]:
                raise ValueError('dimension mismatch')
            return self._mul_sparse_matrix(other)

        try:
            other.shape
        except AttributeError:
            # If it's a list or whatever, treat it like a matrix
            other = np.asanyarray(other)

        other = np.asanyarray(other)

        if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:
            # dense row or column vector
            if other.shape != (N,) and other.shape != (N,1):
                raise ValueError('dimension mismatch')

            result = self._mul_vector(np.ravel(other))

            if isinstance(other, np.matrix):
                result = np.asmatrix(result)

            if other.ndim == 2 and other.shape[1] == 1:
                # If 'other' was an (nx1) column vector, reshape the result
                result = result.reshape(-1,1)

            return result

        elif other.ndim == 2:
            ##
            # dense 2D array or matrix ("multivector")

            if other.shape[0] != self.shape[1]:
                raise ValueError('dimension mismatch')

            result = self._mul_multivector(np.asarray(other))

            if isinstance(other, np.matrix):
                result = np.asmatrix(result)

            return result
        else:
            raise ValueError('could not interpret dimensions')
Exemple #12
0
    def __mul__(self, other):
        """interpret other and call one of the following

        self._mul_scalar()
        self._mul_vector()
        self._mul_multivector()
        self._mul_sparse_matrix()
        """

        M, N = self.shape

        if isscalarlike(other):
            # scalar value
            return self._mul_scalar(other)

        if issparse(other):
            if self.shape[1] != other.shape[0]:
                raise ValueError("dimension mismatch")
            return self._mul_sparse_matrix(other)

        try:
            other.shape
        except AttributeError:
            # If it's a list or whatever, treat it like a matrix
            other = np.asanyarray(other)

        other = np.asanyarray(other)

        if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:
            # dense row or column vector
            if other.shape != (N,) and other.shape != (N, 1):
                raise ValueError("dimension mismatch")

            result = self._mul_vector(np.ravel(other))

            if isinstance(other, np.matrix):
                result = np.asmatrix(result)

            if other.ndim == 2 and other.shape[1] == 1:
                # If 'other' was an (nx1) column vector, reshape the result
                result = result.reshape(-1, 1)

            return result

        elif other.ndim == 2:
            ##
            # dense 2D array or matrix ("multivector")

            if other.shape[0] != self.shape[1]:
                raise ValueError("dimension mismatch")

            result = self._mul_multivector(np.asarray(other))

            if isinstance(other, np.matrix):
                result = np.asmatrix(result)

            return result
        else:
            raise ValueError("could not interpret dimensions")
Exemple #13
0
 def __itruediv__(self, other):
     if isscalarlike(other):
         # Multiply this scalar by every element.
         for (key, val) in self.iteritems():
             self[key] = val / other
         return self
     else:
         return NotImplementedError
Exemple #14
0
Fichier : dok.py Projet : 87/scipy
 def __itruediv__(self, other):
     if isscalarlike(other):
         # Multiply this scalar by every element.
         for (key, val) in self.iteritems():
             self[key] = val / other
         return self
     else:
         return NotImplementedError
Exemple #15
0
 def __truediv__(self, other):  # self / other
     if isscalarlike(other):
         new = self.copy()
         # Divide every element by this scalar
         new.data = [[val / other for val in rowvals]
                     for rowvals in new.data]
         return new
     else:
         return self.tocsr() / other
Exemple #16
0
 def __truediv__(self, other):           # self / other
     if isscalarlike(other):
         new = self.copy()
         # Divide every element by this scalar
         new.data = [[val/other for val in rowvals] for
                     rowvals in new.data]
         return new
     else:
         return self.tocsr() / other
Exemple #17
0
Fichier : dok.py Projet : 87/scipy
 def __imul__(self, other):
     if isscalarlike(other):
         # Multiply this scalar by every element.
         for (key, val) in self.iteritems():
             self[key] = val * other
         #new.dtype.char = self.dtype.char
         return self
     else:
         return NotImplementedError
Exemple #18
0
 def __imul__(self, other):
     if isscalarlike(other):
         # Multiply this scalar by every element.
         for (key, val) in self.iteritems():
             self[key] = val * other
         #new.dtype.char = self.dtype.char
         return self
     else:
         return NotImplementedError
Exemple #19
0
Fichier : dok.py Projet : 87/scipy
 def __truediv__(self, other):
     if isscalarlike(other):
         new = dok_matrix(self.shape, dtype=self.dtype)
         # Multiply this scalar by every element.
         for (key, val) in self.iteritems():
             new[key] = val / other
         #new.dtype.char = self.dtype.char
         return new
     else:
         return self.tocsr() / other
Exemple #20
0
 def __truediv__(self, other):
     if isscalarlike(other):
         new = dok_matrix(self.shape, dtype=self.dtype)
         # Multiply this scalar by every element.
         for (key, val) in self.iteritems():
             new[key] = val / other
         #new.dtype.char = self.dtype.char
         return new
     else:
         return self.tocsr() / other
Exemple #21
0
 def __rmul__(self, other): # other * self
     if isscalarlike(other):
         return self.__mul__(other)
     else:
         # Don't use asarray unless we have to
         try:
             tr = other.transpose()
         except AttributeError:
             tr = np.asarray(other).transpose()
         return (self.transpose() * tr).transpose()
Exemple #22
0
 def __rmul__(self, other):  # other * self
     if isscalarlike(other):
         return self.__mul__(other)
     else:
         # Don't use asarray unless we have to
         try:
             tr = other.transpose()
         except AttributeError:
             tr = np.asarray(other).transpose()
         return (self.transpose() * tr).transpose()
 def __rsub__(self,other):  # other - self
     #note: this can't be replaced by other + (-self) for unsigned types
     if isscalarlike(other):
         # Now we would add this scalar to every element.
         raise NotImplementedError, 'adding a scalar to a sparse ' \
               'matrix is not supported'
     elif isdense(other):
         # Convert this matrix to a dense matrix and subtract them
         return other - self.todense()
     else:
         raise NotImplementedError
Exemple #24
0
 def __rsub__(self,other):  # other - self
     #note: this can't be replaced by other + (-self) for unsigned types
     if isscalarlike(other):
         # Now we would add this scalar to every element.
         raise NotImplementedError, 'adding a scalar to a sparse ' \
               'matrix is not supported'
     elif isdense(other):
         # Convert this matrix to a dense matrix and subtract them
         return other - self.todense()
     else:
         raise NotImplementedError
Exemple #25
0
    def __truediv__(self,other):
        if isscalarlike(other):
            return self * (1./other)

        elif isspmatrix(other):
            if other.shape != self.shape:
                raise ValueError('inconsistent shapes')

            return self._binopt(other,'_eldiv_')

        else:
            raise NotImplementedError
Exemple #26
0
    def __truediv__(self, other):
        if isscalarlike(other):
            return self * (1. / other)

        elif isspmatrix(other):
            if other.shape != self.shape:
                raise ValueError('inconsistent shapes')

            return self._binopt(other, '_eldiv_')

        else:
            raise NotImplementedError
    def __sub__(self,other):
        # First check if argument is a scalar
        if isscalarlike(other):
            # Now we would add this scalar to every element.
            raise NotImplementedError, 'adding a scalar to a sparse ' \
                  'matrix is not supported'
        elif isspmatrix(other):
            if (other.shape != self.shape):
                raise ValueError, "inconsistent shapes"

            return self._binopt(other,'_minus_')
        elif isdense(other):
            # Convert this matrix to a dense matrix and subtract them
            return self.todense() - other
        else:
            raise NotImplementedError
Exemple #28
0
    def __sub__(self,other):
        # First check if argument is a scalar
        if isscalarlike(other):
            # Now we would add this scalar to every element.
            raise NotImplementedError, 'adding a scalar to a sparse ' \
                  'matrix is not supported'
        elif isspmatrix(other):
            if (other.shape != self.shape):
                raise ValueError, "inconsistent shapes"

            return self._binopt(other,'_minus_')
        elif isdense(other):
            # Convert this matrix to a dense matrix and subtract them
            return self.todense() - other
        else:
            raise NotImplementedError
Exemple #29
0
    def __add__(self,other):
        # First check if argument is a scalar
        if isscalarlike(other):
            # Now we would add this scalar to every element.
            raise NotImplementedError('adding a scalar to a CSC or CSR '
                                        'matrix is not supported')
        elif isspmatrix(other):
            if (other.shape != self.shape):
                raise ValueError("inconsistent shapes")

            return self._binopt(other,'_plus_')
        elif isdense(other):
            # Convert this matrix to a dense matrix and add them
            return self.todense() + other
        else:
            raise NotImplementedError
Exemple #30
0
    def __sub__(self, other):
        # First check if argument is a scalar
        if isscalarlike(other):
            if other == 0:
                return self.copy()
            else:  # Now we would add this scalar to every element.
                raise NotImplementedError("adding a nonzero scalar to a " "sparse matrix is not supported")
        elif isspmatrix(other):
            if other.shape != self.shape:
                raise ValueError("inconsistent shapes")

            return self._binopt(other, "_minus_")
        elif isdense(other):
            # Convert this matrix to a dense matrix and subtract them
            return self.todense() - other
        else:
            raise NotImplementedError
Exemple #31
0
    def __pow__(self, other):
        if self.shape[0] != self.shape[1]:
            raise TypeError('matrix is not square')

        if isintlike(other):
            other = int(other)
            if other < 0:
                raise ValueError('exponent must be >= 0')

            if other == 0:
                from construct import identity
                return identity( self.shape[0], dtype=self.dtype )
            elif other == 1:
                return self.copy()
            else:
                result = self
                for i in range(1,other):
                    result = result*self
                return result
        elif isscalarlike(other):
            raise ValueError('exponent must be an integer')
        else:
            raise NotImplementedError
Exemple #32
0
 def __imul__(self, other): #self *= other
     if isscalarlike(other):
         self.data *= other
         return self
     else:
         raise NotImplementedError
Exemple #33
0
 def __itruediv__(self, other):
     if isscalarlike(other):
         self[:, :] = self / other
         return self
     else:
         raise NotImplementedError
Exemple #34
0
 def __truediv__(self, other):
     if isscalarlike(other):
         return self * (1./other)
     else:
         return self.tocsr().__truediv__(other)
Exemple #35
0
 def __imul__(self, other):  # self *= other
     if isscalarlike(other):
         self.data *= other
         return self
     else:
         raise NotImplementedError
Exemple #36
0
 def __itruediv__(self,other):
     if isscalarlike(other):
         self[:,:] = self / other
         return self
     else:
         raise NotImplementedError
Exemple #37
0
 def __truediv__(self, other):
     if isscalarlike(other):
         return self * (1.0 / other)
     else:
         return self.tocsr().__truediv__(other)