コード例 #1
0
ファイル: test_curvature.py プロジェクト: ChupingYang/cvxpy
    def setup_class(self):
        self.cvx = Variable()**2
        self.ccv = Variable()**0.5
        self.aff = Variable()
        self.const = Constant(5)
        self.unknown_curv = log(Variable()**3)

        self.pos = Constant(1)
        self.neg = Constant(-1)
        self.zero = Constant(0)
        self.unknown_sign = Parameter()
コード例 #2
0
ファイル: test_sign.py プロジェクト: nicaiseeric/cvxpy
class TestSign(BaseTest):
    """ Unit tests for the expression/sign class. """
    @classmethod
    def setup_class(self):
        self.pos = Constant(1)
        self.neg = Constant(-1)
        self.zero = Constant(0)
        self.unknown = Variable()

    def test_add(self):
        self.assertEqual((self.pos + self.neg).sign, self.unknown.sign)
        self.assertEqual((self.neg + self.zero).sign, self.neg.sign)
        self.assertEqual((self.pos + self.pos).sign, self.pos.sign)
        self.assertEqual((self.unknown + self.zero).sign, self.unknown.sign)

    def test_sub(self):
        self.assertEqual((self.pos - self.neg).sign, self.pos.sign)
        self.assertEqual((self.neg - self.zero).sign, self.neg.sign)
        self.assertEqual((self.pos - self.pos).sign, self.unknown.sign)

    def test_mult(self):
        self.assertEqual((self.zero * self.pos).sign, self.zero.sign)
        self.assertEqual((self.unknown * self.pos).sign, self.unknown.sign)
        self.assertEqual((self.pos * self.neg).sign, self.neg.sign)
        self.assertEqual((self.pos * self.pos).sign, self.pos.sign)
        self.assertEqual((self.pos * self.pos).sign, self.pos.sign)
        self.assertEqual((self.neg * self.neg).sign, self.pos.sign)
        self.assertEqual((self.zero * self.unknown).sign, self.zero.sign)

    def test_neg(self):
        self.assertEqual((-self.zero).sign, self.zero.sign)
        self.assertEqual((-self.pos).sign, self.neg.sign)

    # Tests the is_positive and is_negative methods.
    def test_is_sign(self):
        assert self.pos.is_positive()
        assert not self.neg.is_positive()
        assert not self.unknown.is_positive()
        assert self.zero.is_positive()

        assert not self.pos.is_negative()
        assert self.neg.is_negative()
        assert not self.unknown.is_negative()
        assert self.zero.is_negative()

        assert self.zero.is_zero()
        assert not self.neg.is_zero()

        assert not (self.unknown.is_positive() or self.unknown.is_negative())
コード例 #3
0
ファイル: test_sign.py プロジェクト: nicaiseeric/cvxpy
 def setup_class(self):
     self.pos = Constant(1)
     self.neg = Constant(-1)
     self.zero = Constant(0)
     self.unknown = Variable()
コード例 #4
0
ファイル: test_curvature.py プロジェクト: ChupingYang/cvxpy
class TestCurvature(object):
    """ Unit tests for the expression/curvature class. """
    @classmethod
    def setup_class(self):
        self.cvx = Variable()**2
        self.ccv = Variable()**0.5
        self.aff = Variable()
        self.const = Constant(5)
        self.unknown_curv = log(Variable()**3)

        self.pos = Constant(1)
        self.neg = Constant(-1)
        self.zero = Constant(0)
        self.unknown_sign = Parameter()

    def test_add(self):
        assert_equals( (self.const + self.cvx).curvature, self.cvx.curvature)
        assert_equals( (self.unknown_curv + self.ccv).curvature, self.unknown_curv.curvature)
        assert_equals( (self.cvx + self.ccv).curvature, self.unknown_curv.curvature)
        assert_equals( (self.cvx + self.cvx).curvature, self.cvx.curvature)
        assert_equals( (self.aff + self.ccv).curvature, self.ccv.curvature)

    def test_sub(self):
        assert_equals( (self.const - self.cvx).curvature, self.ccv.curvature)
        assert_equals( (self.unknown_curv - self.ccv).curvature, self.unknown_curv.curvature)
        assert_equals( (self.cvx - self.ccv).curvature, self.cvx.curvature)
        assert_equals( (self.cvx - self.cvx).curvature, self.unknown_curv.curvature)
        assert_equals( (self.aff - self.ccv).curvature, self.cvx.curvature)

    def test_sign_mult(self):
        assert_equals( (self.zero* self.cvx).curvature, self.const.curvature)
        assert_equals( (self.neg*self.cvx).curvature, self.ccv.curvature)
        assert_equals( (self.neg*self.ccv).curvature, self.cvx.curvature)
        assert_equals( (self.neg*self.unknown_curv).curvature, self.unknown_curv.curvature)
        assert_equals( (self.pos*self.aff).curvature, self.aff.curvature)
        assert_equals( (self.pos*self.ccv).curvature, self.ccv.curvature)
        assert_equals( (self.unknown_sign*self.const).curvature, self.const.curvature)
        assert_equals( (self.unknown_sign*self.ccv).curvature, self.unknown_curv.curvature)

    def test_neg(self):
        assert_equals( (-self.cvx).curvature, self.ccv.curvature)
        assert_equals( (-self.aff).curvature, self.aff.curvature)

    # Tests the is_affine, is_convex, and is_concave methods
    def test_is_curvature(self):
        assert self.const.is_affine()
        assert self.aff.is_affine()
        assert not self.cvx.is_affine()
        assert not self.ccv.is_affine()
        assert not self.unknown_curv.is_affine()

        assert self.const.is_convex()
        assert self.aff.is_convex()
        assert self.cvx.is_convex()
        assert not self.ccv.is_convex()
        assert not self.unknown_curv.is_convex()

        assert self.const.is_concave()
        assert self.aff.is_concave()
        assert not self.cvx.is_concave()
        assert self.ccv.is_concave()
        assert not self.unknown_curv.is_concave()
コード例 #5
0
    Q = sparse.diags([0.2, 0.3])
    QN = sparse.diags([0.4, 0.5])  # final cost
    R = 0.1 * sparse.eye(1)

    # Initial and reference states
    x0 = np.array([0.1, 0.2])  # initial state
    # Reference input and states
    pref = 7.0
    vref = 0
    xref = np.array([pref, vref])  # reference state

    # Prediction horizon
    Np = 20

    # Define problem
    u = Variable((nu, Np))
    x = Variable((nx, Np + 1))
    x_init = Parameter(nx)
    objective = 0
    constraints = [x[:, 0] == x_init]
    for k in range(Np):
        objective += quad_form(x[:, k] - xref, Q) + quad_form(u[:, k], R)
        constraints += [x[:, k + 1] == Ad * x[:, k] + Bd * u[:, k]]
        constraints += [xmin <= x[:, k], x[:, k] <= xmax]
        constraints += [umin <= u[:, k], u[:, k] <= umax]
    objective += quad_form(x[:, Np] - xref, QN)
    prob = Problem(Minimize(objective), constraints)

    # Simulate in closed loop
    # Simulate in closed loop
    len_sim = 15  # simulation length (s)
コード例 #6
0
 def __init__(self, inputs, values, indicies=None, **kwargs):
     MIPConstraint.__init__(self, inputs, **kwargs)
     self._choices = values
     self._indices = indicies
     self._internal_vars = Variable(shape=(4, len(inputs)), boolean=True)
コード例 #7
0
 def setup_class(self):
     self.pos = Constant(1)
     self.neg = Constant(-1)
     self.zero = Constant(0)
     self.unknown = Variable()
コード例 #8
0
    data += [(-1, offset + np.random.normal(-1.0, 2.0, (n, 1)))]
data_splits = [data[i:i + SPLIT_SIZE] for i in range(0, N, SPLIT_SIZE)]


# Count misclassifications.
def get_error(w):
    error = 0
    for label, sample in data:
        if not label * (np.dot(w[:-1].T, sample) - w[-1])[0] > 0:
            error += 1
    return "%d misclassifications out of %d samples" % (error, N)


# Construct problem.
rho = 1.0
w = Variable(n + 1)


def prox(args):
    f, w_avg = args
    f += (rho / 2) * sum_squares(w - w_avg)
    Problem(Minimize(f)).solve()
    return w.value


def svm(data):
    slack = [pos(1 - b * (a.T * w[:-1] - w[-1])) for (b, a) in data]
    return norm(w, 2) + sum(slack)


fi = map(svm, data_splits)
コード例 #9
0
ファイル: gen_SILL_Koopman.py プロジェクト: cajUCSB/darpa-sd2
print "[INFO] f_all_points.shape (E-DMD): " + repr(f_all_points.shape)

solver_instance = cvxpy.CVXOPT

f_dimensions = f_all_points.shape[1]
num_product_terms = f_dimensions

num_logistic_functions = 3
#this hyperparameter needs to be generalized

all_center_handles = [None] * num_logistic_functions
all_weight_handles = [None] * num_logistic_functions
approximator = 0.0
for j in range(0, x_all_points.shape[0]):
    for k in range(0, num_logistic_functions):
        all_weight_handles[k] = Variable(1, 1)
        all_center_handles[k] = Variable(num_product_terms, 1)
        prod_log_functions = 1.0

        for i in range(0, num_product_terms):
            prod_log_functions = prod_log_functions * 1.0 / (
                1.0 + cvxpy.exp(alpha *
                                (x_all_points[j] - all_center_handles[k][i])))

    approximator = approximator + cvxpy.norm1(f_all_points[j] -
                                              prod_log_functions)

# # # - - - - -  Koopman calculation - - - - - # # #


def calc_Koopman(Yf, Yp, flag=1):
コード例 #10
0
ファイル: ex_5_1.py プロジェクト: sjschneider/cvxpy
# Taken from CVX website http://cvxr.com/cvx/examples/
# Exercise 5.1d: Sensitivity analysis for a simple QCQP
# Ported from cvx matlab to cvxpy by Misrab Faizullah-Khan
# Original comments below

# Boyd & Vandenberghe, "Convex Optimization"
# Joelle Skaf - 08/29/05
# (a figure is generated)
#
# Let p_star(u) denote the optimal value of:
#           minimize    x^2 + 1
#               s.t.    (x-2)(x-2)<=u
# Finds p_star(u) and plots it versus u

u = Parameter()
x = Variable()

objective = Minimize(quad_form(x, 1) + 1)
constraint = [quad_form(x, 1) - 6 * x + 8 <= u]
p = Problem(objective, constraint)


# Assign a value to gamma and find the optimal x.
def get_x(u_value):
    u.value = u_value
    result = p.solve()
    return x.value


u_values = np.linspace(-0.9, 10, num=50)
# Serial computation.
コード例 #11
0
    def compute_edge_curv(self,
                          vertex_a,
                          vertex_b,
                          direction=None,
                          alpha=0.0,
                          vertex_weight=None,
                          measure_dir=None,
                          dist_dir='OUT',
                          weighted_distance=False,
                          solver=None,
                          solver_options={},
                          verbose=False):
        """

        NB:  dist_dir='OUT', weighted_distance=False are very important

        :param vertex_a:
        :param vertex_b:
        :param direction:
        :param alpha:
        :param vertex_weight:
        :param measure_dir:
        :param solver:
        :param solver_options:
        :param verbose:
        :return:
        """

        if vertex_a == vertex_b:
            return 1.

        nei_a, mx = self.measure(vertex_a, direction, alpha, vertex_weight,
                                 measure_dir)
        nei_b, my = self.measure(vertex_b, direction, alpha, vertex_weight,
                                 measure_dir)

        if verbose:
            print(f'a: {vertex_a}, nei: {nei_a}, measure: {mx}')
            print(f'b: {vertex_b}, nei: {nei_b}, measure: {my}')

        if (vertex_a not in nei_b) and (vertex_b not in nei_a):
            print(f'a: {vertex_a}, nei: {nei_a}, measure: {mx}')
            print(f'b: {vertex_b}, nei: {nei_b}, measure: {my}')
            raise ValueError('x and y are not neighbours')

        if verbose:
            print(len(nei_a), len(nei_b), len(set(nei_a) & set(nei_b)))

        dist = self.distance_matrix(nei_a,
                                    nei_b,
                                    dist_dir,
                                    weighted=weighted_distance)
        dist0 = self.distance_matrix([vertex_a], [vertex_b],
                                     dist_dir,
                                     weighted=weighted_distance)

        if verbose:
            print(dist)

        plan = Variable((len(nei_a), len(nei_b)))
        mx_trans = mx.reshape(-1, 1) * dist
        mu_trans_param = Parameter(mx_trans.shape, value=mx_trans)
        obj = Minimize(cvx_sum(cvx_mul(plan, mu_trans_param)))
        plan_i = cvx_sum(plan, axis=1)
        my_constraint = mx * plan
        constraints = [
            my_constraint == my, plan >= 0, plan <= 1,
            plan_i == np.ones(len(nei_a))
        ]
        problem = Problem(obj, constraints)
        try:
            wd = problem.solve(solver=solver, **solver_options)
            curv = 1. - wd / dist0[0, 0]
        except:
            curv = 'failed'
            print(
                f'fail: '
                f'va: {vertex_a} : {nei_a} \n'
                f'vb: {vertex_b} : {nei_b}\n'
                f'solver options: {solver} with {solver_options}; val = {curv}'
            )
            solvers = list(self.solvers)
            print(solvers)
            while curv == 'failed' and solvers:

                try:
                    solver = solvers.pop()
                    wd = problem.solve(solver=solver, **solver_options)
                    curv = 1. - wd / dist0[0, 0]
                    print(
                        f'succeed: '
                        f'va: {vertex_a} : {nei_a} \n'
                        f'vb: {vertex_b} : {nei_b}\n'
                        f'solver options: {solver} with {solver_options}; val = {curv}'
                    )

                except:
                    print(
                        f'fail: '
                        f'va: {vertex_a} : {nei_a} \n'
                        f'vb: {vertex_b} : {nei_b}\n'
                        f'solver options: {solver} with {solver_options}; val = {curv}'
                    )
        return curv