How to use the cvxopt.solvers function in cvxopt

To help you get started, we’ve selected a few cvxopt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Marigold / universal-portfolios / universal / algos / kelly.py View on Github external
def maximize(self, mu, sigma, r):
        n = len(mu)
        
        P = matrix((sigma - r*mu*mu.T + (n*r)**2) / (1+r))
        q = matrix(-mu)
        G = matrix(-np.eye(n))
        h = matrix(np.zeros(n))
        
        sol = solvers.qp(P, q, G, h)
        return np.squeeze(sol['x'])
github insarlab / MintPy / pysar / utils / solvers / l1.py View on Github external
# x0 = [ uls;  1.1*abs(rls) ];   s0 = [q;-q] - [P,-I; -P,-I] * x0
    x0 = matrix([uls[:n],  1.1*abs(rls)])
    s0 = +h
    Fi(x0, s0, alpha=-1, beta=1)

    # z0 = [ (1+w)/2; (1-w)/2 ] where w = (.9/||rls||_inf) * rls
    # if rls is nonzero and w = 0 otherwise.
    if max(abs(rls)) > 1e-10:
        w = .9/max(abs(rls)) * rls
    else:
        w = matrix(0.0, (m, 1))
    z0 = matrix([.5*(1+w), .5*(1-w)])

    dims = {'l': 2*m, 'q': [], 's': []}
    sol = solvers.conelp(c, Fi, h, dims, kktsolver=Fkkt,
                         primalstart={'x': x0, 's': s0}, dualstart={'z': z0})
    return sol['x'][:n]
github tulip-control / tulip-control / tulip / polytope / esp.py View on Github external
c = np.zeros(d+1)
                c[0] = 1
                Gup = np.hstack([-np.ones([Sq.shape[0],1]),Sq])
                Gdo = np.hstack([-1, np.zeros(Sq.shape[1])])
                G = np.vstack([Gup, Gdo])
                h = np.hstack([tq, 1])
                
                Al = np.zeros([2, 1])
                Ar = np.vstack([af,S[i,:]])
                A = np.hstack([Al,Ar])
                bb = np.hstack([bf,t[i]])
                
                solvers.options['show_progress']=False
                solvers.options['LPX_K_MSGLEV'] = 0
                sol = solvers.lp(matrix(c), matrix(G) , matrix(h), matrix(A), matrix(bb), lp_solver)
                if sol['status'] == 'optimal':
                    tau = sol['x'][0]
                    if tau < -abs_tol:
                        ar = np.array([S[i,:]]).flatten()
                        br = t[i].flatten()
                        
                        # Make orthogonal to facet
                        ar = ar - af*np.dot(af.flatten(),ar.flatten())
                        br = br - bf*np.dot(af.flatten(),ar.flatten())
            
                        # Normalize and make ridge equation point outwards
                        norm = np.sqrt(np.sum(ar*ar))
                        ar = ar/norm
                        br = br/norm
                        
                        Er_list.append(Ridge(np.sort(np.hstack([E,E_c[Q]])),ar,br))
github yangarbiter / adversarial-nonparametrics / nnattack / attacks / nns / nn_attack.py View on Github external
if init_x is None and not sol_sat_constraints(G, h):
        return False, None

    c = matrix(np.concatenate((np.zeros(fet_dim), np.ones(fet_dim))), tc='d')

    G = np.hstack((G, np.zeros((G.shape[0], fet_dim))))
    G = np.vstack((G, np.hstack((np.eye(fet_dim), -np.eye(fet_dim)))))
    G = np.vstack((G, np.hstack((-np.eye(fet_dim), -np.eye(fet_dim)))))

    h = np.concatenate((h, target_x, -target_x))

    G, h = matrix(G, tc='d'), matrix(h, tc='d')

    temph = h - CONSTRAINTTOL
    if init_x is not None:
        sol = solvers.lp(c=c, G=G, h=temph, solver='glpk',
                         initvals=init_x)
    else:
        sol = solvers.lp(c=c, G=G, h=temph, solver='glpk')

    if sol['status'] == 'optimal':
        ret = np.array(sol['x']).reshape(-1)
        return True, ret[:len(ret)//2]
    else:
        return False, None
github santiaago / caltech.ml / hw7.py View on Github external
def run_pla_vs_svm(nbruns = 1, N = 10):
    solvers.options['show_progress'] = False
    
    d = []
    l = 0
    f = 0
    t_set = []
    y = []
    svm_vs_pla = []
    for i in range(nbruns):
        onBothSides = False
        while(not onBothSides):
            d = data(N)
            l = randomline()
            f = target_function(l)
            t_set = build_training_set(d,f)
            y = target_vector(t_set)
            if (1 in y) and (-1 in y):
github czielinski / portfolioopt / portfolioopt / portfolioopt.py View on Github external
else:
        # exp_rets*x >= target_ret
        G = opt.matrix(-exp_rets.values).T
        h = opt.matrix(-target_ret)

    # Constraints Ax = b
    # sum(x) = 1
    A = opt.matrix(1.0, (1, n))

    if not market_neutral:
        b = opt.matrix(1.0)
    else:
        b = opt.matrix(0.0)

    # Solve
    optsolvers.options['show_progress'] = False
    sol = optsolvers.qp(P, q, G, h, A, b)

    if sol['status'] != 'optimal':
        warnings.warn("Convergence problem")

    # Put weights into a labeled series
    weights = pd.Series(sol['x'], index=cov_mat.index)
    return weights
github tulip-control / tulip-control / tulip / hybrid_costs / hybrid_costs.py View on Github external
H_after = block_diag(*[H1.A]*(N-switch))
    H_blk = block_diag(H_before,H_after)
    h_before = np.tile(H0.b,(1,(switch+1)))[0]
    h_after = np.tile(H1.b,(1,(N-switch)))[0]
    h_blk = np.hstack((h_before,h_after))
    
    # Combine input and state constraints
    G = np.vstack((np.dot(H_blk, S_u), D_blk))
    h = np.hstack((h_blk-np.dot(H_blk, np.dot(S_x,x0)), d_blk))
        
    P = 2*matrix(H)     #factor of 2 for cvxopt input
    q = matrix(2*np.dot(x0,F)) 
    G = matrix(G)
    h = matrix(h)
            
    sol = solvers.qp(P,q,G,h)
    
    if sol['status'] != "optimal":
        raise Exception("getInputHelper: QP solver finished with status " + \
                        str(sol['status']))
    u = np.array(sol['x']).flatten()
    cost = sol['primal objective'] + np.dot(x0,np.dot(Y,x0))
    
    return u.reshape(N, m), cost
github msmbuilder / msmbuilder / Mixtape / mslds_solvers / mslds_Q_sdp.py View on Github external
for i in range(len(Gs)):
        Gs[i] = -Gs[i]
    G = np.copy(matrix(Gs[0]))

    # Now scale D upwards for stability
    max_D_eig = max(eig(D)[0])

    hs, _ = construct_const_matrix(x_dim, A, Bdown, D)
    for i in range(len(hs)):
        hs[i] = matrix(hs[i])
    # Smallest number epsilon such that 1. + epsilon != 1.
    epsilon = np.finfo(np.float32).eps
    # Add a small positive offset to avoid taking sqrt of singular matrix
    F = real(sqrtm(Bdown + epsilon * eye(x_dim)))

    solvers.options['maxiters'] = max_iters
    solvers.options['show_progress'] = show_display
    #solvers.options['debug'] = True
    sol = solvers.sdp(cm, Gs=Gs, hs=hs)
    qvec = np.array(sol['x'])
    qvec = qvec[int(1 + x_dim * (x_dim + 1) / 2):]
    Q = np.zeros((x_dim, x_dim))
    for j in range(x_dim):
        for k in range(j + 1):
            vec_pos = int(j * (j + 1) / 2 + k)
            Q[j, k] = qvec[vec_pos]
            Q[k, j] = Q[j, k]
    return sol, c, Gs, hs
github cvxopt / cvxopt / src / python / modeling.py View on Github external
raise TypeError('lp must have at least one inequality')
        G = inequalities[0]._f._linear._coeff[x]
        h = -inequalities[0]._f._constant

        equalities = lp1._equalities
        if equalities:
            A = equalities[0]._f._linear._coeff[x]
            b = -equalities[0]._f._constant
        elif format == 'dense':
            A = matrix(0.0, (0,len(x)))
            b = matrix(0.0, (0,1))
        else:
            A = spmatrix(0.0, [], [],  (0,len(x)))
            b = matrix(0.0, (0,1))

        sol = solvers.lp(c[:], G, h, A, b, solver=solver, **kwargs)

        x.value = sol['x']
        inequalities[0].multiplier.value = sol['z']
        if equalities: equalities[0].multiplier.value = sol['y']

        self.status = sol['status']
        if type(t) is tuple:
            for v,f in iter(vmap.items()): v.value = f.value()
            for c,f in iter(mmap.items()): c.multiplier.value = f.value()
github zfergus / seam-erasure / SeamMin / inequalities.py View on Github external
def cvxopt_solve_all_depth(shape, P, q, G=None, h=None, A=None, b=None,
            solver = None):
        """
        Wrapper around CVXOPT's QP solver that solve for all channels.
        Input:
            shape - the shape of the linear term, q.
            !(shape) - same as CVXOPT QP
        Output:
            Numpy array of the solved channels.
        """
        # sol = cvxopt.solvers.qp(P, q, G=G, h=h, A=A, b=b, solver=solver)
        x = numpy.empty(shape)
        for i in range(shape[1]):
            hi = None if h is None else h[:, i]
            bi = None if b is None else b[:, i]
            result  = cvxopt.solvers.qp(P, q[:, i], G=G, h=hi, A=A, b=bi,
                solver=solver)
            # result  = cvxopt.solvers.qp(P, q[:, i], solver = solver)
            x[:, i] = numpy.array(result["x"]).flatten()
        return x