Esempio n. 1
0
    def setUp(self):
        # Data.
        c = picos.new_param("c", cvxopt.matrix([1, 2, 3, 4, 5]))
        A = picos.new_param("A", [
            cvxopt.matrix([1, 0, 0, 0, 0]).T,
            cvxopt.matrix([0, 0, 2, 0, 0]).T,
            cvxopt.matrix([0, 0, 0, 2, 0]).T,
            cvxopt.matrix([1, 0, 0, 0, 0]).T,
            cvxopt.matrix([1, 0, 2, 0, 0]).T,
            cvxopt.matrix([0, 1, 1, 1, 0]).T,
            cvxopt.matrix([1, 2, 0, 0, 0]).T,
            cvxopt.matrix([1, 0, 3, 0, 1]).T
        ])
        self.n = n = len(A)
        self.m = m = c.size[0]

        # Primal problem.
        self.P = P = picos.Problem()
        self.u = u = P.add_variable("u", m)
        P.set_objective("min", c | u)
        self.C = P.add_list_of_constraints(
            [abs(A[i] * u) < 1 for i in range(n)], "i", "[n]")

        # Dual problem.
        self.D = D = picos.Problem()
        self.z = z = [D.add_variable("z[{}]".format(i)) for i in range(n)]
        self.mu = mu = D.add_variable("mu", n)
        D.set_objective("min", 1 | mu)
        D.add_list_of_constraints([abs(z[i]) < mu[i] for i in range(n)], "i",
                                  "[n]")
        D.add_constraint(
            picos.sum([A[i].T * z[i] for i in range(n)], "i", "[n]") == c)
def DOBSS(AttackerRF, DefenderRF, Prob):
    prob = pic.Problem()
    l = len(DefenderRF[0])
    m = len(DefenderRF[0][0])
    tnum = len(DefenderRF)
    x = prob.add_variable('x', l, lower=0, upper=1)
    na = prob.add_variable('na', (tnum, m), 'binary')
    v = prob.add_variable('v', tnum)
    rfa = pic.new_param('rfa', AttackerRF)
    rfd = pic.new_param('rfd', DefenderRF)
    pr = pic.new_param('pr', Prob)

    prob.add_constraint(pic.sum([x[i] for i in range(l)], 'i', '[l]') == 1)
    for j in range(0, tnum):
        prob.add_constraint(
            pic.sum([na[j, i] for i in range(m)], 'i', '[m]') == 1)

    for j in range(0, tnum):
        prob.add_list_of_constraints(
            [v[j] - (x.T * rfa[j])[i] > 0 for i in range(m)], 'i', '[m]')
        prob.add_list_of_constraints([
            v[j] - (x.T * rfa[j])[i] < 1000000 * (1 - na[j, i])
            for i in range(m)
        ], 'i', '[m]')

    obj = 0
    for j in range(0, tnum):
        obj = obj + pr[j] * x.T * rfd[j] * (na[j, :]).T

    #obj = pic.sum([pr[p]*x.T*rfd[p]*(na[p,:]).T for p in range(tnum)],'p','[tnum]')
    prob.set_objective('max', obj)
    prob.solve(verbose=0)
    return np.array(x), np.array(obj)
Esempio n. 3
0
def calc_update(graph, alive_points, alpha, beta, eta, s, verbose=False):
    # Update coloring for alive variables
    incidence = graph.incidence[alive_points]
    (living_n, m) = np.shape(incidence)

    # Calculates each dangerosity of S_j
    dangerosity = np.zeros(m, dtype=int)
    max_k = beta.size - 1
    for j in range(m):
        k = max(0, np.searchsorted(beta, abs(eta[j])) - 1)
        if (k == max_k):
            raise AlgorithmFailure
        else:
            dangerosity[j] = k
    # print("dangerosity =", dangerosity)

    sdp = pic.Problem()
    Xp = sdp.add_variable("X", (living_n, living_n), vtype='symmetric')

    if verbose:
        print('incidence mat. of alive points =')
        print(incidence)

    vs = [incidence[:, j] for j in range(m)]
    vvs = [
        pic.new_param('vv' + str(j), np.outer(vs[j], vs[j])) for j in range(m)
    ]
    iden = pic.new_param('I', np.identity(living_n, dtype=int))

    if verbose:
        # print("I =", iden)
        print('vs =', vs)
        print('vvs =', [np.outer(vs[j], vs[j]) for j in range(m)])

    sdp.add_constraint(iden | Xp > living_n * 0.5)
    sdp.add_list_of_constraints(
        [vvs[j] | Xp < alpha[dangerosity[j]] for j in range(m)])
    sdp.add_list_of_constraints([Xp[i, i] < 1 for i in range(living_n)])
    sdp.add_constraint(Xp >> 0)
    sdp.set_objective('find', 0)
    if verbose:
        print(sdp)

    sdp.solve(verbose=0)
    v = np.linalg.cholesky(Xp.value)
    g = np.array([np.random.normal() for i in range(living_n)])
    gamma = np.zeros(graph.n)

    short_idx = 0
    for (i, flag) in enumerate(alive_points):
        if flag:
            gamma[i] = s * np.dot(g, v[:, short_idx])
            short_idx += 1

    if verbose:
        print('v =', v)
        print('gamma =', gamma)

    return gamma
Esempio n. 4
0
def unpack_params_picos(params):
    '''

    :param params: list [c, q, xi_0, b]
    :return:
    '''
    c = pic.new_param('c', params[0])
    q = pic.new_param('q', params[1])
    xi_0 = pic.new_param('xi_0', params[2])
    b = pic.new_param('b', params[3])
    B = pic.new_param('B', np.diag(params[3]))
    return c, q, xi_0, b, B
Esempio n. 5
0
def calc_update(graph, alive_points, coloring, verbose=False):
    # Updates alive variables
    incidence = graph.incidence[alive_points]
    (remaining_n, l) = np.shape(incidence)
    sdp = pic.Problem()
    Xp = sdp.add_variable("X", (remaining_n, remaining_n), vtype='symmetric')
    a = 6
    big_set_flags = (np.sum(incidence == 1, axis=0) >= a * graph.degree)
    alive_coloring = coloring[alive_points]
    if verbose:
        print('incidence mat. of alive points =')
        print(incidence)

    vs = [incidence[:, i] for i in range(l)]
    xs = [vs[i] * alive_coloring for i in range(l)]
    vvs = [
        pic.new_param('vv' + str(i), np.outer(vs[i], vs[i])) for i in range(l)
    ]
    iden = pic.new_param('I', np.identity(remaining_n))
    xxs = [
        pic.new_param('xx' + str(i), np.outer(xs[i], xs[i])) for i in range(l)
    ]

    if verbose:
        print('vs =')
        print(vs)
        print('xs =')
        print(xs)
        print('vvs =')
        print([np.outer(vs[i], vs[i]) for i in range(l)])
        print('xxs =')
        print([np.outer(xs[i], xs[i]) for i in range(l)])

    sdp.add_list_of_constraints(
        [vvs[i] | Xp == 0 for i in range(l) if big_set_flags[i]])
    sdp.add_list_of_constraints([(vvs[i] - 2 * iden) | Xp < 0 for i in range(l)
                                 if not big_set_flags[i]])
    sdp.add_list_of_constraints([(xxs[i] - 2 * iden) | Xp < 0 for i in range(l)
                                 if not big_set_flags[i]])
    sdp.add_list_of_constraints([Xp[i, i] < 1 for i in range(remaining_n)])
    sdp.add_constraint(Xp >> 0)
    sdp.set_objective('max', pic.trace(Xp))

    sdp.solve(verbose=0)
    U = np.linalg.cholesky(Xp.value)

    if verbose:
        print(sdp)
        print('U =')
        print(U)

    return (np.linalg.cholesky(Xp.value))
Esempio n. 6
0
def solve_SAA(params, Xi, r):
    N = Xi.shape[0]
    Xi_pic = [pic.new_param('xi_' + str(i + 1), Xi[i]) for i in range(N)]
    # Unpack problem parameters
    c, q, xi_0, b, B = unpack_params_picos(params)
    r = pic.new_param('r', r)
    # Unpack artificial parameters
    E, c_tilde, E_tilde_arr, E_arr, e5 = define_art_params(
        c.get_value(), q.get_value(), xi_0)
    E, c_tilde, E_tilde_arr, E_arr, e5 = convert_art_params_picos(
        E, c_tilde, E_tilde_arr, E_arr, e5)
    # Get dimensions.
    x_dim = len(c)
    xi_dim = len(xi_0)
    num_piecewise_lin_f = len(E_tilde_arr)
    # Initialize picos problem.
    pb = pic.Problem()

    # Add variables.
    x_tilde = pb.add_variable("x_tilde", x_dim + 1)
    t = pb.add_variable("t", N)
    eta1_arr = [
        pb.add_variable("eta1_" + str(i + 1), xi_dim) for i in range(2)
    ]
    eta2_arr = [pb.add_variable("eta2_" + str(i + 1), 10) for i in range(2)]

    # Add constraints.
    for i in range(N):
        for j in range(num_piecewise_lin_f):
            pb.add_constraint((E_tilde_arr[j] * Xi_pic[i]) | x_tilde <= t[i])

    for j in range(2):
        pb.add_constraint(
            abs(B.T * E_arr[j].T * x_tilde - B.T *
                (eta1_arr[j] - eta2_arr[j])) <= MAX_MAN_HOUR -
            (x_tilde.T * E_arr[j] * xi_0 / r) -
            ((eta1_arr[j] + eta2_arr[j]) | b / r))
        # positivity of lagrange multipliers
        pb.add_constraint(eta1_arr[j] >= 0)
        pb.add_constraint(eta2_arr[j] >= 0)

    pb.add_constraint(E.T * x_tilde >= 0)
    pb.add_constraint(e5 | x_tilde == -1)

    # Set objective.
    pb.set_objective("min", (1 / N) * (1 | t) - (c_tilde | x_tilde))

    solution = pb.solve(solver='cvxopt')
    opt_val = -pb.obj_value()
    opt_sol = np.array(solution['cvxopt_sol']['x'][:x_dim]).reshape(-1).round(
        5)  # round 5 digits
    return opt_sol, opt_val
Esempio n. 7
0
def convert_art_params_picos(E, c_tilde, E_tilde_arr, E_arr, e5):
    E = pic.new_param('E', E)
    c_tilde = pic.new_param('c_tilde', c_tilde)
    E_tilde_arr = [pic.new_param('E_tilde_1', E_tilde_arr[0]),
                   pic.new_param('E_tilde_2', E_tilde_arr[1]),
                   pic.new_param('E_tilde_3', E_tilde_arr[2]),
                   pic.new_param('E_tilde_4', E_tilde_arr[3])]
    E_arr = [pic.new_param('E_1', E_arr[0]), pic.new_param('E_2', E_arr[1])]
    e5 = pic.new_param('e5', e5)
    return E, c_tilde, E_tilde_arr, E_arr, e5
Esempio n. 8
0
def lin_fbcon(A, B, solv):
    ## A, B are knwon matrices of the LTI system
    #solv: choose the solver for example mosek, sdpa, cvxopt
    # The solvers need to be installed separatelly
    # http://picos.zib.de/intro.html#solvers

    #size of matrices A and B
    [n, n] = np.shape(A)
    [n, m] = np.shape(B)
    #starting the optimization problem
    F = pic.Problem()

    #Add parameters and variables
    A = pic.new_param('A', A)

    B = pic.new_param('B', B)

    P = F.add_variable('P', (n, n), 'symmetric')
    Q = F.add_variable('Q', (m, n))

    F.add_constraint(P * A.T - Q.T * B.T + A * P - B * Q << 0)

    F.add_constraint(P >> 0)
    #optimzation objective
    #by default the objetive is to maximize the trace of P
    #comment the next line if the objetive is just to find any solution
    F.set_objective('max', 'I' | P)
    print(F)
    #solving the LMI, with selected solver
    F.solve(solver=solv, verbose=0)

    P = np.matrix(P.value)
    Q = np.matrix(Q.value)

    print('optimal matrix P:')
    print(P)
    print('matrix Q:')
    print(Q)
    print("\n the Eigenvalues of P are:")
    print(LA.eigvals(P))
    print("\nSolution test")
    #print(LA.eigvals(A.T*P+P*A))

    K = Q * P.I
    print('The gain matrix K is:')
    print(K)

    return K
Esempio n. 9
0
def sdp(P, k):
    """Solve the SDP relaxation.

    Parameters
    ----------
    P : np.array
        m*N matrix of N m-dimensional points stacked columnwise
    k : int
        Number of clusters

    Returns
    -------
    The SDP minimizer S_D
    """
    N = P.shape[1]

    # Compute pairwise distances
    D = scipy.spatial.distance.pdist(P.T)
    D = scipy.spatial.distance.squareform(D)

    # Create the semi-definite program
    sdp = pic.Problem()
    Dparam = pic.new_param("D", D)
    X = sdp.add_variable("X", (N, N), vtype="symmetric")
    sdp.add_constraint(pic.trace(X) == k)
    sdp.add_constraint(X * "|1|({},1)".format(N) == 1)
    sdp.add_constraint(X > 0)
    sdp.add_constraint(X >> 0)
    sdp.minimize(Dparam | X)

    # Extract the SDP solution
    X_D = np.array(X.value)

    return X_D
Esempio n. 10
0
def lin_lyap(A):
    # matrix A in nxn
    n = np.shape(A)
    print n
    F = pic.Problem()
    A = pic.new_param("A", A)

    P = F.add_variable('P', n, 'symmetric')
    #objetive maximize the trace of P
    # if the objective is just to find a solution, then comment  the next line
    F.set_objective('max', 'I' | P)  #('I' | Z.real) works as well
    F.add_constraint(A.H * P + P * A << 0)
    F.add_constraint(P >> 0)
    print F

    F.solve(solver='mosek', verbose=0)

    #print 'fidelity: F(P,Q) = {0:.4f}'.format(F.obj_value())

    print 'optimal matrix P:'
    P = np.array(P.value)
    A = np.array(A.value)
    print P
    print "\n the Eigenvalues of P are:"
    print LA.eigvals(P)
    print "\nSolution test"
    print LA.eigvals(np.transpose(A) * P + P * A)
    return P
def f(rho1, sig2, gam1, gam2, d2, cov=True):
    # rho -> sigma under GP (set cov=False)/ GPC map? Output \approx 1 --> yes, output<1 --> no.
    #    dim(rho1) = dim(gam1)
    #    dim(sig2) = dim(gam2) = d2

    id_d2 = pic.new_param('id_d2', np.eye(d2))
    ## def problem & variables ##
    p = pic.Problem()
    X1 = p.add_variable('X1', (3, 3), 'hermitian')
    X2 = p.add_variable('X2', (d2, d2), 'hermitian')
    X3 = p.add_variable('X3', (d2, d2), 'hermitian')

    p.add_constraint((sig2 | X2) + (gam2 | X3) == 1)
    if cov == True:
        p.add_constraint(
            pic.kron(id_d2, X1) - dephase2(pic.kron(X2, rho1)) -
            pic.kron(X3, gam1) >> 0.)
    else:
        p.add_constraint(
            pic.kron(id_d2, X1) - pic.kron(X2, rho1) -
            pic.kron(X3, gam1) >> 0.)

    p.add_constraint(X1 >> 0)
    p.add_constraint(X2 >> 0)
    p.add_constraint(X3 >> 0)

    ## objective fn & solve ##
    p.set_objective('min', pic.trace(X1))
    p.solve(verbose=0, solver='cvxopt')
    return p.obj_value().real
def maxcut_ipm_solver(C):
    """
    Solve the Max-Cut SDP problem with Interior Point Method

    :param C: (2d array[float], NxN) - Weight Matrix representd the graph to be partitioned
    :return: (2d array[float], NxN) - SDP solution,
             (1d array[integer]) - Final objective value,
             (float) - Final elapsed time

    """
    N = C.shape[0]

    # SDP Creation =====================================================================================================
    max_cut = pic.Problem()
    C = pic.new_param('C', C)
    X = max_cut.add_variable('X', (N, N), 'symmetric')
    max_cut.add_constraint(pic.tools.diag_vect(X) == 1)
    max_cut.add_constraint(X >> 0)
    max_cut.set_objective('max', C | (1 - X))

    # Solve SDP ========================================================================================================
    start_time = time.time()
    max_cut.solve(verbose=0)  # Solve SDP
    elapsed_time = time.time() - start_time  # Calculate execution time

    return np.array(X.value), 0.5 * max_cut.obj_value(), elapsed_time
def solveCompleteGame(DefenderRF, AttackerRF, PureStrategyList, BoundList,
                      Prob):
    rewardmax = -10000000
    deltamax = []

    for i in range(0, len(PureStrategyList)):

        #print(BoundList[i])
        if (np.array(BoundList[i].value) < np.array(rewardmax)):
            continue
        try:

            prob = pic.Problem()
            m = len(DefenderRF[0][0])
            l = len(DefenderRF[0])
            t = len(DefenderRF)
            delta = prob.add_variable('delta', l, lower=0, upper=1)
            rfa = pic.new_param('rfa', AttackerRF)
            rfd = pic.new_param('rfd', DefenderRF)
            probs = pic.new_param('prob', Prob)
            sigma = pic.new_param('sigma', PureStrategyList[i])
            purestrategylist = pic.new_param('purestrategylist',
                                             PureStrategyList)
            prob.add_constraint(
                pic.sum([delta[j] for j in range(l)], 'j', '[l]') == 1)
            attrew = pic.sum([
                probs[p] * delta.T * rfa[p] * (sigma[p, :]).T for p in range(t)
            ], 'p', '[t]')
            for k in range(0, len(PureStrategyList)):
                prob.add_constraint(attrew > pic.sum([
                    probs[p] * delta.T * rfa[p] * (purestrategylist[k][p, :]).T
                    for p in range(t)
                ], 'p', '[t]'))
            obj = 0
            for j in range(0, t):
                obj = obj + probs[j] * delta.T * rfd[j] * (sigma[j, :]).T
            #obj = pic.sum([probs[p]*delta.T*rfd[p]*(sigma[p,:]).T for p in range(t)],'p','[t]')
            prob.set_objective('max', obj)
            #print(prob)
            prob.solve(verbose=0)
            print(obj)
            if ((obj.value[0]) > rewardmax):
                rewardmax = (obj.value[0])
                deltamax = np.array(delta)
        except:
            print("boohoo")
    return deltamax, rewardmax
Esempio n. 14
0
    def get_GW_cut(self, graph):
        ########################################################################
        # RETURNS AVERAGE GEOMANNS WILLIAMSON CUT FOR A GIVEN GRAPH
        ########################################################################

        G = graph
        N = len(G.nodes())

        # Allocate weights to the edges.
        for (i, j) in G.edges():
            G[i][j]['weight'] = 1.0

        maxcut = pic.Problem()

        # Add the symmetric matrix variable.
        X = maxcut.add_variable('X', (N, N), 'symmetric')

        # Retrieve the Laplacian of the graph.
        LL = 1 / 4. * nx.laplacian_matrix(G).todense()
        L = pic.new_param('L', LL)

        # Constrain X to have ones on the diagonal.
        maxcut.add_constraint(pic.tools.diag_vect(X) == 1)

        # Constrain X to be positive semidefinite.
        maxcut.add_constraint(X >> 0)

        # Set the objective.
        maxcut.set_objective('max', L | X)

        # Solve the problem.
        maxcut.solve(verbose=0, solver='cvxopt')

        # Use a fixed RNG seed so the result is reproducable.
        cvx.setseed(1)

        # Perform a Cholesky factorization.
        V = X.value
        cvxopt.lapack.potrf(V)
        for i in range(N):
            for j in range(i + 1, N):
                V[i, j] = 0

        # Do up to 100 projections. Stop if we are within a factor 0.878 of the SDP
        # optimal value.
        count = 0
        obj_sdp = maxcut.obj_value()
        obj = 0
        while (obj < 0.878 * obj_sdp):
            r = cvx.normal(N, 1)
            x = cvx.matrix(np.sign(V * r))
            o = (x.T * L * x).value
            if o > obj:
                x_cut = x
                obj = o
            count += 1
        x = x_cut

        return obj, count
def solveRestrictedGame(DefenderRF, AttackerRF):
    PureStrategyList = generatePureStrategy(AttackerRF)
    Delete = []
    Bound = [10000000] * len(PureStrategyList)
    rewardmax = -10000000
    deltamax = []
    count = 0

    for i in range(0, len(PureStrategyList)):
        try:
            prob = pic.Problem()
            m = len(DefenderRF[0])
            l = len(DefenderRF)
            t = 1
            delta = prob.add_variable('delta', l, lower=0, upper=1)
            rfa = pic.new_param('rfa', AttackerRF)
            rfd = pic.new_param('rfd', DefenderRF)
            sigma = pic.new_param('sigma', PureStrategyList[i])
            purestrategylist = pic.new_param('purestrategylist',
                                             PureStrategyList)
            prob.add_constraint(
                pic.sum([delta[j] for j in range(l)], 'j', '[l]') == 1)
            attrew = delta.T * rfa * (sigma)
            #print(purestrategylist)
            for k in range(0, len(PureStrategyList)):
                prob.add_constraint(attrew > delta.T * rfa *
                                    (purestrategylist[k].T))

            obj = delta.T * rfd * (sigma)
            prob.set_objective('max', obj)
            prob.solve(verbose=0)
            print(obj)
            if (np.array(obj) > rewardmax):
                rewardmax = np.array(obj)
                deltamax = np.array(delta)
            Bound[count] = np.array(obj)
            count += 1
        except:
            Delete.append(PureStrategyList[i])
            print("boohoo")
    for i in range(0, len(Delete)):
        PureStrategyList.remove(Delete[i])
    return PureStrategyList, Bound[0:len(PureStrategyList)], deltamax
Esempio n. 16
0
def get_CBT_norm(J, n, m, rev=False):
    import cvxopt as cvx
    import picos as pic
    # Get completely bounded trace norm of Choi-matrix J representing quantum channel from number_of_qubits-dimensional space to m-dimensional space
    J = cvx.matrix(J)
    prob = pic.Problem(verbose=0)
    X = prob.add_variable("X", (n * m, n * m), vtype='complex')

    I = pic.new_param('I', np.eye(m))

    rho0 = prob.add_variable("rho0", (n, n), vtype='hermitian')
    rho1 = prob.add_variable("rho1", (n, n), vtype='hermitian')
    prob.add_constraint(rho0 >> 0)
    prob.add_constraint(rho1 >> 0)

    prob.add_constraint(pic.trace(rho0) == 1)
    prob.add_constraint(pic.trace(rho1) == 1)

    if (rev == True):
        # TODO FBM: tests which conention is good.
        # TODO FBM: add reference to paper

        # This is convention REVERSED with respect to the paper,
        # and seems that this is a proper one????
        C0 = pic.kron(rho0, I)
        C1 = pic.kron(rho1, I)
    else:
        C0 = pic.kron(I, rho0)
        C1 = pic.kron(I, rho1)

    F = pic.trace((J.H) * X) + pic.trace(J * (X.H))

    prob.add_constraint(((C0 & X) // (X.H & C1)) >> 0)

    prob.set_objective('max', F)

    prob.solve(verbose=0)

    if prob.status.count("optimal") > 0:
        #        print('solution optimal')
        1
    elif (prob.status.count("optimal") == 0):
        print('uknown_if_solution_optimal')

    else:
        print('solution not found')

    cbt_norm = prob.obj_value() / 2

    if (abs(np.imag(cbt_norm)) >= 0.00001):
        raise ValueError
    else:
        cbt_norm = np.real(cbt_norm)

    return cbt_norm
Esempio n. 17
0
def f(rho1, sig2, beta=1, H1=[0, 1, 2], H2=[0, 1], cov=True, GP=True):
    ##   rho -> sigma under CPTP/ GP/ GPC/ Cov map?
    ##   output \approx 1 --> yes, output < 1 --> no.
    ##   dim(rho1) = dim(H1) = d1
    ##   dim(sig2) = dim(H2) = d2
    ##   default: qutrit-qubit CPG, equally-spaced energy levels, inv.temp=1
    d1 = len(H1)
    d2 = len(H2)
    id_d2 = pic.new_param('id_d2', np.eye(d2))

    ## def problem & variables ##
    p = pic.Problem()
    X1 = p.add_variable('X1', (d1, d1), 'hermitian')
    X2 = p.add_variable('X2', (d2, d2), 'hermitian')
    X3 = p.add_variable('X3', (d2, d2), 'hermitian')

    ## Gibbs-state:
    def g(x):
        return np.exp(-beta * x)

    exp_array1 = np.array(list(map(g, H1)))
    exp_array2 = np.array(list(map(g, H2)))
    gam1 = pic.diag(np.true_divide(exp_array1, np.sum(exp_array1)))
    gam2 = pic.diag(np.true_divide(exp_array2, np.sum(exp_array2)))
    #g2_0 = gam2[0].value

    ### constraints ###
    if GP == False:
        p.add_constraint((sig2 | X2) == 1)
        if cov == True:
            p.add_constraint(
                pic.kron(id_d2, X1) -
                dephase(pic.kron(X2, rho1), H1, H2) >> 0.)
        else:
            p.add_constraint(pic.kron(id_d2, X1) - pic.kron(X2, rho1) >> 0.)
    else:
        p.add_constraint((sig2 | X2) + (gam2 | X3) == 1)
        p.add_constraint(X3 >> 0)
        if cov == True:
            p.add_constraint(
                pic.kron(id_d2, X1) - dephase(pic.kron(X2, rho1), H1, H2) -
                pic.kron(X3, gam1) >> 0.)
        else:
            p.add_constraint(
                pic.kron(id_d2, X1) - pic.kron(X2, rho1) -
                pic.kron(X3, gam1) >> 0.)
    p.add_constraint(X1 >> 0)
    p.add_constraint(X2 >> 0)

    ### objective fn & solve ###
    p.set_objective('min', pic.trace(X1))
    p.solve(verbose=0, solver='cvxopt')
    return p.obj_value().real
Esempio n. 18
0
def ellipsoid_bounds(P):
    dimension = len(P)
    radius_dim = []
    for d in range(dimension):
        d_vec = []
        for temp in range(0, d):
            d_vec.append(0)
        d_vec.append(1)
        for temp in range(d, dimension - 1):
            d_vec.append(0)

        A = cvx.matrix(P)
        c = cvx.matrix([1])

        #create the problem, variables and params
        prob = pic.Problem()
        AA = cvx.sparse(A, tc='d')  #each AA[i].T is a 3 x 5 observation matrix

        AA = pic.new_param('A', AA)
        cc = pic.new_param('c', c)
        ss = pic.new_param('s', cvx.matrix(d_vec))

        x = prob.add_variable('x', AA.size[1])
        # mu = prob.add_variable('mu',1)

        #define the constraints and objective function
        prob.add_list_of_constraints(
            [x.T * AA * x < cc],  #constraints
        )

        prob.set_objective('max', ss | x)

        #solve the problem and retrieve the optimal weights of the optimal design.
        # print prob
        prob.solve(verbose=0, solver='cvxopt')
        x = x.value

        radius_dim.append(x[d])

    return radius_dim
Esempio n. 19
0
    def setUp(self):
        # Set the dimensionality.
        self.n = n = 4

        # Define parameters.
        ones = picos.new_param("ones", [1.0] * n)
        I = picos.diag(ones)

        # Primal problem.
        self.P = P = picos.Problem()
        self.x = x = P.add_variable("x", n)
        P.set_objective("max", 0.5 * x.T * I * x - (1 | x) - 0.5)
        P.add_constraint(0.5 * x.T * I * x + (0 | x) - 0.5 <= 0)
Esempio n. 20
0
File: maxcut.py Progetto: 84monta/OR
 def solve_picos(self):
     #http://www.orsj.or.jp/archive2/or63-12/or63_12_755.pdf
     #とけてるのかどうかわからん
     p = pic.Problem()
     X = p.add_variable('X', (self.n, self.n), 'symmetric')
     gL = nx.laplacian_matrix(self.G, weight='w', nodelist=self.G.nodes)
     gL = gL.toarray().astype(np.double)
     L = pic.new_param('L', 1 / 4 * gL)
     p.add_constraint(pic.diag_vect(X) == 1)
     p.add_constraint(X >> 0)
     p.set_objective('max', L | X)
     p.solve()
     print('bound from the SDP relaxation: {0}'.format(p.obj_value()))
def calc_update(graph):
    incidence = graph.incidence
    print(incidence)
    (n, l) = np.shape(incidence)
    sdp = pic.Problem()
    Xp = sdp.add_variable("X", (n, n), vtype = 'symmetric')
    a = 6
    degree = graph.degree()
    big_set_flags = (np.sum(incidence == 1, axis = 0) >= a*degree)
    coloring = np.asarray(np.random.rand(n))*0.4-0.2

    vs = [incidence[:, i] for i in range(l)]
    xs = [vs[i]*coloring for i in range(l)]
    vvs = [pic.new_param('vv'+str(i), np.outer(vs[i], vs[i])) for i in range(l)]
    iden = pic.new_param('I', np.identity(n))
    xxs = [pic.new_param('xx'+str(i), np.outer(xs[i], xs[i])) for i in range(l)]

    # print('vs =')
    # print(vs)
    # print('xs =')
    # print(xs)
    # print('vvs =')
    # print([np.outer(vs[i], vs[i]) -2*np.identity(n) for i in range(l)])
    # print('xxs =')
    # print([np.outer(xs[i], xs[i]) -2*np.identity(n) for i in range(l)])

    sdp.add_list_of_constraints([vvs[i] | Xp == 0 for i in range(l) if big_set_flags[i]])
    sdp.add_list_of_constraints([(vvs[i] - 2*iden) | Xp < 0 for i in range(l) if not big_set_flags[i]])
    sdp.add_list_of_constraints([(xxs[i] - 2*iden) | Xp < 0 for i in range(l) if not big_set_flags[i]])
    sdp.add_list_of_constraints([Xp[i, i] < 1 for i in range(n)])
    sdp.add_constraint(Xp >> 0)
    sdp.set_objective('max', pic.trace(Xp))
    sdp.solve()
    print(Xp.value)
    U = np.linalg.cholesky(Xp.value)
    print(U)
    
    return U, np.asarray(Xp.value)
Esempio n. 22
0
def cut(G):
    N = len(G.nodes())
    maxcut = pic.Problem()
    X = maxcut.add_variable('X', (N, N), 'symmetric')

    # objective
    L = pic.new_param('L', 1/4. * nx.laplacian_matrix(G).toarray())
    maxcut.set_objective('max', L | X)

    # constraints
    maxcut.add_constraint(pic.tools.diag_vect(X) == 1)
    maxcut.add_constraint(X >> 0)

    maxcut.solve(verbose=0)
    return random_projection(unified(X.value), L, maxcut.obj_value())
Esempio n. 23
0
def extendibility(rho, dim_A, dim_B, k=2, verbose=0):
    '''
    Checks if the state ρ is k-extendible.
    --------------------------------------
    Given an input state ρ ∈ 𝓗_A ⊗ 𝓗_B. Try to find an extension σ_AB_1..B_k ∈ 𝓗_A ⊗ 𝓗_B^(⊗k), such that (σ_AB)_i=ρ
    Not that the extensions are only the B-system.
    :param ρ: The state we want to check
    :param dim_A: Dimensions of system A
    :param dim_B: Dimensions of system B
    :param k: The extendibility order
    
    '''

    #Define variables, and create problem
    rho = picos.new_param('ρ', rho)
    problem = picos.Problem()

    sigma_AB = problem.add_variable(
        'σ_AB',
        (dim_A * binom(dim_B + k - 1, k), dim_A * binom(dim_B + k - 1, k)),
        'hermitian')
    #Set objective to a feasibility problem. The second argument is ignored by picos, so set some random scalar function.
    problem.set_objective('find', picos.trace(sigma_AB))

    #Add constrains
    problem.add_constraint(sigma_AB >> 0)
    problem.add_constraint(picos.trace(sigma_AB) == 1)
    problem.add_constraint(bose_trace(sigma_AB, dim_A, dim_B, k) == rho)

    print("\nChecking for %d extendibility..." % (k))

    #Solve the SDP either silently or verbose
    if verbose:
        try:
            print(problem)
            problem.solve(verbose=verbose, solver='mosek')
            print(problem.status)
            check_exstendibility(rho, sigma_AB, dim_A, dim_B,
                                 k)  #Run a solution check if the user wants
        except UnicodeEncodeError:
            print(
                "!!!Can't print the output due to your terminal not supporting unicode encoding!!!\nThis can be solved by setting verbose=0, or running the function using ipython instead."
            )
    else:
        problem.solve(verbose=verbose, solver='mosek')
        print(problem.status)
    return sigma_AB
Esempio n. 24
0
    def add_constraints(self, matrix, rhs_vector, equality_vector):
        """Adds to constraint to the problem using the matrix.

        Arguments
        ---------

        matrix: m x n constraint matrix, where n is the number of variables
                and m is the number of constraints
        rhs_vector: list of length m, the number of constraints,
        equality_vector: list of m integers. The number rel[i] defines the
                         relation, rel[i] < 0, rel[i] == 0, rel[i] > 0
                         gives the sign of the (in)equality

        sum(matrix[i][:]) <= rhs_vector[i], if equ_vector[i] < 0
        sum(matrix[i][:]) == rhs_vector[i], if equ_vector[i] = 0
        """

        num_equ, num_vars = matrix.size
        if not (num_equ == len(rhs_vector) == len(equality_vector)) or \
                num_equ == 0 or \
                num_vars != self.variables.size[0]:

            raise ValueError(
                'Dimensions do not match or are zero. '
                'A: %ix%i. b: %i. rel: %i' %
                (num_equ, num_vars, len(rhs_vector), len(equality_vector)))

        rhs_vector = pic.new_param('rhs_vec', rhs_vector)
        equality_vector = np.array(equality_vector)

        # get indices of ineqs and eqs
        inequality_idx = np.where(equality_vector)[0]
        equality_vector[inequality_idx] = 1
        equality_idx = np.where(1 - equality_vector)[0]

        # add lists of constraints

        self.pic_problem.add_list_of_constraints([
            matrix[int(idx), :] * self.variables == rhs_vector[int(idx)]
            for idx in equality_idx
        ])
        self.pic_problem.add_list_of_constraints([
            matrix[int(idx), :] * self.variables < rhs_vector[int(idx)]
            for idx in inequality_idx
        ])

        self.matrix = matrix[:]
Esempio n. 25
0
        Ms[i,j] = M[i,j] / p
      else:
        Ms[i,j] = 0
  return Ms

r = 4
k = 10
M = adv(r,k)
mu = r*k/3
print M
N1 = M.shape[0]
N2 = M.shape[1]
Ms = samp(M,11.0/N2)
print Ms

A = pic.new_param('A', Ms)
J = pic.new_param('J', np.ones(shape=(N1,N2)))
sdp = pic.Problem()
#M = sdp.add_variable('M',(N,N))
#W1 = sdp.add_variable('W1',(N,N),'symmetric')
#W2 = sdp.add_variable('W2',(N,N),'symmetric')
#sdp.add_constraint([[W1,M],[M.T,W2]]>>0)
U = sdp.add_variable('U',(N1+N2,N1+N2),'symmetric')
Mr = U[0:N1,N1:N1+N2]
W1 = U[0:N1,0:N1]
W2 = U[N1:N1+N2,N1:N1+N2]
sdp.add_constraint(U>>0)
sdp.add_constraint(Mr>0)
sdp.add_constraint(Mr<J)
sdp.set_objective('max', (A | Mr) - 0.5 * mu * (trace(W1)+trace(W2)))
print sdp
Esempio n. 26
0
      k = k - (r+1)
      r = r + 1

maxval = 0
for t in range(T):
  A = np.zeros(shape=(N,N))
  I = np.eye(N)
  for k in range(m):
    i,j = unpack(k)
    u = 2 * randint(0,1) - 1
    A[i,j] = u
    A[j,i] = u
  print ''
  print 'A:'
  print A
  A = pic.new_param('A', A)
  #J = pic.new_param('J', np.ones(shape=(N,N)))
  sdp = pic.Problem()
  P = sdp.add_variable('P',(N,N),'symmetric')
  sdp.add_constraint(P>>0)
  sdp.add_constraint(P<<I)
  sdp.set_objective('max', A | P)
  print sdp
  sdp.solve(verbose = 1, maxit=50)
  val = sdp.obj_value()
  print 'value: {0}'.format(val)

  solution = P.value
  np.set_printoptions(precision=3,threshold='nan',linewidth=1000,suppress=True)
  print 'solution:'
  print solution
Esempio n. 27
0
for i,e in enumerate(G.edges()):
        c[e]=((-2)**i)%17 #an arbitrary sequence of numbers


#-------------#
#   min cut   #
#-------------#

mincut=pic.Problem()

#source and sink nodes
s=16
t=10

#convert the capacities as a picos expression
cc=pic.new_param('c',c)

#cut variable
d={}
for e in G.edges():
        d[e]=mincut.add_variable('d[{0}]'.format(e),1)
        
#potentials
p=mincut.add_variable('p',N)

#potential inequality
mincut.add_list_of_constraints(
        [d[i,j] > p[i]-p[j]
        for (i,j) in G.edges()],        #list of constraints
        ['i','j'],'edges')              #indices and set they belong to
Esempio n. 28
0
print ''
N = A.shape[0]
if N != A.shape[1]:
  raise Exception('matrix is not square')
for i in range(N):
  for j in range(N):
    if random() < p:
      A[i,j] = A[i,j] / p
    else:
      A[i,j] = 0
print 'Ar:'
print A
print ''

I = np.eye(N)
A = pic.new_param('A', A)
J = pic.new_param('J', np.ones(shape=(N,N)))
sdp = pic.Problem()
#M = sdp.add_variable('M',(N,N))
#W1 = sdp.add_variable('W1',(N,N),'symmetric')
#W2 = sdp.add_variable('W2',(N,N),'symmetric')
#sdp.add_constraint([[W1,M],[M.T,W2]]>>0)
U = sdp.add_variable('U',(2*N,2*N),'symmetric')
M = U[0:N,N:2*N]
W1 = U[0:N,0:N]
W2 = U[N:2*N,N:2*N]
sdp.add_constraint(U>>0)
sdp.add_constraint(M>0)
sdp.add_constraint(M<J)
sdp.set_objective('max', (A | M) - mu * (trace(W1)+trace(W2)))
print sdp
Esempio n. 29
0
                [1 ,-5,-5]])

#size of the data
s = len(A)
m = A[0].size[0]
l = [ Ai.size[1] for Ai in A ]
r = K.size[1]

#creates a problem and the optimization variables
prob = pic.Problem()
mu = prob.add_variable('mu',s)
Z  = [prob.add_variable('Z[' + str(i) + ']', (l[i],r))
        for i in range(s)]

#convert the constants into params of the problem
A = pic.new_param('A',A)
K = pic.new_param('K',K)

#add the constraints
prob.add_constraint( pic.sum([ A[i]*Z[i] for i in range(s)], #summands
                                'i',                            #name of the index
                                '[s]'                           #set to which the index belongs
                                ) == K
                        )
prob.add_list_of_constraints( [ abs(Z[i]) < mu[i] for i in range(s)], #constraints
                                'i',                                    #index of the constraints
                                '[s]'                                   #set to which the index belongs
                                )

#sets the objective
prob.set_objective('min', 1 | mu ) # scalar product of the vector of all ones with mu
Esempio n. 30
0
M = 3

X = sdp.add_variable('X',(2*(M+N)+1,2*(M+N)+1),'symmetric')
sdp.add_constraint(X>>0)
sdp.add_constraint(X[0,0]<=1)
sdp.add_constraint(X>=0)
for i in range(N+M):
  sdp.add_constraint(X[i+1,i+1]==X[i+1,0])
  sdp.add_constraint(X[i+1,i+1]==X[i+1,i+N+M+1])
  sdp.add_constraint(X[i+N+M+1,i+N+M+1]==X[i+N+M+1,0])
for i in range(M):
  sdp.add_constraint(X[i+N+M+1,i+N+M+1]==1)
  for j in range(M,N+M):
    sdp.add_constraint(X[i+1,j+N+M+1]==0)
diagC = np.array([0] + [1] * M + [0]*(2*N+M))
C = pic.new_param('C',np.diag(diagC))
diagD = np.array([0] + [0] * M + [1] * N + [0] * (N+M))
D = pic.new_param('D',np.diag(diagD))
sdp.add_constraint(D|X >= 2);
sdp.set_objective('max', C | X)

print sdp
sdp.solve(verbose = 1, maxit=50)

print 'value: {0}'.format(sdp.obj_value())

solution = X.value

np.set_printoptions(precision=3,threshold='nan',linewidth=1000,suppress=True)
print 'solution:'
print np.array(solution)
Esempio n. 31
0
                [0,3,2,0,0],
                [1,0,0,2,0]])
  ]
  
c = cvx.matrix([1,2,3,4,5])

#create the problems

#--------------------------------------#
#         D-optimal design             #
#--------------------------------------#
prob_D = pic.Problem()
AA=[cvx.sparse(a,tc='d') for a in A]
s=len(AA)
m=AA[0].size[0]
AA=pic.new_param('A',AA)
mm=pic.new_param('m',m)
L=prob_D.add_variable('L',(m,m))
V=[prob_D.add_variable('V['+str(i)+']',AA[i].T.size) for i in range(s)]
w=prob_D.add_variable('w',s)
u={}
for k in ['01','23','4.','0123','4...','01234']:
        u[k] = prob_D.add_variable('u['+k+']',1)
prob_D.add_constraint(
                pic.sum([AA[i]*V[i]
                    for i in range(s)],'i','[s]')
                 == L)
#L lower inferior
prob_D.add_list_of_constraints( [L[i,j] == 0
                                for i in range(m)
                                for j in range(i+1,m)],['i','j'],'upper triangle')
Esempio n. 32
0
import cvxopt.lapack
import numpy as np

#make G undirected
G=nx.Graph(G)

#allocate weights to the edges
for (i,j) in G.edges():
        G[i][j]['weight']=c[i,j]+c[j,i]


maxcut = pic.Problem()
X=maxcut.add_variable('X',(N,N),'symmetric')

#Laplacian of the graph  
L=pic.new_param('L',1/4.*nx.laplacian(G))

#ones on the diagonal
maxcut.add_constraint(pic.tools.diag_vect(X)==1)
#X positive semidefinite
maxcut.add_constraint(X>>0)

#objective
maxcut.set_objective('max',L|X)

#print maxcut
maxcut.solve(verbose = 0)

#Cholesky factorization
V=X.value
Esempio n. 33
0
print minus

X = sdp.add_variable('X',(2*N+1,2*N+1),'symmetric')
sdp.add_constraint(X>>0)
sdp.add_constraint(X[2*N,2*N]<=1)
sdp.add_constraint(X>=0)
for i in range(N):
  sdp.add_constraint(X[i,i]==X[i,2*N])
  sdp.add_constraint(X[i,i]==X[i,i+N])
  sdp.add_constraint(X[i+N,i+N]==X[i+N,2*N])
for (i,j) in plus:
  sdp.add_constraint(X[i,i]==X[i,j+N])
for (i,j) in minus:
  sdp.add_constraint(X[i,j+N]==0)
diag = np.array([1]*N + [0]*(N+1))
C = pic.new_param('C',np.diag(diag))
print X
print C
sdp.set_objective('max', C | X)

print sdp
sdp.solve(verbose = 1, maxit=50)

print 'value: {0}'.format(sdp.obj_value())

solution = X.value

np.set_printoptions(precision=2,threshold='nan',linewidth=1000,suppress=True)
print 'solution:'
print np.array(solution)
Esempio n. 34
0
                [1 ,-5,-5]])

#size of the data
s = len(A)
m = A[0].size[0]
l = [ Ai.size[1] for Ai in A ]
r = K.size[1]

#creates a problem and the optimization variables
prob = pic.Problem()
mu = prob.add_variable('mu',s)
Z  = [prob.add_variable('Z[' + str(i) + ']', (l[i],r))
      for i in range(s)]

#convert the constants into params of the problem
A = pic.new_param('A',A)
K = pic.new_param('K',K)

#add the constraints
prob.add_constraint( pic.sum([ A[i]*Z[i] for i in range(s)], #summands
                            'i',                            #name of the index
                            '[s]'                           #set to which the index belongs
                           ) == K
                   )
prob.add_list_of_constraints( [ abs(Z[i]) < mu[i] for i in range(s)], #constraints
                              'i',                                    #index of the constraints
                              '[s]'                                   #set to which the index belongs
                            )

#sets the objective
prob.set_objective('min', 1 | mu ) # scalar product of the vector of all ones with mu