Example #1
0
 def multiply(self, other):
     """Point-wise multiplication by another matrix, vector, or
     scalar.
     """
     # Scalar multiplication.
     if isscalarlike(other):
         return self.__mul__(other)
     # Sparse matrix or vector.
     if isspmatrix(other):
         if self.shape == other.shape:
             other = self.__class__(other)
             return self._binopt(other, '_elmul_')
         # Single element.
         elif other.shape == (1,1):
             return self.__mul__(other.tocsc().data[0])
         elif self.shape == (1,1):
             return other.__mul__(self.tocsc().data[0])
         # A row times a column.
         elif self.shape[1] == other.shape[0] and self.shape[1] == 1:
             return self._mul_sparse_matrix(other.tocsc())
         elif self.shape[0] == other.shape[1] and self.shape[0] == 1:
             return other._mul_sparse_matrix(self.tocsc())
         # Row vector times matrix. other is a row.
         elif other.shape[0] == 1 and self.shape[1] == other.shape[1]:
             other = dia_matrix((other.toarray().ravel(), [0]),
                                 shape=(other.shape[1], other.shape[1]))
             return self._mul_sparse_matrix(other)
         # self is a row.
         elif self.shape[0] == 1 and self.shape[1] == other.shape[1]:
             copy = dia_matrix((self.toarray().ravel(), [0]),
                                 shape=(self.shape[1], self.shape[1]))
             return other._mul_sparse_matrix(copy)
         # Column vector times matrix. other is a column.
         elif other.shape[1] == 1 and self.shape[0] == other.shape[0]:
             other = dia_matrix((other.toarray().ravel(), [0]),
                                 shape=(other.shape[0], other.shape[0]))
             return other._mul_sparse_matrix(self)
         # self is a column.
         elif self.shape[1] == 1 and self.shape[0] == other.shape[0]:
             copy = dia_matrix((self.toarray().ravel(), [0]),
                                 shape=(self.shape[0], self.shape[0]))
             return copy._mul_sparse_matrix(other)
         else:
             raise ValueError("inconsistent shapes")
     # Dense matrix.
     if isdense(other):
         if self.shape == other.shape:
             ret = self.tocoo()
             ret.data = np.multiply(ret.data, other[ret.row, ret.col]
                                    ).view(np.ndarray).ravel()
             # Current tests expect dense output.
             return ret.todense()
         # Single element.
         elif other.size == 1:
             return self.__mul__(other.flat[0])
     # Anything else.
     return np.multiply(self.todense(), other)
Example #2
0
    def create_sparse_rate_matrix(self):
        """
        constructs the following rate matrix for a M/M/1 queue
        TODO: fix math string
        :math: `
        Q = \begin{pmatrix}
        -\lambda & \lambda \\
        \mu & -(\mu+\lambda) & \lambda \\
        &\mu & -(\mu+\lambda) & \lambda \\
        &&\mu & -(\mu+\lambda) & \lambda &\\
        &&&&\ddots
        \end{pmatrix}`
        taken from: https://en.wikipedia.org/wiki/Transition_rate_matrix
        """
        lambda_ = 5
        mu = 3
        dim = self.dim

        diag = np.empty((3, dim))
        # main diagonal
        diag[0, 0] = (-lambda_)
        diag[0, 1:dim - 1] = -(mu + lambda_)
        diag[0, dim - 1] = lambda_

        # lower diag
        diag[1, :] = mu
        diag[1, -2:] = -mu
        diag[1, -2:] = lambda_
        diag[0, dim - 1] = -lambda_
        # upper diag
        diag[2, :] = lambda_

        offsets = [0, -1, 1]

        return dia_matrix((diag, offsets), shape=(dim, dim))
Example #3
0
    def create_sparse_rate_matrix(self):
        """
        constructs the following rate matrix for a M/M/1 queue
        TODO: fix math string
        :math: `
        Q = \begin{pmatrix}
        -\lambda & \lambda \\
        \mu & -(\mu+\lambda) & \lambda \\
        &\mu & -(\mu+\lambda) & \lambda \\
        &&\mu & -(\mu+\lambda) & \lambda &\\
        &&&&\ddots
        \end{pmatrix}`
        taken from: https://en.wikipedia.org/wiki/Transition_rate_matrix
        """
        lambda_ = 5
        mu = 3
        dim = self.dim

        diag = np.empty((3, dim))
        # main diagonal
        diag[0, 0] = (-lambda_)
        diag[0, 1:dim - 1] = -(mu + lambda_)
        diag[0, dim - 1] = lambda_

        # lower diag
        diag[1, :] = mu
        diag[1, -2:] = -mu
        diag[1, -2:] = lambda_
        diag[0, dim - 1] = -lambda_
        # upper diag
        diag[2, :] = lambda_

        offsets = [0, -1, 1]

        return dia_matrix((diag, offsets), shape=(dim, dim))
Example #4
0
 def _n_theta_operator(self) -> csc_matrix:
     """
     Returns
     -------
         `n_theta` operator in the charge basis"""
     diag_elements = np.arange(-self.ncut, self.ncut + 1)
     return dia_matrix(
         (diag_elements, [0]),
         shape=(self._dim_theta(), self._dim_theta())).tocsc()
Example #5
0
    def create_rev_t(self):
        dim = self.dim

        diag = np.zeros((3, dim))

        # forward_p = 4 / 5.
        forward_p = 0.6
        backward_p = 1 - forward_p
        # main diagonal
        diag[0, 0] = backward_p
        diag[0, -1] = backward_p

        # lower diag
        diag[1, :] = backward_p
        diag[1, 1] = forward_p

        # upper diag
        diag[2, :] = forward_p

        return dia_matrix((diag, [0, 1, -1]), shape=(dim, dim))
Example #6
0
    def create_rev_t(self):
        dim = self.dim

        diag = np.zeros((3, dim))

        # forward_p = 4 / 5.
        forward_p = 0.6
        backward_p = 1 - forward_p
        # main diagonal
        diag[0, 0] = backward_p
        diag[0, -1] = backward_p

        # lower diag
        diag[1, :] = backward_p
        diag[1, 1] = forward_p

        # upper diag
        diag[2, :] = forward_p

        return dia_matrix((diag, [0, 1, -1]), shape=(dim, dim))
Example #7
0
def partial_fit(self, x):
    max_idx = max(self.vocabulary_.values())
    for a in x:
        # update vocabulary_
        if self.lowercase:
            a = a.lower()
        tokens = re.findall(self.token_pattern, a)
        for w in tokens:
            if w not in self.vocabulary_:
                max_idx += 1
                self.vocabulary_[w] = max_idx

        # update idf_
        df = (self.n_docs + self.smooth_idf) / np.exp(self.idf_ -
                                                      1) - self.smooth_idf
        self.n_docs += 1
        df.resize(len(self.vocabulary_))
        for w in tokens:
            df[self.vocabulary_[w]] += 1
        idf = np.log(
            (self.n_docs + self.smooth_idf) / (df + self.smooth_idf)) + 1
        self._tfidf._idf_diag = dia_matrix((idf, 0),
                                           shape=(len(idf), len(idf)))
Example #8
0
    def multiply(self, other):
        """Point-wise multiplication by another matrix, vector, or
        scalar.
        """
        # print("multiply")
        # Scalar multiplication.
        if isscalarlike(other):
            return self._mul_scalar(other)
        # Sparse matrix or vector.
        if isspmatrix(other):
            if self.shape == other.shape:
                other = self.__class__(other)
                return self._binopt(other, '_elmul_')
            # Single element.
            elif other.shape == (1, 1):
                return self._mul_scalar(other.toarray()[0, 0])
            elif self.shape == (1, 1):
                return other._mul_scalar(self.toarray()[0, 0])
            # A row times a column.
            elif self.shape[1] == 1 and other.shape[0] == 1:
                return self._mul_sparse_matrix(other.tocsc())
            elif self.shape[0] == 1 and other.shape[1] == 1:
                return other._mul_sparse_matrix(self.tocsc())
            # Row vector times matrix. other is a row.
            elif other.shape[0] == 1 and self.shape[1] == other.shape[1]:
                other = dia_matrix((other.toarray().ravel(), [0]),
                                   shape=(other.shape[1], other.shape[1]))
                return self._mul_sparse_matrix(other)
            # self is a row.
            elif self.shape[0] == 1 and self.shape[1] == other.shape[1]:
                copy = dia_matrix((self.toarray().ravel(), [0]),
                                  shape=(self.shape[1], self.shape[1]))
                return other._mul_sparse_matrix(copy)
            # Column vector times matrix. other is a column.
            elif other.shape[1] == 1 and self.shape[0] == other.shape[0]:
                other = dia_matrix((other.toarray().ravel(), [0]),
                                   shape=(other.shape[0], other.shape[0]))
                return other._mul_sparse_matrix(self)
            # self is a column.
            elif self.shape[1] == 1 and self.shape[0] == other.shape[0]:
                copy = dia_matrix((self.toarray().ravel(), [0]),
                                  shape=(self.shape[0], self.shape[0]))
                return copy._mul_sparse_matrix(other)
            else:
                raise ValueError("inconsistent shapes")

        # Assume other is a dense matrix/array, which produces a single-item
        # object array if other isn't convertible to ndarray.
        other = np.atleast_2d(other)

        if other.ndim != 2:
            return np.multiply(self.toarray(), other)
        # Single element / wrapped object.
        if other.size == 1:
            return self._mul_scalar(other.flat[0])
        # Fast case for trivial sparse matrix.
        elif self.shape == (1, 1):
            return np.multiply(self.toarray()[0, 0], other)

        from scipy.sparse.coo import coo_matrix
        ret = self.tocoo()
        # Matching shapes.
        if self.shape == other.shape:
            data = np.multiply(ret.data, other[ret.row, ret.col])
        # Sparse row vector times...
        elif self.shape[0] == 1:
            if other.shape[1] == 1:  # Dense column vector.
                data = np.multiply(ret.data, other)
            elif other.shape[1] == self.shape[1]:  # Dense matrix.
                data = np.multiply(ret.data, other[:, ret.col])
            else:
                raise ValueError("inconsistent shapes")
            row = np.repeat(np.arange(other.shape[0]), len(ret.row))
            col = np.tile(ret.col, other.shape[0])
            return coo_matrix((data.view(np.ndarray).ravel(), (row, col)),
                              shape=(other.shape[0], self.shape[1]),
                              copy=False)
        # Sparse column vector times...
        elif self.shape[1] == 1:
            if other.shape[0] == 1:  # Dense row vector.
                data = np.multiply(ret.data[:, None], other)
            elif other.shape[0] == self.shape[0]:  # Dense matrix.
                data = np.multiply(ret.data[:, None], other[ret.row])
            else:
                raise ValueError("inconsistent shapes")
            row = np.repeat(ret.row, other.shape[1])
            col = np.tile(np.arange(other.shape[1]), len(ret.col))
            return coo_matrix((data.view(np.ndarray).ravel(), (row, col)),
                              shape=(self.shape[0], other.shape[1]),
                              copy=False)
        # Sparse matrix times dense row vector.
        elif other.shape[0] == 1 and self.shape[1] == other.shape[1]:
            data = np.multiply(ret.data, other[:, ret.col].ravel())
        # Sparse matrix times dense column vector.
        elif other.shape[1] == 1 and self.shape[0] == other.shape[0]:
            data = np.multiply(ret.data, other[ret.row].ravel())
        else:
            raise ValueError("inconsistent shapes")
        ret.data = data.view(np.ndarray).ravel()
        return ret