def cscmat2sym(mat): Ax = [] for j in range(mat.shape[1]): for p in range(mat.indptr[j], mat.indptr[j + 1]): Ax += [SymConst(mat.data[p])] return SymMatrix(list(mat.indptr), list(mat.indices), Ax, mat.shape[0], mat.shape[1])
def mul_elem(self, b): if isinstance(b, float) or isinstance(b, int): b = SymConst(b) Ax = [] for p in range(len(self.Ax)): Ax += [b * self.Ax[p]] return SymMatrix(self.Ap, self.Ai, Ax, self.m, self.n)
def densemat2sym(mat): Ap = [0] Ai = [] Ax = [] m, n = mat.shape for j in range(n): Ap += [Ap[-1] + m] for i in range(m): Ai += [i] Ax += [SymConst(mat[i, j])] return SymMatrix(Ap, Ai, Ax, m, n)
def as_dense(self): m, n = self.size Ap = [m * j for j in range(n + 1)] Ai = [p % m for p in range(m * n)] Ax = [SymConst(0.0)] * m * n for j in range(n): for p in range(self.Ap[j], self.Ap[j + 1]): i = self.Ai[p] p2 = j * m + i Ax[p2] = self.Ax[p] return SymMatrix(Ap, Ai, Ax, m, n)
def get_scalar(expr): if isinstance(expr, SymMatrix): if expr.shape == (1, 1): if expr.nnz == 0: return SymConst(0) else: return expr.Ax[0] else: return None elif isinstance(expr, float) or isinstance(expr, int): return float(expr) elif (isinstance(expr, np.matrix) or isinstance(expr, np.ndarray) or isinstance(expr, sp.csc_matrix) or isinstance(expr, sp.csr_matrix) or isinstance(expr, sp.coo_matrix)): if expr.shape == (1, 1): return SymConst(expr[0, 0]) else: return None else: raise TypeError("Unsupported argument type: %s" % str(type(expr)))
def as_sym_matrix(expr, sparsity=None): if isinstance(expr, SymMatrix): return expr elif isinstance(expr, CallbackParam): return cscparam2sym(expr, sparsity) elif isinstance(expr, Parameter): return denserowparam2sym(expr) elif isinstance(expr, float) or isinstance(expr, int): return SymMatrix([0, 1], [0], [SymConst(expr)], 1, 1) elif isinstance(expr, np.matrix): return densemat2sym(expr) elif isinstance(expr, np.ndarray): return densemat2sym(np.asmatrix(expr)) elif isinstance(expr, sp.csc_matrix): return cscmat2sym(expr) elif isinstance(expr, sp.coo_matrix): return cscmat2sym(sp.csc_matrix(expr)) else: raise TypeError("Unsupported argument type: %s" % str(type(expr)))
def reciprocals(A): Ax = [] for p in range(A.nnz): Ax += [SymConst(1) / A.Ax[p]] return SymMatrix(A.Ap, A.Ai, Ax, A.m, A.n)
def __neg__(self): return self.mul_elem(SymConst(-1))