Exemplo n.º 1
0
def markowitz_optimizer(mu, sigma, lam=1):
    '''
    Implementation of a long only mean-variance optimizer
        based on Markowitz's Portfolio
    Construction method:

    https://en.wikipedia.org/wiki/Modern_portfolio_theory

    This function relies on cvxpy.

    Argument Definitions:
    mu    -- 1xn numpy array of expected asset returns
    sigma -- nxn covariance matrix between asset return time series
    lam   -- optional risk tolerance parameter

    Argument Constraints:
    mu    -- expected return bector
    sigma -- positive semidefinite symmetric matrix
    lam   -- any non-negative float
    '''

    # define variable of weights to be solved for by optimizer
    x = Variable(len(sigma))
    # define Markowitz mean/variance objective function
    objective = Minimize(quad_form(x, sigma) - lam * mu * x)
    constraints = [sum_entries(x) == 1, x >= 0]  # define long only constraint
    p = Problem(objective, constraints)  # create optimization problem
    L = p.solve()  # solve problem
    return np.array(x.value).flatten()  # return optimal weights
Exemplo n.º 2
0
    def as_constraint(self, **kwargs):
        """
        given an adjacency matrix,


        WH = max{wA + wB , wC + wD }(max{hA , hB } + max{hC , hD }).

        Take max of all possible chains left-right
        * max of all possible chains up-down

        number of chains in any direction is (box_dim /min_unit_dim)!
        """
        X, Y, W, H = self.inputs.vars
        num_children = len(self.inputs)
        A = Variable(shape=num_children, boolean=True)
        C = []

        def constraint_node(wi, wj, hi, hj):
            wa = Variable(pos=True)
            ha = Variable(pos=True)
            ha = Variable(pos=True)
            c = [
                wa <= wi + wj,
                ha <= cvx.max(hi + hj),
            ]

            return

        return
Exemplo n.º 3
0
 def as_constraint(self, **kwargs):
     X, Y, W, H = self.inputs.vars
     n = self.mat.shape[0]
     theta_ij = Variable()
     for r, (i, j) in enumerate(zip(*np.triu_indices(n, 1))):
         pass
     return
Exemplo n.º 4
0
    def __scratch(self):
        """

        """
        s0 = self._init_a_tree()
        num_nodes = len(s0)
        X = Variable(shape=(num_nodes, 3), pos=True)
Exemplo n.º 5
0
 def __init__(self, name, c, A, b, dims):
     logging.info(name + " started")
     logging.info(name + "'s dims = " + str(dims))
     self.name = name
     _, n = np.shape(A)
     self.n = n
     self.dims = dims
     self.xbar = Parameter(n, value=np.zeros(n))
     self.xbar_old = Parameter(n, value=np.zeros(n))
     self.u = Parameter(n, value=np.zeros(n))
     self.x = Variable(n)
     self.c = c
     self.A = A
     self.b = b
     self.f = self.c.T @ self.x
     self.rho = constants.RHO
     self.f += (self.rho /
                2) * sum_squares(self.x[self.dims] - self.xbar[self.dims] +
                                 self.u[self.dims])
     logging.info(name + "'s f = " + str(self.f))
     self.prox = Problem(Minimize(self.f),
                         [self.A @ self.x == self.b, self.x >= 0])
     self.history = {
         'objval': [],
         'r_norm': [],
         'eps_pri': [],
         's_norm': [],
         'eps_dual': [],
         'iter': []
     }
     self.has_converged = False
     self.k = 0
Exemplo n.º 6
0
def dgp():
    # DGP requires Variables to be declared positive via `pos=True`.
    x = Variable(pos=True)
    y = Variable(pos=True)
    z = Variable(pos=True)

    objective_fn = x * y * z
    constraints = [
        4 * x * y * z + 2 * x * z <= 10, x <= 2 * y, y <= 2 * x, z >= 1
    ]
    problem = Problem(Maximize(objective_fn), constraints)
    problem.solve(gp=True)
    print("Optimal value: ", problem.value)
    print("x: ", x.value)
    print("y: ", y.value)
    print("z: ", z.value)
def MarkowitzOpt(mean, variance, covariance, interest_rate, min_return):
    n = mean.size + 1                   # Number of assets (number of stocks + interest rate)
    
    mu = mean.values                    # Mean returns of n assets
    temp = np.full(n, interest_rate)
    temp[:-1] = mu
    mu = temp
        
    counter = 0
    Sigma = np.zeros((n,n))                 # Covariance of n assets
    for i in np.arange(n-1):
        for j in np.arange(i, n-1):
            if i==j:
                Sigma[i,j] = variance[i]
            else:
                Sigma[i,j] = covariance[counter]
                Sigma[j,i] = Sigma[i,j]
                counter+=1
    Sigma = nearestPD(Sigma)                # Converting covariance to the nearest positive-definite matrix
    
    # Ensuring feasability of inequality contraint
    if mu.max() < min_return:
        min_return = interest_rate
    
    w = Variable(n)                         # Portfolio allocation vector
    ret = mu.T*	w
    risk = quad_form(w, Sigma)
    min_ret = Parameter(nonneg=True)
    min_ret.value = min_return
    prob = Problem(Minimize(risk),          # Restricting to long-only portfolio
                   [ret >= min_ret,
                   sum(w) == 1,
                   w >= 0])
    prob.solve()
    return w.value
Exemplo n.º 8
0
    def add_stability_constraint(self,
                                 aff_lyap,
                                 comp=None,
                                 slacked=False,
                                 coeff=0):
        """Add Lyapunov function derivative constraint

        Inputs:
        Affine Lyapunov function: AffineDynamics, ScalarDynamics
        Class-K comparison function, comp: float -> float
        Flag for slacking constraint, slacked: bool
        Coefficient for slack variable in cost function, coeff: float
        """

        if comp is None:
            comp = lambda r: 0
        if slacked:
            delta = Variable()
            self.variables.append(delta)
            self.static_costs.append(coeff * square(delta))
            constraint = lambda x, t: aff_lyap.drift(x, t) + aff_lyap.act(
                x, t) * self.u <= -comp(aff_lyap.eval(x, t)) + delta
        else:
            constraint = lambda x, t: aff_lyap.drift(x, t) + aff_lyap.act(
                x, t) * self.u <= -comp(aff_lyap.eval(x, t))
        self.constraints.append(constraint)
Exemplo n.º 9
0
def cvxpy_solve_qp(P,
                   q,
                   G=None,
                   h=None,
                   A=None,
                   b=None,
                   initvals=None,
                   solver=None):
    """
    Solve a Quadratic Program defined as:

        minimize
            (1/2) * x.T * P * x + q.T * x

        subject to
            G * x <= h
            A * x == b

    calling a given solver using the CVXPY <http://www.cvxpy.org/> modelling
    language.

    Parameters
    ----------
    P : array, shape=(n, n)
        Primal quadratic cost matrix.
    q : array, shape=(n,)
        Primal quadratic cost vector.
    G : array, shape=(m, n)
        Linear inequality constraint matrix.
    h : array, shape=(m,)
        Linear inequality constraint vector.
    A : array, shape=(meq, n), optional
        Linear equality constraint matrix.
    b : array, shape=(meq,), optional
        Linear equality constraint vector.
    initvals : array, shape=(n,), optional
        Warm-start guess vector (not used).
    solver : string, optional
        Solver name in ``cvxpy.installed_solvers()``.

    Returns
    -------
    x : array, shape=(n,)
        Solution to the QP, if found, otherwise ``None``.
    """
    if initvals is not None:
        print("CVXPY: note that warm-start values are ignored by wrapper")
    n = q.shape[0]
    x = Variable(n)
    P = Constant(P)  # see http://www.cvxpy.org/en/latest/faq/
    objective = Minimize(0.5 * quad_form(x, P) + q * x)
    constraints = []
    if G is not None:
        constraints.append(G * x <= h)
    if A is not None:
        constraints.append(A * x == b)
    prob = Problem(objective, constraints)
    prob.solve(solver=solver)
    x_opt = array(x.value).reshape((n, ))
    return x_opt
Exemplo n.º 10
0
def mpt_opt(data, gamma_vec):
    NUM_SAMPLES = len(gamma_vec)
    w_vec_results = [None] * NUM_SAMPLES
    ret_results = np.zeros(NUM_SAMPLES)
    risk_results = np.zeros(NUM_SAMPLES)

    N = len(data)
    w_vec = Variable(N)
    mu_vec = np.array([np.mean(data[i]) for i in range(N)])
    sigma_mat = np.cov(data)

    gamma = Parameter(nonneg=True)

    ret_val = mu_vec.T * w_vec
    risk_val = quad_form(w_vec, sigma_mat)  # w^T Sigma w
    problem = Problem(Maximize(ret_val - gamma * risk_val),
                      [sum(w_vec) == 1, w_vec >= 0])

    for i, new_gamma in enumerate(gamma_vec):
        gamma.value = new_gamma
        problem.solve()
        w_vec_results[i] = w_vec.value
        ret_results[i] = ret_val.value
        risk_results[i] = sqrt(risk_val).value

    return (w_vec_results, ret_results, risk_results)
Exemplo n.º 11
0
def ForceCanBeCounteractedByAccelerationVector(dt, Fp, u1min, u1max, u2min, u2max, plot=False) :

        ### question (1) : can we produce an acceleration ddW, such that it counteracts F?

        ## dynamics projected onto identity element, it becomes obvious that in an infinitesimal neighborhood, 
        ## we can only counteract forces along the x and the theta axes due to non-holonomicity

        dt2 = dt*dt/2

        ## span dt2-hyperball in Ndim
        F = dt2*Fp
        thetamin = dt2*u2min
        thetamax = dt2*u2max
        xmin = 0.0
        xmax = dt2*u1max

        Xlow = np.dot(np.dot(Rz(-pi/2),Rz(thetamin)),np.array((1,0,0)))
        Xhigh = np.dot(np.dot(Rz(pi/2),Rz(thetamax)),np.array((1,0,0)))

        Ndim = Fp.shape[0]
        if Fp.ndim <= 1:
                Nsamples = 1
        else:
                Nsamples = Fp.shape[1]
        p = Variable(3,Nsamples)

        constraints = []
        objfunc = 0.0
        for i in range(0,Nsamples):
                constraints.append( norm(p[:,i]) <= xmax )
                constraints.append( np.matrix(Xlow[0:3])*p[:,i] <= 0 )
                constraints.append( np.matrix(Xhigh[0:3])*p[:,i] <= 0 )
                if Fp.ndim <= 1:
                        objfunc += norm(p[:,i]-F[0:3])
                else:
                        objfunc += norm(p[:,i]-F[0:3,i])
                #objfunc.append(norm(p[:,i]-F[:,i]))

        objective = Minimize(objfunc)
        prob = Problem(objective, constraints)

        result = prob.solve(solver=SCS, eps=1e-7)

        #nearest_ddq = np.array(p.value)
        nearest_ddq = np.array(p.value/dt2)

        codimension = Ndim-nearest_ddq.shape[0]

        #print Ndim, nearest_ddq.shape
        #print codimension
        zero_rows = np.zeros((codimension,Nsamples))

        if nearest_ddq.shape[0] < Ndim:
                nearest_ddq = np.vstack((nearest_ddq,zero_rows))

        if plot:
                PlotReachableSetForceDistance(dt, u1min, u1max, u2min, u2max, -F, dt2*nearest_ddq)

        return nearest_ddq
Exemplo n.º 12
0
def cvxpy_solve_qp(P, q, G=None, h=None, A=None, b=None, initvals=None,
                   solver=None, verbose=False):
    """
    Solve a Quadratic Program defined as:

    .. math::

        \\begin{split}\\begin{array}{ll}
        \\mbox{minimize} &
            \\frac{1}{2} x^T P x + q^T x \\\\
        \\mbox{subject to}
            & G x \\leq h                \\\\
            & A x = h
        \\end{array}\\end{split}

    calling a given solver using the `CVXPY <http://www.cvxpy.org/>`_ modelling
    language.

    Parameters
    ----------
    P : array, shape=(n, n)
        Primal quadratic cost matrix.
    q : array, shape=(n,)
        Primal quadratic cost vector.
    G : array, shape=(m, n)
        Linear inequality constraint matrix.
    h : array, shape=(m,)
        Linear inequality constraint vector.
    A : array, shape=(meq, n), optional
        Linear equality constraint matrix.
    b : array, shape=(meq,), optional
        Linear equality constraint vector.
    initvals : array, shape=(n,), optional
        Warm-start guess vector (not used).
    solver : string, optional
        Solver name in ``cvxpy.installed_solvers()``.
    verbose : bool, optional
        Set to `True` to print out extra information.

    Returns
    -------
    x : array, shape=(n,)
        Solution to the QP, if found, otherwise ``None``.
    """
    if initvals is not None:
        print("CVXPY: note that warm-start values are ignored by wrapper")
    n = q.shape[0]
    x = Variable(n)
    P = Constant(P)  # see http://www.cvxpy.org/en/latest/faq/
    objective = Minimize(0.5 * quad_form(x, P) + q * x)
    constraints = []
    if G is not None:
        constraints.append(G * x <= h)
    if A is not None:
        constraints.append(A * x == b)
    prob = Problem(objective, constraints)
    prob.solve(solver=solver, verbose=verbose)
    x_opt = array(x.value).reshape((n,))
    return x_opt
Exemplo n.º 13
0
    def test_svc(self):
        n = 2
        m = 100
        shift = 10

        # Generate data.
        X = np.random.normal(0, 5, size=(m, n))
        y = np.ones(m)
        y[:int(m / 2)] = -1
        X[y == 1, :] = X[y == 1, :] + shift

        # Support vector classifier with bound on number of misclassifications.
        beta0 = Variable()
        beta = Variable(n)
        obj = norm(beta)
        projection = multiply(y, X * beta + beta0)
        bound = 1 - self.tolerance
        constr = [prob(projection <= bound) <= 0.1]
        p = Problem(Minimize(obj), constr)
        p.solve()

        print("Objective:", p.value)
        print("Fraction misclassified:", np.mean(projection.value <= bound))

        # Scatter plot of results.
        hpos = plt.scatter(X[y == +1, 0], X[y == +1, 1], color="blue")
        hneg = plt.scatter(X[y == -1, 0], X[y == -1, 1], color="red")
        wrong_pos = np.logical_and(projection.value <= bound, y == +1)
        wrong_neg = np.logical_and(projection.value <= bound, y == -1)
        plt.scatter(X[wrong_pos, 0],
                    X[wrong_pos, 1],
                    color="white",
                    edgecolor="blue")
        plt.scatter(X[wrong_neg, 0],
                    X[wrong_neg, 1],
                    color="white",
                    edgecolor="red")
        plt.legend([hpos, hneg], ["$y = +1$", "$y = -1$"])

        # Plot supporting hyperplane and margins.
        slope = -beta[0].value / beta[1].value
        intercept = -beta0.value / beta[1].value
        margin = 1 / beta[1].value
        self.plot_abline(slope, intercept, color="grey")
        self.plot_abline(slope, intercept + margin, "--", color="grey")
        self.plot_abline(slope, intercept - margin, "--", color="grey")
Exemplo n.º 14
0
 def __init__(self, inputs, values, **kwargs):
     """ THis may be more efficent in the discrete space,
         as with fixed dimensions, this becomes
         sum(edge_i @ X) == min_dim
     """
     MIPConstraint.__init__(self, inputs, **kwargs)
     self._choices = values
     self._internal_vars = Variable(shape=(4, len(inputs)), boolean=True)
Exemplo n.º 15
0
 def __init__(self, *args, n_colors=0, **kwargs):
     _VarGraphBase.__init__(self)
     Mesh2d.HalfEdge.__init__(self, *args, **kwargs)
     self.X = Variable(n_colors,
                       boolean=True,
                       name='hedg.{}'.format(self.index))
     self._map = dict()
     self._hard_map = dict()
Exemplo n.º 16
0
def test_boolean():
    """Test boolean variable."""
    x = Variable((5, 4))
    y = Boolean((5, 4))
    p = Problem(Minimize(sum(1 - x) + sum(x)), [x == y])
    result = p.solve(**solve_args)
    assert result[0] == approx(20)
    for v in np.nditer(x.value):
        assert v * (1 - v) == approx(0)

    # This time test a scalar variable, while restricting to a single entry
    # of a Boolean matrix.
    x = Variable()
    p = Problem(Minimize(sum(1 - x) + sum(x)), [x == Boolean((5, 4))[0, 0]])
    result = p.solve(**solve_args)
    assert result[0] == approx(1)
    assert x.value * (1 - x.value) == approx(0)
Exemplo n.º 17
0
def calc_Koopman(Yf,Yp,flag=1,lambda_val=0.0):
    #solver_instance = cvxpy.CVXOPT;
    solver_instance = cvxpy.SCS;
    if flag==1: # moore penrose inverse, plain ol' least squares Koopman
        #Yp_inv = np.dot(np.transpose(Yp_final), np.linalg.inv( np.dot(Yp_final,np.transpose(Yp_final)) )   );
        Yp_inv = np.linalg.pinv(Yp);
        K = np.dot(Yf,Yp_inv);
        

    if flag ==2: # cvx optimization approach - L2 + L1 lasso 
        norm1_term = 0.0;
        all_col_handles = [None]*Yf.shape[0]
        for i in range(0,Yf.shape[0]):            
            all_col_handles[i] = Variable(shape=(Yf.shape[0],1)) ;#Variable(shape=(Yf.shape[0],1) );
        #    if norm1_term < cvxpy.norm(all_col_handles[i],p=1):
        #        norm1_term = cvxpy.norm(all_col_handles[i],p=1);
            #norm1_term =  cvxpy.max(cvxpy.hstack( [norm1_term,cvxpy.norm(all_col_handles[i],p=1) ])  );
        operator = cvxpy.hstack(all_col_handles);
        norm1_term =cvxpy.norm( operator,p=1);
        #operator = all_col_handles[0];
        #for i in range(1,Yf.shape[0]):
        #    operator = cvxpy.hstack([operator,all_col_handles[i]]);
        #operator.
        #print("[INFO]: CVXPY Koopman operator variable: " +repr(operator.shape));
        #print(repr(operator));
        #print("[INFO]: Yf.shape in calc_Koopman: " + repr(Yf.shape));
        #print("[INFO]: Yp.shape in calc_Koopman: " + repr(Yp.shape));
        norm2_fit_term = cvxpy.norm(cvxpy.norm(Yf-operator*Yp,p=2,axis=0),p=2);
        objective = Minimize(norm2_fit_term + lambda_val*norm1_term)
        constraints = [];
        prob = Problem(objective,constraints);
        result = prob.solve(verbose=True,solver=solver_instance,max_iters=np.int(1e7))#,reltol=1e-10,abstol=1e-10);
        print("[INFO]: Finished executing cvx solver, printing CVXPY problem status")
        print(prob.status);
        K = operator.value;

    if flag ==3:
        operator = Variable((Yf.shape[0],Yf.shape[0]))
        objective = Minimize(cvxpynorm(operator,2))
        constraints = [cvxpynorm(Yf-operator*Yp,'fro')/cvxpynorm(Yf,'fro')<0.01 ]
        prob = Problem(objective, constraints)
        result = prob.solve(verbose=True)#(solver=solver_instance);
        print(prob.status);
        K = operator.value;

    return K;
Exemplo n.º 18
0
 def test_permutation(self):
     x = Variable(1, 5)
     c = cvxopt.matrix([1, 2, 3, 4, 5]).T
     perm = Assign(5, 5)
     p = Problem(Minimize(sum(x)), [x == c * perm])
     result = p.solve(method="admm")
     self.assertAlmostEqual(result, 15)
     self.assertAlmostEqual(sorted(np.nditer(x.value)), c)
Exemplo n.º 19
0
    def as_constraint(self, **kwargs):
        """
        l_i < h/w < u_i
        s_max = max(h,w)
        s_min = min(h,w)

        s_min = s_max / B
        s_max = s_min * B
        A = s_max  * s_min
        sqrt(A * B) = s_max
        sqrt(A / B) = s_min

        P = s_max + s_min
        P = sqrt(A * B) + sqrt(A / B)
        """
        _, _, W, H = self.inputs.vars
        b, p, a = self._max_aspect, self._max_perim, self._max_area
        M = np.sum(self._max_area.value)
        u = Variable(shape=W.shape[0], boolean=True, name='pvar')
        C = [
            b * W <= H + M * u,  # cW < H,  u = 0,
            H <= b * W + M * (1 - u),  # W > cH,  u = 1
            W + H <= p,

            # cvx.sqrt(b) * W - M * u <= cvx.sqrt(a) ,
            # cvx.sqrt(b) * H <= cvx.sqrt(a) + M * (1 - u),
        ]
        # todo do something with the area! f**k this permiter shit
        # area if aspect is known
        # u = Variable(boolean=True)     # W > H => 1
        # W, H = self._box[2], self._box[3]
        # b, a = self._aspect, self._area
        # p = (np.sqrt(b * a) + np.sqrt(a / b))
        # print('p', p)
        # C += [
        #     W >= 1,
        #     H >= 1,
        #     # H <= np.ceil(np.sqrt(a)),
        #     # W <= np.ceil(np.sqrt(a)),
        #
        #     b * W <= H + M * u,          # cW < H,  u = 0,
        #     H <= b * W + M * (1 - u),    # W > cH,  u = 1
        #     W + H <= p
        #     # np.sqrt(b) * H + M <= np.sqrt(a),
        #     # np.sqrt(b) * W + M * u <= np.sqrt(a),
        #
        #
        #     # np.sqrt(b) * W + M * u <= np.sqrt(self._area),
        #     # np.sqrt(b) * H + M * (1 - u) <= np.sqrt(self._area),
        #
        #     # H * np.sqrt(self._aspect) + M * (1 - vasp) <= np.sqrt(self._area),
        #
        #     # self._box[3] * self._box[2] <= self._area
        #     # cvx.log_det(cvx.bmat([[ self._box[3], 0],
        #     #                       [0, self._box[2]]])) <= np.log(self._area)
        #     # cvx.log(self._box[3]) + cvx.log(self._box[2]) <= np.log(self._area)
        #     ]
        return C
Exemplo n.º 20
0
def test_permutation():
    """Test permutation variable."""
    x = Variable((1, 5))
    c = np.array([[1, 2, 3, 4, 5]])
    perm = Assign((5, 5))
    p = Problem(Minimize(sum(x)), [x == c @ perm])
    result = p.solve(**solve_args)
    assert result[0] == approx(15)
    assert_array_almost_equal(sorted(np.nditer(x.value)), c.ravel())
Exemplo n.º 21
0
 def __init__(self, inputs, values, **kwargs):
     """
     box.W = values[0] and  box.H = values[1]
     or
     box.W = values[1] and  box.H = values[0]
     """
     MIPConstraint.__init__(self, inputs, **kwargs)
     self._choices = values
     self._internal_vars = Variable(shape=(len(values), len(self._indices)), boolean=True)
Exemplo n.º 22
0
 def __init__(self, inputs, values, **kwargs):
     """
     continuous X_i
     x_i = values[i, 0] or x_i = values[i, 1]
     todo - currently
     """
     MIPConstraint.__init__(self, inputs, **kwargs)
     self._choices = values
     self._internal_vars = Variable(shape=(len(values), len(self._indices)), boolean=True)
Exemplo n.º 23
0
def linearize_abs(X, Y, name=None):
    """
    constraints for absolute values of distance matrix of X, Y (only upper tri entries)

    """
    n = X.shape[0]
    tri_i, tri_j = np.triu_indices(n, 1)
    U = Variable(shape=tri_j.shape[0], pos=True, name='U.{}'.format(name))
    V = Variable(shape=tri_j.shape[0], pos=True, name='V.{}'.format(name))
    tri_i, tri_j = tri_i.tolist(), tri_j.tolist()
    C = [
        # linearized absolute value constraints
        # | x_i - x_j |  | y_i - y_j |
        U >= X[tri_i] - X[tri_j],
        U >= X[tri_j] - X[tri_i],
        V >= Y[tri_i] - Y[tri_j],
        V >= Y[tri_j] - Y[tri_i]
    ]
    return (U, V), C
Exemplo n.º 24
0
 def __init__(self, *args, n_colors=0, is_usable=1, **kwargs):
     _VarGraphBase.__init__(self)
     Mesh2d.Edge.__init__(self, *args, **kwargs)
     self._usable = max([0, min(1, is_usable)])
     self.X = Variable(shape=n_colors,
                       boolean=True,
                       name='edge.{}'.format(self.index))
     self._map = ddict(dict)
     self._placements = []
     self._check_acks = []
Exemplo n.º 25
0
    def test_error(self):
        n = 10
        x = Variable(n)
        p_list = [Problem(Minimize(norm(x, 1)))]
        probs = Problems(p_list)

        probs.solve(method="consensus")
        probs.solve(method="consensus", rho_init={x.id: 0.5})
        with self.assertRaises(ValueError) as cm:
            probs.solve(method="consensus", rho_init={(x.id + 1): 0.5})
Exemplo n.º 26
0
 def test_choose(self):
     x = Variable(5, 4)
     p = Problem(Minimize(sum(1 - x) + sum(x)), [x == Choose(5, 4, k=4)])
     result = p.solve(method="admm", solver=CVXOPT)
     self.assertAlmostEqual(result, 20)
     for i in range(x.size[0]):
         for j in range(x.size[1]):
             v = x.value[i, j]
             self.assertAlmostEqual(v * (1 - v), 0)
     self.assertAlmostEqual(x.value.sum(), 4)
Exemplo n.º 27
0
 def __init__(self,
              inputs: PointList = None,
              high: Optional[float] = None,
              low: Optional[float] = None,
              **kwargs):
     """
     """
     FormulationR2.__init__(self, inputs, **kwargs)
     self.B = Variable(shape=len(inputs), pos=True, name=self.name)
     self._bnd = NumericBound(self.B, high=high, low=low)
Exemplo n.º 28
0
def test_choose():
    """Test choose variable."""
    x = Variable((5, 4))
    y = Choose((5, 4), k=4)
    p = Problem(Minimize(sum(1 - x) + sum(x)), [x == y])
    result = p.solve(**solve_args)
    assert result[0] == approx(20)
    for v in np.nditer(x.value):
        assert v * (1 - v) == approx(0)
    assert x.value.sum() == approx(4)
Exemplo n.º 29
0
def calc_Koopman(Yf, Yp, flag=1):
    solver_instance = cvxpy.CVXOPT
    #solver_instance = cvxpy.ECOS;
    if flag == 1:  # moore penrose inverse, plain ol' least squares Koopman
        #Yp_inv = np.dot(np.transpose(Yp_final), np.linalg.inv( np.dot(Yp_final,np.transpose(Yp_final)) )   );
        Yp_inv = np.linalg.pinv(Yp)
        K = np.dot(Yf, Yp_inv)

    if flag == 2:  # cvx optimization approach - L2 + L1 lasso
        norm1_term = 0.0
        all_col_handles = [None] * Yf.shape[0]
        for i in range(0, Yf.shape[0]):
            all_col_handles[i] = Variable(Yf.shape[0], 1)
            norm1_term = norm1_term + norm2(all_col_handles[i])

        operator = all_col_handles[0]
        for i in range(1, Yf.shape[0]):
            operator = cvxpy.hstack(operator, all_col_handles[i])

        print "[INFO]: CVXPY Koopman operator variable: " + repr(operator)
        print "[INFO]: Yf.shape in calc_Koopman: " + repr(Yf.shape)
        norm2_fit_term = norm2(norm2(Yf - operator * Yp, axis=0))
        objective = Minimize(norm2_fit_term + norm1_term)
        constraints = []
        prob = Problem(objective, constraints)
        result = prob.solve(verbose=True, solver=solver_instance)
        print "[INFO]: Finished executing cvx solver, printing CVXPY problem status"
        print(prob.status)
        K = operator.value

    if flag == 3:
        operator = Variable(Yf.shape[0], Yf.shape[0])
        objective = Minimize(cvxpynorm(operator, 2))
        constraints = [
            cvxpynorm(Yf - operator * Yp, 'fro') / cvxpynorm(Yf, 'fro') < 0.01
        ]
        prob = Problem(objective, constraints)
        result = prob.solve(verbose=True)  #(solver=solver_instance);
        print(prob.status)
        K = operator.value

    return K
Exemplo n.º 30
0
    def __init__(self,
                 min_area,
                 max_area=None,
                 min_dim=None,
                 max_dim=None,
                 name=None,
                 aspect=2.0):
        # CONSTRAINTS
        self.name = name
        self.min_dim = min_dim
        self.max_dim = max_dim
        self.max_area = max_area
        self.min_area = min_area
        self.aspect = aspect

        # VARS
        self.height = Variable(pos=True, name='{}.h'.format(name))
        self.width = Variable(pos=True, name='{}.w'.format(name))
        self.x = Variable(pos=True, name='{}.x'.format(name))
        self.y = Variable(pos=True, name='{}.y'.format(name))