Пример #1
0
    def tocoo(self, copy=False):
        from .coo import coo_matrix
        if self.nnz == 0:
            return coo_matrix(self.shape, dtype=self.dtype)

        idx_dtype = get_index_dtype(maxval=max(self.shape))
        data = np.fromiter(itervalues(self), dtype=self.dtype, count=self.nnz)
        row = np.fromiter((i for i, _ in iterkeys(self)), dtype=idx_dtype, count=self.nnz)
        col = np.fromiter((j for _, j in iterkeys(self)), dtype=idx_dtype, count=self.nnz)
        A = coo_matrix((data, (row, col)), shape=self.shape, dtype=self.dtype)
        A.has_canonical_format = True
        return A
Пример #2
0
    def tocoo(self, copy=False):
        from .coo import coo_matrix
        if self.nnz == 0:
            return coo_matrix(self.shape, dtype=self.dtype)

        idx_dtype = get_index_dtype(maxval=max(self.shape))
        data = np.fromiter(itervalues(self), dtype=self.dtype, count=self.nnz)
        row = np.fromiter((i for i, _ in iterkeys(self)), dtype=idx_dtype, count=self.nnz)
        col = np.fromiter((j for _, j in iterkeys(self)), dtype=idx_dtype, count=self.nnz)
        A = coo_matrix((data, (row, col)), shape=self.shape, dtype=self.dtype)
        A.has_canonical_format = True
        return A
Пример #3
0
 def __neg__(self):
     if self.dtype.kind == 'b':
         raise NotImplementedError('Negating a sparse boolean matrix is not'
                                   ' supported.')
     new = dok_matrix(self.shape, dtype=self.dtype)
     dict.update(new, ((k, -self[k]) for k in iterkeys(self)))
     return new
Пример #4
0
 def __add__(self, other):
     if isscalarlike(other):
         res_dtype = upcast_scalar(self.dtype, other)
         new = dok_matrix(self.shape, dtype=res_dtype)
         # Add this scalar to every element.
         M, N = self.shape
         for key in itertools.product(xrange(M), xrange(N)):
             aij = dict.get(self, (key), 0) + other
             if aij:
                 new[key] = aij
         # new.dtype.char = self.dtype.char
     elif isspmatrix_dok(other):
         if other.shape != self.shape:
             raise ValueError("Matrix dimensions are not equal.")
         # We could alternatively set the dimensions to the largest of
         # the two matrices to be summed.  Would this be a good idea?
         res_dtype = upcast(self.dtype, other.dtype)
         new = dok_matrix(self.shape, dtype=res_dtype)
         dict.update(new, self)
         with np.errstate(over='ignore'):
             dict.update(new,
                        ((k, new[k] + other[k]) for k in iterkeys(other)))
     elif isspmatrix(other):
         csc = self.tocsc()
         new = csc + other
     elif isdense(other):
         new = self.todense() + other
     else:
         return NotImplemented
     return new
Пример #5
0
 def __neg__(self):
     if self.dtype.kind == 'b':
         raise NotImplementedError('Negating a sparse boolean matrix is not'
                                   ' supported.')
     new = dok_matrix(self.shape, dtype=self.dtype)
     dict.update(new, ((k, -self[k]) for k in iterkeys(self)))
     return new
Пример #6
0
 def __add__(self, other):
     if isscalarlike(other):
         res_dtype = upcast_scalar(self.dtype, other)
         new = dok_matrix(self.shape, dtype=res_dtype)
         # Add this scalar to every element.
         M, N = self.shape
         for key in itertools.product(xrange(M), xrange(N)):
             aij = dict.get(self, (key), 0) + other
             if aij:
                 new[key] = aij
         # new.dtype.char = self.dtype.char
     elif isspmatrix_dok(other):
         if other.shape != self.shape:
             raise ValueError("Matrix dimensions are not equal.")
         # We could alternatively set the dimensions to the largest of
         # the two matrices to be summed.  Would this be a good idea?
         res_dtype = upcast(self.dtype, other.dtype)
         new = dok_matrix(self.shape, dtype=res_dtype)
         dict.update(new, self)
         with np.errstate(over='ignore'):
             dict.update(new,
                         ((k, new[k] + other[k]) for k in iterkeys(other)))
     elif isspmatrix(other):
         csc = self.tocsc()
         new = csc + other
     elif isdense(other):
         new = self.todense() + other
     else:
         return NotImplemented
     return new
Пример #7
0
 def resize(self, *shape):
     shape = check_shape(shape)
     newM, newN = shape
     M, N = self.shape
     if newM < M or newN < N:
         # Remove all elements outside new dimensions
         for (i, j) in list(iterkeys(self)):
             if i >= newM or j >= newN:
                 del self[i, j]
     self._shape = shape
Пример #8
0
 def resize(self, *shape):
     shape = check_shape(shape)
     newM, newN = shape
     M, N = self.shape
     if newM < M or newN < N:
         # Remove all elements outside new dimensions
         for (i, j) in list(iterkeys(self)):
             if i >= newM or j >= newN:
                 del self[i, j]
     self._shape = shape
Пример #9
0
    def resize(self, shape):
        """Resize the matrix in-place to dimensions given by `shape`.

        Any non-zero elements that lie outside the new shape are removed.
        """
        if not isshape(shape):
            raise TypeError("Dimensions must be a 2-tuple of positive integers")
        newM, newN = shape
        M, N = self.shape
        if newM < M or newN < N:
            # Remove all elements outside new dimensions
            for (i, j) in list(iterkeys(self)):
                if i >= newM or j >= newN:
                    del self[i, j]
        self._shape = shape
Пример #10
0
    def resize(self, shape):
        """Resize the matrix in-place to dimensions given by `shape`.

        Any non-zero elements that lie outside the new shape are removed.
        """
        if not isshape(shape):
            raise TypeError(
                "Dimensions must be a 2-tuple of positive integers")
        newM, newN = shape
        M, N = self.shape
        if newM < M or newN < N:
            # Remove all elements outside new dimensions
            for (i, j) in list(iterkeys(self)):
                if i >= newM or j >= newN:
                    del self[i, j]
        self._shape = shape
Пример #11
0
    def _getitem_ranges(self, i_indices, j_indices, shape):
        # performance golf: we don't want Numpy scalars here, they are slow
        i_start, i_stop, i_stride = map(int, i_indices)
        j_start, j_stop, j_stride = map(int, j_indices)

        newdok = dok_matrix(shape, dtype=self.dtype)

        for (ii, jj) in iterkeys(self):
            # ditto for numpy scalars
            ii = int(ii)
            jj = int(jj)
            a, ra = divmod(ii - i_start, i_stride)
            if a < 0 or a >= shape[0] or ra != 0:
                continue
            b, rb = divmod(jj - j_start, j_stride)
            if b < 0 or b >= shape[1] or rb != 0:
                continue
            dict.__setitem__(newdok, (a, b), dict.__getitem__(self, (ii, jj)))
        return newdok
Пример #12
0
    def _getitem_ranges(self, i_indices, j_indices, shape):
        # performance golf: we don't want Numpy scalars here, they are slow
        i_start, i_stop, i_stride = map(int, i_indices)
        j_start, j_stop, j_stride = map(int, j_indices)

        newdok = dok_matrix(shape, dtype=self.dtype)

        for (ii, jj) in iterkeys(self):
            # ditto for numpy scalars
            ii = int(ii)
            jj = int(jj)
            a, ra = divmod(ii - i_start, i_stride)
            if a < 0 or a >= shape[0] or ra != 0:
                continue
            b, rb = divmod(jj - j_start, j_stride)
            if b < 0 or b >= shape[1] or rb != 0:
                continue
            dict.__setitem__(newdok, (a, b),
                             dict.__getitem__(self, (ii, jj)))
        return newdok
Пример #13
0
 def __radd__(self, other):
     if isscalarlike(other):
         new = dok_matrix(self.shape, dtype=self.dtype)
         M, N = self.shape
         for key in itertools.product(xrange(M), xrange(N)):
             aij = dict.get(self, (key), 0) + other
             if aij:
                 new[key] = aij
     elif isspmatrix_dok(other):
         if other.shape != self.shape:
             raise ValueError("Matrix dimensions are not equal.")
         new = dok_matrix(self.shape, dtype=self.dtype)
         dict.update(new, self)
         dict.update(new,
                    ((k, self[k] + other[k]) for k in iterkeys(other)))
     elif isspmatrix(other):
         csc = self.tocsc()
         new = csc + other
     elif isdense(other):
         new = other + self.todense()
     else:
         return NotImplemented
     return new
Пример #14
0
 def __radd__(self, other):
     if isscalarlike(other):
         new = dok_matrix(self.shape, dtype=self.dtype)
         M, N = self.shape
         for key in itertools.product(xrange(M), xrange(N)):
             aij = dict.get(self, (key), 0) + other
             if aij:
                 new[key] = aij
     elif isspmatrix_dok(other):
         if other.shape != self.shape:
             raise ValueError("Matrix dimensions are not equal.")
         new = dok_matrix(self.shape, dtype=self.dtype)
         dict.update(new, self)
         dict.update(new,
                     ((k, self[k] + other[k]) for k in iterkeys(other)))
     elif isspmatrix(other):
         csc = self.tocsc()
         new = csc + other
     elif isdense(other):
         new = other + self.todense()
     else:
         return NotImplemented
     return new
Пример #15
0
 def _get_sliceXslice(self, row, col):
     row_start, row_stop, row_step = row.indices(self.shape[0])
     col_start, col_stop, col_step = col.indices(self.shape[1])
     row_range = xrange(row_start, row_stop, row_step)
     col_range = xrange(col_start, col_stop, col_step)
     shape = (len(row_range), len(col_range))
     # Switch paths only when advantageous
     # (count the iterations in the loops, adjust for complexity)
     if len(self) >= 2 * shape[0] * shape[1]:
         # O(nr*nc) path: loop over <row x col>
         return self._get_columnXarray(row_range, col_range)
     # O(nnz) path: loop over entries of self
     newdok = dok_matrix(shape, dtype=self.dtype)
     for key in iterkeys(self):
         i, ri = divmod(int(key[0]) - row_start, row_step)
         if ri != 0 or i < 0 or i >= shape[0]:
             continue
         j, rj = divmod(int(key[1]) - col_start, col_step)
         if rj != 0 or j < 0 or j >= shape[1]:
             continue
         x = dict.__getitem__(self, key)
         dict.__setitem__(newdok, (i, j), x)
     return newdok
Пример #16
0
 def _get_sliceXslice(self, row, col):
     row_start, row_stop, row_step = row.indices(self.shape[0])
     col_start, col_stop, col_step = col.indices(self.shape[1])
     row_range = xrange(row_start, row_stop, row_step)
     col_range = xrange(col_start, col_stop, col_step)
     shape = (len(row_range), len(col_range))
     # Switch paths only when advantageous
     # (count the iterations in the loops, adjust for complexity)
     if len(self) >= 2 * shape[0] * shape[1]:
         # O(nr*nc) path: loop over <row x col>
         return self._get_columnXarray(row_range, col_range)
     # O(nnz) path: loop over entries of self
     newdok = dok_matrix(shape, dtype=self.dtype)
     for key in iterkeys(self):
         i, ri = divmod(int(key[0]) - row_start, row_step)
         if ri != 0 or i < 0 or i >= shape[0]:
             continue
         j, rj = divmod(int(key[1]) - col_start, col_step)
         if rj != 0 or j < 0 or j >= shape[1]:
             continue
         x = dict.__getitem__(self, key)
         dict.__setitem__(newdok, (i, j), x)
     return newdok