Пример #1
0
def solve_sdp_program(W):
    assert W.ndim == 2
    assert W.shape[0] == W.shape[1]
    W = W.copy()
    n = W.shape[0]
    W = expand_matrix(W)
    with Model('gw_max_3_cut') as M:
        W = Matrix.dense(W / 3.)
        J = Matrix.ones(3*n, 3*n)
        # variable
        Y = M.variable('Y', Domain.inPSDCone(3*n))
        # objective function
        M.objective(ObjectiveSense.Maximize, Expr.dot(W, Expr.sub(J, Y)))
        # constraints
        for i in range(3*n):
            M.constraint(f'c_{i}{i}', Y.index(i, i), Domain.equalsTo(1.))
        for i in range(n):
            M.constraint(f'c_{i}^01', Y.index(i*3,   i*3+1), Domain.equalsTo(-1/2.))
            M.constraint(f'c_{i}^02', Y.index(i*3,   i*3+2), Domain.equalsTo(-1/2.))
            M.constraint(f'c_{i}^12', Y.index(i*3+1, i*3+2), Domain.equalsTo(-1/2.))
            for j in range(i+1, n):
                for a, b in product(range(3), repeat=2):
                    M.constraint(f'c_{i}{j}^{a}{b}-0', Y.index(i*3 + a, j*3 + b), Domain.greaterThan(-1/2.))
                    M.constraint(f'c_{i}{j}^{a}{b}-1', Expr.sub(Y.index(i*3 + a, j*3 + b), Y.index(i*3 + (a + 1) % 3, j*3 + (b + 1) % 3)), Domain.equalsTo(0.))
                    M.constraint(f'c_{i}{j}^{a}{b}-2', Expr.sub(Y.index(i*3 + a, j*3 + b), Y.index(i*3 + (a + 2) % 3, j*3 + (b + 2) % 3)), Domain.equalsTo(0.))
        # solution
        M.solve()
        Y_opt = Y.level()
    return np.reshape(Y_opt, (3*n,3*n))
Пример #2
0
def minimum_variance(matrix):
    # Given the matrix of returns a (each column is a series of returns) this method
    # computes the weights for a minimum variance portfolio, e.g.

    # min   2-Norm[a*w]^2
    # s.t.
    #         w >= 0
    #     sum[w] = 1

    # This is the left-most point on the efficiency frontier in the classic Markowitz theory

    # build the model
    with Model("Minimum Variance") as model:
        # introduce the weight variable

        weights = model.variable("weights", matrix.shape[1],
                                 Domain.inRange(0.0, 1.0))
        # sum of weights has to be 1
        model.constraint(Expr.sum(weights), Domain.equalsTo(1.0))
        # returns
        r = Expr.mul(Matrix.dense(matrix), weights)
        # compute l2_norm squared of those returns
        # minimize this l2_norm
        model.objective(ObjectiveSense.Minimize,
                        __l2_norm_squared(model, "2-norm^2(r)", expr=r))
        # solve the problem
        model.solve()
        # return the series of weights
        return np.array(weights.level())
Пример #3
0
def minimum_variance(matrix):
    # Given the matrix of returns a (each column is a series of returns) this method
    # computes the weights for a minimum variance portfolio, e.g.

    # min   2-Norm[a*w]^2
    # s.t.
    #         w >= 0
    #     sum[w] = 1

    # This is the left-most point on the efficiency frontier in the classic Markowitz theory

    # build the model
    with Model("Minimum Variance") as model:
        # introduce the weight variable

        weights = model.variable("weights", matrix.shape[1], Domain.inRange(0.0, 1.0))
        # sum of weights has to be 1
        model.constraint(Expr.sum(weights), Domain.equalsTo(1.0))
        # returns
        r = Expr.mul(Matrix.dense(matrix), weights)
        # compute l2_norm squared of those returns
        # minimize this l2_norm
        model.objective(ObjectiveSense.Minimize, __l2_norm_squared(model, "2-norm^2(r)", expr=r))
        # solve the problem
        model.solve()
        # return the series of weights
        return np.array(weights.level())
Пример #4
0
def solve_sdp_program(A):
    assert A.ndim == 2
    assert A.shape[0] == A.shape[1]
    A = A.copy()
    n = A.shape[0]
    with Model('theta_1') as M:
        A = Matrix.dense(A)
        # variable
        X = M.variable('X', Domain.inPSDCone(n))
        # objective function
        M.objective(ObjectiveSense.Maximize,
                    Expr.sum(Expr.dot(Matrix.ones(n, n), X)))
        # constraints
        M.constraint(f'c1', Expr.sum(Expr.dot(X, A)), Domain.equalsTo(0.))
        M.constraint(f'c2', Expr.sum(Expr.dot(X, Matrix.eye(n))),
                     Domain.equalsTo(1.))
        # solution
        M.solve()
        sol = X.level()
    return sum(sol)
Пример #5
0
def solve_sdp_program(W):
    assert W.ndim == 2
    assert W.shape[0] == W.shape[1]
    W = W.copy()
    n = W.shape[0]
    with Model('gw_max_cut') as M:
        W = Matrix.dense(W / 4.)
        J = Matrix.ones(n, n)
        # variable
        Y = M.variable('Y', Domain.inPSDCone(n))
        # objective function
        M.objective(ObjectiveSense.Maximize, Expr.dot(W, Expr.sub(J, Y)))
        # constraints
        for i in range(n):
            M.constraint(f'c_{i}', Y.index(i, i), Domain.equalsTo(1.))
        # solve
        M.solve()
        # solution
        Y_opt = Y.level()
    return np.reshape(Y_opt, (n, n))
Пример #6
0
def solve_sdp_program(W, k):
    assert W.ndim == 2
    assert W.shape[0] == W.shape[1]
    W = W.copy()
    n = W.shape[0]
    with Model('fj_max_k_cut') as M:
        W = Matrix.dense((k - 1) / (2 * k) * W)
        J = Matrix.ones(n, n)
        # variable
        Y = M.variable('Y', Domain.inPSDCone(n))
        # objective function
        M.objective(ObjectiveSense.Maximize, Expr.dot(W, Expr.sub(J, Y)))
        # constraints
        for i in range(n):
            M.constraint(f'c_{i}', Y.index(i, i), Domain.equalsTo(1.))
            for j in range(i + 1, n):
                M.constraint(f'c_{i},{j}', Y.index(i, j),
                             Domain.greaterThan(-1 / (k - 1)))
        # solution
        M.solve()
        Y_opt = Y.level()
    return np.reshape(Y_opt, (n, n))
Пример #7
0
    def __init__(self,name, 
                 foods, 
                 nutrients,
                 daily_allowance,
                 nutritive_value):
        Model.__init__(self,name)
        finished = False
        try:
          self.foods     = [ str(f) for f in foods ]
          self.nutrients = [ str(n) for n in nutrients ]
          self.dailyAllowance = numpy.array(daily_allowance, float)
          self.nutrientValue = Matrix.dense(nutritive_value).transpose()

          M = len(self.foods)
          N = len(self.nutrients)
          if len(self.dailyAllowance) != N:
              raise ValueError("Length of daily_allowance does not match "
                               "the number of nutrients")
          if self.nutrientValue.numColumns() != M:
              raise ValueError("Number of rows in nutrient_value does not "
                               "match the number of foods")
          if self.nutrientValue.numRows() != N:
              raise ValueError("Number of columns in nutrient_value does "
                               "not match the number of nutrients")
          
          self.__dailyPurchase = self.variable('Daily Purchase', 
                                               StringSet(self.foods), 
                                               Domain.greaterThan(0.0))
          self.__dailyNutrients = \
              self.constraint('Nutrient Balance',
                              StringSet(nutrients),
                              Expr.mul(self.nutrientValue,self.__dailyPurchase),
                              Domain.greaterThan(self.dailyAllowance))
          self.objective(ObjectiveSense.Minimize, Expr.sum(self.__dailyPurchase))
          finished = True
        finally:
          if not finished:
            self.__del__()
Пример #8
0
def __mat_vec_prod(matrix, expr):
    return Expr.mul(Matrix.dense(matrix), expr)
Пример #9
0
def __mat_vec_prod(matrix, expr):
    return Expr.mul(Matrix.dense(matrix), expr)
Пример #10
0
    def Build_Co_Model(self):
        r = len(self.roads)
        mu, sigma = self.mu, self.sigma
        m, n, r = self.m, self.n, len(self.roads)
        f, h = self.f, self.h
        M, N = m + n + r, 2 * m + 2 * n + r
        A = self.__Construct_A_Matrix()
        A_Mat = Matrix.dense(A)
        b = self.__Construct_b_vector()

        # ---- build Mosek Model
        COModel = Model()

        # -- Decision Variable
        Z = COModel.variable('Z', m, Domain.inRange(0.0, 1.0))
        I = COModel.variable('I', m, Domain.greaterThan(0.0))
        Alpha = COModel.variable('Alpha', M,
                                 Domain.unbounded())  # M by 1 vector
        Beta = COModel.variable('Beta', M, Domain.unbounded())  # M by 1 vector
        Theta = COModel.variable('Theta', N,
                                 Domain.unbounded())  # N by 1 vector
        # M1_matrix related decision variables
        '''
            [tau, xi^T, phi^T
        M1 = xi, eta,   psi^t
             phi, psi,   w  ]
        '''
        # no-need speedup variables
        Psi = COModel.variable('Psi', [N, n], Domain.unbounded())
        Xi = COModel.variable('Xi', n, Domain.unbounded())  # n by 1 vector
        Phi = COModel.variable('Phi', N, Domain.unbounded())  # N by 1 vector
        # has the potential to speedup
        Tau, Eta, W = self.__Declare_SpeedUp_Vars(COModel)

        # M2 matrix decision variables
        '''
            [a, b^T, c^T
        M2 = b, e,   d^t
             c, d,   f  ]
        '''
        a_M2 = COModel.variable('a_M2', 1, Domain.greaterThan(0.0))
        b_M2 = COModel.variable('b_M2', n, Domain.greaterThan(0.0))
        c_M2 = COModel.variable('c_M2', N, Domain.greaterThan(0.0))
        e_M2 = COModel.variable('e_M2', [n, n], Domain.greaterThan(0.0))
        d_M2 = COModel.variable('d_M2', [N, n], Domain.greaterThan(0.0))
        f_M2 = COModel.variable('f_M2', [N, N], Domain.greaterThan(0.0))

        # -- Objective Function
        obj_1 = Expr.dot(f, Z)
        obj_2 = Expr.dot(h, I)
        obj_3 = Expr.dot(b, Alpha)
        obj_4 = Expr.dot(b, Beta)
        obj_5 = Expr.dot([1], Expr.add(Tau, a_M2))
        obj_6 = Expr.dot([2 * mean for mean in mu], Expr.add(Xi, b_M2))
        obj_7 = Expr.dot(sigma, Expr.add(Eta, e_M2))
        COModel.objective(
            ObjectiveSense.Minimize,
            Expr.add([obj_1, obj_2, obj_3, obj_4, obj_5, obj_6, obj_7]))

        # Constraint 1
        _expr = Expr.sub(Expr.mul(A_Mat.transpose(), Alpha), Theta)
        _expr = Expr.sub(_expr, Expr.mul(2, Expr.add(Phi, c_M2)))
        _expr_rhs = Expr.vstack(Expr.constTerm([0.0] * n), Expr.mul(-1, I),
                                Expr.constTerm([0.0] * M))
        COModel.constraint('constr1', Expr.sub(_expr, _expr_rhs),
                           Domain.equalsTo(0.0))
        del _expr, _expr_rhs

        # Constraint 2
        _first_term = Expr.add([
            Expr.mul(Beta.index(row),
                     np.outer(A[row], A[row]).tolist()) for row in range(M)
        ])
        _second_term = Expr.add([
            Expr.mul(Theta.index(k), Matrix.sparse(N, N, [k], [k], [1]))
            for k in range(N)
        ])
        _third_term = Expr.add(W, f_M2)
        _expr = Expr.sub(Expr.add(_first_term, _second_term), _third_term)
        COModel.constraint('constr2', _expr, Domain.equalsTo(0.0))
        del _expr, _first_term, _second_term, _third_term

        # Constraint 3
        _expr = Expr.mul(-2, Expr.add(Psi, d_M2))
        _expr_rhs = Matrix.sparse([[Matrix.eye(n)], [Matrix.sparse(N - n, n)]])
        COModel.constraint('constr3', Expr.sub(_expr, _expr_rhs),
                           Domain.equalsTo(0))
        del _expr, _expr_rhs

        # Constraint 4: I <= M*Z
        COModel.constraint('constr4', Expr.sub(Expr.mul(20000.0, Z), I),
                           Domain.greaterThan(0.0))

        # Constraint 5: M1 is SDP
        COModel.constraint(
            'constr5',
            Expr.vstack(Expr.hstack(Tau, Xi.transpose(), Phi.transpose()),
                        Expr.hstack(Xi, Eta, Psi.transpose()),
                        Expr.hstack(Phi, Psi, W)), Domain.inPSDCone(1 + n + N))

        return COModel