当前位置: 首页>>代码示例>>Python>>正文


Python cvxopt.spmatrix方法代码示例

本文整理汇总了Python中cvxopt.spmatrix方法的典型用法代码示例。如果您正苦于以下问题:Python cvxopt.spmatrix方法的具体用法?Python cvxopt.spmatrix怎么用?Python cvxopt.spmatrix使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cvxopt的用法示例。


在下文中一共展示了cvxopt.spmatrix方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: cvxopt_matrix

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def cvxopt_matrix(M):
    """
    Convert matrix to CVXOPT format.

    Parameters
    ----------
    M : numpy.array
        Matrix in NumPy format.

    Returns
    -------
    N : cvxopt.matrix
        Matrix in CVXOPT format.
    """
    if type(M) is ndarray:
        return matrix(M)
    elif type(M) is spmatrix or type(M) is matrix:
        return M
    coo = M.tocoo()
    return spmatrix(
        coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=M.shape) 
开发者ID:stephane-caron,项目名称:qpsolvers,代码行数:23,代码来源:cvxopt_.py

示例2: _break_cols

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def _break_cols(mat, sizes):
    n = len(sizes)
    I, J, V = [], [], []
    for i in range(n):
        I.append([])
        J.append([])
        V.append([])
    cumsz = np.cumsum(sizes)
    import bisect
    for i, j, v in zip(mat.I, mat.J, mat.V):
        block = bisect.bisect(cumsz, j)
        I[block].append(i)
        V[block].append(v)
        if block == 0:
            J[block].append(j)
        else:
            J[block].append(j - cumsz[block - 1])
    return [spmatrix(V[k], I[k], J[k], (mat.size[0], sz))
            for k, sz in enumerate(sizes)] 
开发者ID:gsagnol,项目名称:picos,代码行数:21,代码来源:tools.py

示例3: _break_rows

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def _break_rows(mat, sizes):
    n = len(sizes)
    I, J, V = [], [], []
    for i in range(n):
        I.append([])
        J.append([])
        V.append([])
    cumsz = np.cumsum(sizes)
    import bisect
    for i, j, v in zip(mat.I, mat.J, mat.V):
        block = bisect.bisect(cumsz, i)
        J[block].append(j)
        V[block].append(v)
        if block == 0:
            I[block].append(i)
        else:
            I[block].append(i - cumsz[block - 1])
    return [spmatrix(V[k], I[k], J[k], (sz, mat.size[1]))
            for k, sz in enumerate(sizes)] 
开发者ID:gsagnol,项目名称:picos,代码行数:21,代码来源:tools.py

示例4: _blocdiag

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def _blocdiag(X, n):
    """
    makes diagonal blocs of X, for indices in [sub1,sub2[
    n indicates the total number of blocks (horizontally)
    """
    if not isinstance(X, cvx.base.spmatrix):
        X = cvx.sparse(X)
    if n==1:
        return X
    else:
        Z = spmatrix([],[],[],X.size)
        mat = []
        for i in range(n):
            col = [Z]*(n-1)
            col.insert(i,X)
            mat.append(col)
        return cvx.sparse(mat) 
开发者ID:gsagnol,项目名称:picos,代码行数:19,代码来源:tools.py

示例5: inplace_transpose

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def inplace_transpose(self):
        if isinstance(self, Variable):
            raise Exception(
                'inplace_transpose should not be called on a Variable object')
        for k in self.factors:
            bsize = self.size[0]
            bsize2 = self.size[1]
            I0 = [(i // bsize) + (i % bsize) *
                  bsize2 for i in self.factors[k].I]
            J = self.factors[k].J
            V = self.factors[k].V
            self.factors[k] = spmatrix(V, I0, J, self.factors[k].size)

        if not (self.constant is None):
            self.constant = cvx.matrix(self.constant,
                                       self.size).T[:]
        self._size = (self.size[1], self.size[0])
        if (('*' in self.affstring()) or ('/' in self.affstring())
                or ('+' in self.affstring()) or ('-' in self.affstring())):
            self.string = '( ' + self.string + ' ).T'
        else:
            self.string += '.T' 
开发者ID:gsagnol,项目名称:picos,代码行数:24,代码来源:expression.py

示例6: diag

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def diag(self, dim):
        if self.size != (1, 1):
            raise Exception('not implemented')
        selfcopy = self.copy()
        idx = cvx.spdiag([1.] * dim)[:].I

        for k in self.factors:
            tc = 'z' if self.factors[k].typecode=='z' else 'd'
            selfcopy.factors[k] = spmatrix(
                [], [], [], (dim**2, self.factors[k].size[1]),tc=tc)
            for i in idx:
                selfcopy.factors[k][i, :] = self.factors[k]
        if not self.constant is None:
            tc = 'z' if self.constant.typecode=='z' else 'd'
            selfcopy.constant = cvx.matrix(0., (dim**2, 1),tc=tc)
            for i in idx:
                selfcopy.constant[i] = self.constant[0]
        else:
            selfcopy.constant = None
        selfcopy._size = (dim, dim)
        selfcopy.string = 'diag(' + selfcopy.string + ')'
        return selfcopy 
开发者ID:gsagnol,项目名称:picos,代码行数:24,代码来源:expression.py

示例7: __init__

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def __init__(self, fun, Exp, funstring):
        Expression.__init__(self, self.funstring + '( ' + Exp.string + ')')
        self.fun = fun
        r"""The function ``f`` applied to the affine expression.
                This function must take in argument a
                :func:`cvxopt sparse matrix <cvxopt:cvxopt.spmatrix>` ``X``.
                Moreover, the call ``fx,grad,hess=f(X)``
                must return the function value :math:`f(X)` in ``fx``,
                the gradient :math:`\nabla f(X)` in the
                :func:`cvxopt matrix <cvxopt:cvxopt.matrix>` ``grad``,
                and the Hessian :math:`\nabla^2 f(X)` in the
                :func:`cvxopt sparse matrix <cvxopt:cvxopt.spmatrix>` ``hess``.
                """
        self.Exp = Exp
        """The affine expression to which the function is applied"""
        self.funstring = funstring
        """a string representation of the function name"""
        #self.string=self.funstring+'( '+self.Exp.affstring()+' )' 
开发者ID:gsagnol,项目名称:picos,代码行数:20,代码来源:expression.py

示例8: _get_projector

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def _get_projector(R, N_ex):  # !
    # Projection
    dim = N_ex
    P = spmatrix(1, range(dim), range(dim))
    glast = matrix(np.ones((1, dim)))
    G = sparse([-P, P, glast])
    h1 = np.zeros(dim)
    h2 = np.ones(dim)
    h = matrix(np.concatenate([h1, h2, [R]]))

    def _project(pt):
        print('start projection')
        # pt = gamma.eval()
        q = matrix(- np.array(pt, dtype=np.float64))
        # if np.linalg.norm(pt, ord=1) < R:
        #    return
        _res = cvxopt.solvers.qp(P, q, G, h, initvals=q)
        _resx = np.array(_res['x'], dtype=np.float32)[:, 0]
        # gamma_assign.eval(feed_dict={grad_hyper: _resx})
        return _resx

    return _project


# TODO check the following functions (look right) 
开发者ID:lucfra,项目名称:RFHO,代码行数:27,代码来源:data_hypercleaner.py

示例9: compute_displacements

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def compute_displacements(self, xPhys):
        # Setup and solve FE problem
        sK = ((self.KE.flatten()[np.newaxis]).T * (
            self.Emin + (xPhys)**self.penal *
            (self.Emax - self.Emin))).flatten(order='F')
        K = scipy.sparse.coo_matrix((sK, (self.iK, self.jK)),
            shape=(self.ndof, self.ndof)).tocsc()
        # Remove constrained dofs from matrix and convert to coo
        K = deleterowcol(K, self.fixed, self.fixed).tocoo()
        # Solve system
        K1 = cvxopt.spmatrix(K.data, K.row.astype(np.int), K.col.astype(np.int))
        B = cvxopt.matrix(self.f[self.free, :])
        cvxopt.cholmod.linsolve(K1, B)
        self.u[self.free, :] = np.array(B)[:, :] 
开发者ID:zfergus,项目名称:fenics-topopt,代码行数:16,代码来源:problem.py

示例10: scipy_sparse_to_spmatrix

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def scipy_sparse_to_spmatrix(A):
    """Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
    coo = A.tocoo()
    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
    return SP 
开发者ID:PythonOT,项目名称:POT,代码行数:7,代码来源:cvx.py

示例11: find_nearest_valid_distribution

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def find_nearest_valid_distribution(u_alpha, kernel, initial=None, reg=0):
    """ (solution,distance_sqd)=find_nearest_valid_distribution(u_alpha,kernel):
    Given a n-vector u_alpha summing to 1, with negative terms, 
    finds the distance (squared) to the nearest n-vector summing to 1, 
    with non-neg terms. Distance calculated using nxn matrix kernel. 
    Regularization parameter reg -- 

    min_v (u_alpha - v)^\top K (u_alpha - v) + reg* v^\top v"""

    P = matrix(2 * kernel)
    n = kernel.shape[0]
    q = matrix(np.dot(-2 * kernel, u_alpha))
    A = matrix(np.ones((1, n)))
    b = matrix(1.)
    G = spmatrix(-1., range(n), range(n))
    h = matrix(np.zeros(n))
    dims = {'l': n, 'q': [], 's': []}
    solvers.options['show_progress'] = False
    solution = solvers.coneqp(
        P,
        q,
        G,
        h,
        dims,
        A,
        b,
        initvals=initial
        )
    distance_sqd = solution['primal objective'] + np.dot(u_alpha.T,
            np.dot(kernel, u_alpha))[0, 0]
    return (solution, distance_sqd) 
开发者ID:levelfour,项目名称:SU_Classification,代码行数:33,代码来源:mpe.py

示例12: diag_vect

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def diag_vect(exp):
    """
    Returns the vector with the diagonal elements of the matrix expression ``exp``

    **Example**

    >>> import picos as pic
    >>> prob=pic.Problem()
    >>> X=prob.add_variable('X',(3,3))
    >>> pic.tools.diag_vect(X)
    # (3 x 1)-affine expression: diag(X) #

    """
    from .expression import AffinExp
    (n, m) = exp.size
    n = min(n, m)
    idx = cvx.spdiag([1.] * n)[:].I
    expcopy = AffinExp(exp.factors.copy(), exp.constant, exp.size,
                       exp.string)
    proj = spmatrix([1.] * n, range(n), idx,
                        (n, exp.size[0] * exp.size[1]))
    for k in exp.factors.keys():
        expcopy.factors[k] = proj * expcopy.factors[k]
    if not exp.constant is None:
        expcopy.constant = proj * expcopy.constant
    expcopy._size = (n, 1)
    expcopy.string = 'diag(' + exp.string + ')'
    return expcopy 
开发者ID:gsagnol,项目名称:picos,代码行数:30,代码来源:tools.py

示例13: svecm1

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def svecm1(vec, triu=False):
    if vec.size[1] > 1:
        raise ValueError('should be a column vector')
    v = vec.size[0]
    n = int(np.sqrt(1 + 8 * v) - 1) // 2
    if n * (n + 1) // 2 != v:
        raise ValueError('vec should be of dimension n(n+1)/2')
    if not isinstance(vec, cvx.spmatrix):
        vec = cvx.sparse(vec)
    I = []
    J = []
    V = []
    for i, v in zip(vec.I, vec.V):
        c = int(np.sqrt(1 + 8 * i) - 1) // 2
        r = i - c * (c + 1) // 2
        I.append(r)
        J.append(c)
        if r == c:
            V.append(v)
        else:
            if triu:
                V.append(v / np.sqrt(2))
            else:
                I.append(c)
                J.append(r)
                V.extend([v / np.sqrt(2)] * 2)
    return spmatrix(V, I, J, (n, n)) 
开发者ID:gsagnol,项目名称:picos,代码行数:29,代码来源:tools.py

示例14: _cplx_mat_to_real_mat

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def _cplx_mat_to_real_mat(M):
    """
    if M = A +iB,
    return the block matrix [A,-B;B,A]
    """
    if not(isinstance(M, cvx.base.spmatrix) or isinstance(M, cvx.base.matrix)):
        raise NameError('unexpected matrix type')
    if M.typecode == 'z':
        A = M.real()
        B = M.imag()
    else:
        A = M
        B = spmatrix([], [], [], A.size)
    return cvx.sparse([[A, B], [-B, A]]) 
开发者ID:gsagnol,项目名称:picos,代码行数:16,代码来源:tools.py

示例15: eval

# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import spmatrix [as 别名]
def eval(self, ind=None):
        if self.constant is None:
            val = spmatrix([], [], [], (self.size[0] * self.size[1], 1))
        else:
            val = self.constant
        if self.is0():
            return cvx.matrix(val, self.size)

        for k in self.factors:
            # ignore this factor if the coef is 0
            if not(self.factors[k]):
                continue
            if ind is None:
                if not k.value is None:
                    if k.vtype == 'symmetric':
                        val = val + self.factors[k] * svec(k.value)
                    else:
                        val = val + self.factors[k] * k.value[:]
                else:
                    raise Exception(k + ' is not valued')
            else:
                if ind in k.value_alt:
                    if k.vtype == 'symmetric':
                        val = val + self.factors[k] * svec(k.value_alt[ind])
                    else:
                        val = val + self.factors[k] * k.value_alt[ind][:]
                else:
                    raise Exception(
                        k + ' does not have a value for the index ' + str(ind))
        return cvx.matrix(val, self.size) 
开发者ID:gsagnol,项目名称:picos,代码行数:32,代码来源:expression.py


注:本文中的cvxopt.spmatrix方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。