Beispiel #1
0
def test_sqrt_graph():

    v0 = Variable(name='v0')
    s0 = Symbol(name='s0')

    expr = sqrt(v0)  # concave

    constr = (expr >= s0)  # effectively in relaxed smith form

    print('Graph form of', end=' ')
    print(constr)
    constr = constr.graph_form()
    print('-->', constr)

    assert (constr.dims == 3)
    assert (type(constr) is SecondOrderConeConstraint)
    assert (all([type(c) is le for c in constr.constraints]))

    c = constr

    string_equals = [
        """(-1.0 + (-1.0 * v0)) <= 0""",
        """(1.0 + (-1.0 * v0)) <= 0""",
        """((2.0 * s0)) <= 0""",
    ]

    for n, string in enumerate(string_equals):
        print(c.constraints[n], '==', string, '?')
        assert (str(c.constraints[n]) == str(string))
        print('SUCCESS!')

    reset_symbols()
def test_matvec():
    """ Test Matrix * Vector product """

    a = Parameter((3, 3), name='a')
    x = Variable((3, 1), name='x')

    m = a * x

    print(m, 'with shapes', a.shape, 'x', x.shape)

    expanded = m.expand()

    print_matrix(expanded)

    assert (list_shape(expanded) == m.shape)

    # Holds all the indices we assert must be in each ELEMENT of each atom
    ind = [[
        [[(0, 0), (0, 0)], [(0, 1), (1, 0)], [(0, 2), (2, 0)]],
    ], [
        [[(1, 0), (0, 0)], [(1, 1), (1, 0)], [(1, 2), (2, 0)]],
    ], [
        [[(2, 0), (0, 0)], [(2, 1), (1, 0)], [(2, 2), (2, 0)]],
    ]]

    for n, row in enumerate(ind):
        for m, col in enumerate(row):
            for s, sumarg in enumerate(col):
                for a, mularg_shape in enumerate(sumarg):
                    assert (
                        expanded[n][m].args[s].args[a].index == mularg_shape)

    reset_symbols()
def test_relax_sq2norm():
    """ Relaxed Form of Minimize(square(norm(v0))) """

    v0 = Variable(name = 'v0')
    v1 = Variable(name = 'v1')

    p0 = Parameter(name = 'p0')
    p1 = Parameter(name = 'p1')

    obj = square(norm(v0))
    con = []

    p = Problem(Minimize(obj), con)
    c = Canonicalize(p, verbose=True, only='relax')

    assert( c.objective is not obj   )
    assert( 'sym0' == c.objective.name )

    # Let up on the testing rigor a bit, now that we checked core fundamentals

    string_equals = [
        """((-1.0 * sym1) + (1.0 * norm2(v0))) <= 0""",
        """((-1.0 * sym0) + (1.0 * square(sym1))) <= 0""",
    ]

    for n, string in enumerate(string_equals):
        print(c.constraints[n],'==',string,'?')
        assert(str(c.constraints[n]) == string)
        print('SUCCESS!')

    reset_symbols()
def test_relax_sq():
    """ Relaxed Form of Minimize(square(v0)) """

    v0 = Variable(name = 'v0')
    v1 = Variable(name = 'v1')

    p0 = Parameter(name = 'p0')
    p1 = Parameter(name = 'p1')

    obj = square(v0)
    con = []

    p = Problem(Minimize(obj), con)
    c = Canonicalize(p, verbose=True, only='relax')

    assert( len(c.constraints) == 1 )
    assert( c.objective is not obj   )
    assert( 'sym0' == c.objective.name )

    assert(type(c.constraints[0]) is le)

    assert(c.constraints[0].expr.args[0].curvature == 0)
    assert(c.constraints[0].expr.args[1].curvature == +1)
    assert(c.constraints[0].expr.args[1].symbol_groups()[0][0].value == 1.0)
    assert(c.constraints[0].expr.args[1].symbol_groups()[2][0].name == 'square')

    reset_symbols()
def test_relax_sq2norm_constr():
    """ Relaxed Form of Minimize(square(norm(v0))) with v0 >= p0"""

    v0 = Variable(name = 'v0')
    v1 = Variable(name = 'v1')

    p0 = Parameter(name = 'p0')
    p1 = Parameter(name = 'p1')

    obj = square(norm(v0))
    con = [v0 >= p0]  # should become -v0 + p0 <= 0

    p = Problem(Minimize(obj), con)
    c = Canonicalize(p, verbose=True, only='relax')

    assert( type(c.constraints[-1]) is le)
    assert( type(c.constraints[-1].expr) is sums.sum)
    assert( type(c.constraints[-1].expr.args[0]) is muls.smul)
    assert( type(c.constraints[-1].expr.args[1]) is muls.smul)
    assert( c.objective is not obj   )
    assert( 'sym0' == c.objective.name )

    string_equals = [
        """((-1.0 * sym1) + (1.0 * norm2(v0))) <= 0""",
        """((-1.0 * sym0) + (1.0 * square(sym1))) <= 0""",
        """((-1.0 * v0) + (p0 * 1.0)) <= 0""",
    ]

    for n, string in enumerate(string_equals):
        print(c.constraints[n],'==',string,'?')
        assert(str(c.constraints[n]) == string)
        print('SUCCESS!')

    reset_symbols()
def test_relax_least_squares_constr():
    """ Relaxed Form : Minimize(square(norm(F*x - g))) with x >= p0 """

    x = Variable ((3,1),name='x')
    F = Parameter((3,3),name='F')
    g = Parameter((3,1),name='g')

    objective = square(norm( F*x - g ))

    objective = Minimize(objective)
    problem   = Problem(objective, [x >= 0])

    c = Canonicalize(problem, verbose=True, only='relax')

    string_equals = [
        """(sym2 + (-1.0 * matmul(F, x))) == 0""",
        """(sym3 + (-1.0 * sym2) + (g * 1.0)) == 0""",
        """((-1.0 * sym1) + (1.0 * norm2(sym3))) <= 0""",
        """((-1.0 * sym0) + (1.0 * square(sym1))) <= 0""",
        """((-1.0 * x)) <= 0""",
    ]

    for n, string in enumerate(string_equals):
        print(c.constraints[n],' ???? ',string, end=' ')
        assert(str(c.constraints[n]) == string)
        print('... SUCCESS!')

    reset_symbols()
Beispiel #7
0
def test_quad_over_lin_x1_graph():

    v0 = Variable(name='v0')
    s0 = Symbol(name='s0')

    x = v0
    expr = quad_over_lin([1], x)

    constr = (expr <= s0)  # effectively in relaxed smith form

    print('Graph form of', end='')
    print(constr)
    constr = constr.graph_form()
    print('-->', constr)
    print()

    assert (constr.dims == 3)
    assert (type(constr) is SecondOrderConeConstraint)
    assert (all([type(c) is le for c in constr.constraints]))

    c = constr  # keeps below names same as other tests

    string_equals = [
        """((-1.0 * v0) + (-1.0 * s0)) <= 0""",
        """((1.0 * v0) + (-1.0 * s0)) <= 0""",
        """(2.0) <= 0"""  # although this constraint is weird, it is required
    ]

    for n, string in enumerate(string_equals):
        print(c.constraints[n], '==', string, '?')
        assert (str(c.constraints[n]) == str(string))
        print('SUCCESS!')

    reset_symbols()
Beispiel #8
0
def test_smith_sq():
    """ Smith Form of Minimize(square(v0)) """

    v0 = Variable(name='v0')
    v1 = Variable(name='v1')

    p0 = Parameter(name='p0')
    p1 = Parameter(name='p1')

    obj = square(v0)
    con = []

    p = Problem(Minimize(obj), con)
    c = Canonicalize(p, verbose=True, only='smith')

    assert (len(c.constraints) == 1)
    assert (c.objective is not obj)
    assert ('sym0' == c.objective.name)

    assert (hasattr(c.constraints[0].expr.args[0], 'name'))
    assert (c.constraints[0].expr.args[0].name == 'sym0')

    assert (hasattr(c.constraints[0].expr.args[1], 'args'))
    assert (hasattr(c.constraints[0].expr.args[1].args[0], 'value'))
    assert (c.constraints[0].expr.args[1].args[0].value == -1.0)

    assert (hasattr(c.constraints[0].expr.args[1].args[1], 'name'))
    assert (c.constraints[0].expr.args[1].args[1].name == 'square')

    reset_symbols()
Beispiel #9
0
def test_ecos_trivial_geomean():

    x = cvx.Variable( (2), name='x')

    constraints  = [x[0] >= 0]

    constraints += [x[1] <= cvx.geo_mean(x[0], 5)]
    constraints += [x[1] >= 5]

    objective = x[0] + x[1]  # farthest down and left
    objective = cvx.Minimize(objective)
    problem   = cvx.Problem(objective, constraints)

    canon = Canonicalize(problem, verbose=True)
    canon.assign_values({})

    solution = cvx.solve(canon, verbose = True)

    if solution:

        print('Solution obj:', solution['info']['pcost'])
        print('Solution   x:', solution['x'][0:2])

        assert( np.allclose(solution['x'][0:2], [5.0, 5.0]) )

    reset_symbols()
Beispiel #10
0
def test_ecos_leastsquares():

    x = cvx.Variable (name='x')
    F = cvx.Parameter(name='F')
    g = cvx.Parameter(name='g')

    objective = cvx.square(cvx.norm( F*x - g ))

    objective = cvx.Minimize(objective)
    problem   = cvx.Problem(objective, [])

    canon = Canonicalize(problem, verbose=True)

    # Set values of parameters
    parameters = {
        'F' : 42,
        'g' : 42,
    }

    canon.assign_values(parameters)

    solution = cvx.solve(canon, verbose = True)

    if solution:
        print('Solution obj:', solution['info']['pcost'])
        print('Solution   x:', solution['x'][0])

        assert( np.isclose(solution['x'][0], 1.0) )

    reset_symbols()
Beispiel #11
0
def test_norm_inf():

    x = Variable((3, 1), name='x')

    objective = norm(x, kind='inf')  # returns max(abs(x))

    objective = Minimize(objective)
    problem = Problem(objective, [])

    c = Canonicalize(problem, verbose=True, only='smith')

    assert (len(c.constraints) == 4)

    string_equals = [
        """(sym1[0][0] + (-1.0 * abs(x[0][0]))) == 0""",
        """(sym1[1][0] + (-1.0 * abs(x[1][0]))) == 0""",
        """(sym1[2][0] + (-1.0 * abs(x[2][0]))) == 0""",
        """(sym0 + (-1.0 * max(sym1))) == 0""",
    ]

    for n, string in enumerate(string_equals):
        print(c.constraints[n], ' ???? ', string, end=' ')
        assert (str(c.constraints[n]) == string)
        print('... SUCCESS!')

    reset_symbols()
def test_elementwisesymbol_into_function():
    """ Test a shaped symbol input to a scalar function and
        the elementwise output """

    x = Variable((3, 1), name='x')

    expr = square(x)

    print(expr)

    constr = (expr <= 0)

    print(constr)

    expand = constr.expand()

    print(expand)

    assert (type(constr.expr) is sums.sum)
    assert (type(constr.expr.args[0]) is Vector)
    assert (len(constr.expr.args[0].args) == 3)
    assert (len(expand) == 3)
    assert (all([type(a) is le for a in expand]))

    reset_symbols()
Beispiel #13
0
def test_square_graph():

    v0 = Variable(name='v0')
    s0 = Symbol(name='s0')

    expr = square(v0)

    constr = (expr <= s0)  # effectively in relaxed smith form

    print('Graph form of', end='')
    print(constr)
    constr = constr.graph_form()
    print('-->', constr)
    print()

    n = max(v0.shape[0], v0.shape[1])
    assert (constr.dims == n + 2)
    assert (type(constr) is SecondOrderConeConstraint)
    assert (all([type(c) is le for c in constr.constraints]))

    c = constr  # keeps below names same as other tests

    string_equals = [
        """(-1.0 + (-1.0 * s0)) <= 0""", """(1.0 + (-1.0 * s0)) <= 0""",
        """((2.0 * v0)) <= 0"""
    ]

    for n, string in enumerate(string_equals):
        print(c.constraints[n], '==', string, '?')
        assert (str(c.constraints[n]) == str(string))
        print('SUCCESS!')

    reset_symbols()
def test_matrix_sq():
    """ Matrix Form of Minimize(square(v0)) """

    v0 = Variable(name = 'v0')
    v1 = Variable(name = 'v1')

    p0 = Parameter(name = 'p0')
    p1 = Parameter(name = 'p1')

    obj = square(v0)
    con = []

    p = Problem(Minimize(obj), con)
    c = Canonicalize(p, verbose=True)

    assert(c.c == [0, 0, 1])
    assert(c.A is None)
    assert(c.b is None)

    assert_G =  {
                    'row':[0, 1, 2],
                    'col':[2, 2, 0],
                    'val':[Constant(-1.0), Constant(-1.0), Constant(2.0)]
                }


    assert_h = [Constant(1.0), Constant(-1.0), Constant(0.0)]
    assert_G = COO_to_CS(assert_G, (len(assert_h), len(c.c)), 'col')

    assert(c.G == assert_G)
    assert(all([c.h[n].value == t.value for n, t in enumerate(assert_h)]))

    assert(c.dims == {'q': [3], 'l': 0})

    reset_symbols()
Beispiel #15
0
def test_ecos_trivial_invpos():

    x = cvx.Variable( (2), name='x')

    constraints  = [x[0] >= 0]

    constraints += [x[1] >= x[0]]
    constraints += [x[1] >= cvx.inv_pos(x[0])]

    objective = x[1]
    objective = cvx.Minimize(objective)
    problem   = cvx.Problem(objective, constraints)

    canon = Canonicalize(problem, verbose=True)
    canon.assign_values({})

    solution = cvx.solve(canon, verbose = True)

    if solution:

        print('Solution obj:', solution['info']['pcost'])
        print('Solution   x:', solution['x'][0:2])

        assert( np.allclose(solution['x'][0:2], [1.0, 1.0]) )

    reset_symbols()
def test_matrix_sq2norm_sqcon():
    """ Relaxed Form : Minimize(square(norm(v0))) with v0 >= square(v1) """

    v0 = Variable(name = 'v0')
    v1 = Variable(name = 'v1')

    p0 = Parameter(name = 'p0')
    p1 = Parameter(name = 'p1')

    obj = square(norm(v0 + v1))
    con = [v0 >= square(v1)]  # should become -v0 + square(v1) <= 0

    p = Problem(Minimize(obj), con)
    c = Canonicalize(p, verbose=True)

    sym3 = [v for vn, v in c.vars.items() if vn == 'sym3'][0]

    assert_A = {'row': [0, 0, 0],
         'col': [0, 1, 4],
         'val': [Constant(-1.0), Constant(-1.0), Constant(1.0)]}

    assert_b = [Constant(0.0)]
    #assert_G = {'row': [0, 0, 1, 2, 3, 4, 5, 6, 7, 8],
    #     'col': [0, 5, 3, 4, 2, 2, 3, 5, 5, 1],
    #     'val': [Constant(-1.0), Constant(0.0), Constant(-1.0), Constant(1.0),
    #             Constant(-1.0), Constant(-1.0), Constant(2.0), Constant(-1.0),
    #             Constant(-1.0), Constant(2.0)]}

    assert_G = {'row': [0, 0, 1, 2, 3, 4, 5, 6, 7, 8],
         'col': [0, 5, 3, 4, 2, 2, 3, 5, 5, 1],
         'val': [Constant(-1.0), Constant(1.0), Constant(-1.0), Constant(1.0),
                 Constant(-1.0), Constant(-1.0), Constant(2.0), Constant(-1.0),
                 Constant(-1.0), Constant(2.0)]}

    assert_h = [ (-1.0 * sym3), Constant(0.0), Constant(0.0), Constant(1.0),
                Constant(-1.0), Constant(0.0), Constant(1.0),
                Constant(-1.0), Constant(0.0)]

    assert_h = [Constant(0.0), Constant(0.0), Constant(0.0), Constant(1.0),
                Constant(-1.0), Constant(0.0), Constant(1.0), Constant(-1.0),
                Constant(0.0)]

    assert_dims = {'q': [2, 3, 3], 'l': 1}

    assert_A = COO_to_CS(assert_A, (len(assert_b), len(c.c)), 'col')
    assert_G = COO_to_CS(assert_G, (len(assert_h), len(c.c)), 'col')

    assert_c = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]

    assert(c.c == assert_c)
    assert(c.A == assert_A)
    assert(c.b == assert_b)

    assert(c.G == assert_G)
    assert(all([c.h[n].value == t.value for n, t in enumerate(assert_h)]))

    assert(c.dims == assert_dims)

    reset_symbols()
Beispiel #17
0
def test_symbol_curvature():

    v = Variable(name='v')
    assert (v.curvature == 0)

    p = Parameter(name='p')
    assert (p.curvature == 0)

    reset_symbols()
Beispiel #18
0
def test_ecos_polyhedradist():
    import cvx_sym as cvx

    n = 2  # number of dimensions
    m = 3  # number of lines defining polyhedron 1
    p = 3  # number of lines defining polyhedron 2

    x1 = cvx.Variable ((n,1),name='x1')
    x2 = cvx.Variable ((n,1),name='x2')

    A1 = cvx.Parameter((m,n),name='A1')
    A2 = cvx.Parameter((p,n),name='A2')
    B1 = cvx.Parameter((m,1),name='B1')
    B2 = cvx.Parameter((p,1),name='B2')

    objective = cvx.square(cvx.norm(x1 - x2))

    constraints  = [ A1[i,:].T * x1 <= B1[i] for i in range(m) ]
    constraints += [ A2[i,:].T * x2 <= B2[i] for i in range(p) ]

    objective = cvx.Minimize(objective)
    problem   = cvx.Problem(objective, constraints)

    canon = Canonicalize(problem, verbose=True)

    # Set values of parameters
    parameters = {
        'A1' : np.array([[-1,1],[1,1],[0,-1]]),
        'B1' : np.array([[3],[3],[0]]),

        'A2' : np.array([[.5,-1],[0,1],[+1,0]]),
        'B2' : np.array([[-3],[3],[5]]),
    }

    canon.assign_values(parameters)

    solution = cvx.solve(canon, verbose = True)

    if solution:
        print('Solution obj:', solution['info']['pcost'])

        # Gather the OG solution variables

        v_indices = [n for n, vn in enumerate(canon.vars.keys()) if 'x' in vn]
        x_solution = [solution['x'][i] for i in v_indices]

        print('Solution   x:', x_solution)
        print('Solution vec:', solution['x'])

        # Solution is found at intersection of polyhedra
        assert( np.allclose(x_solution, [0,3, 0,3],  atol=1e-4) )

        # So therefore the objective should be near zero
        assert( np.allclose(solution['info']['pcost'], 0.0 ) )

    reset_symbols()
def test_constraints():

    v0 = Variable(name='v0')
    v1 = Variable(name='v1')

    p0 = Parameter(name='p0')
    p1 = Parameter(name='p1')

    c = (v0 == 0)

    print(c)
    assert (type(c) == eq)
    assert (c.expr.args[0] is v0)

    c = (v0 <= 0)

    print(c)
    assert (type(c) == le)
    assert (c.expr.args[0] is v0)

    c = (v0 >= 0)

    print(c)
    assert (type(c) == le)
    assert (c.expr.args[0].args[0].value == -1)
    assert (c.expr.args[0].args[1] is v0)

    c = (v0 >= p0)

    print(c)
    assert (type(c) == le)
    assert (c.expr.args[0].args[0].value == -1)
    assert (c.expr.args[0].args[1] is v0)
    assert (c.expr.args[1].args[0] is p0)

    # TODO: ADD TESTS FOR ATOMS AND FUNCTIONS IN CONSTRAINTS!

    # ATOMS in Constraints

    c = (v1 + v0 == p0)

    print(c)
    assert (type(c) == eq)
    assert (str(c) == '(p0 + (-1.0 * v1) + (-1.0 * v0)) == 0')

    # FUNCTIONS in Constraints

    c = (norm(v1) <= v0)

    print(c)
    assert (type(c) == le)
    assert (c.expr.nterms == 2)
    assert (c.expr.args[1].args[1] is v0)

    reset_symbols()
def test_mul_redirect():
    """ Test that mul redirects properly to matmul """

    a = Parameter((10, 1), name='a')
    b = Variable((1, 10), name='b')

    m = a * b

    assert (type(m) is matmul)
    assert (m.args[0] is a)
    assert (m.args[1] is b)

    reset_symbols()
Beispiel #21
0
def test_ecos_robustlp():

    import cvx_sym as cvx

    n = 2  # number of dimensions
    m = 3  # number of elementwise elements

    x = cvx.Variable ((n,1),name='x')

    A = cvx.Parameter((m,n),name='A')
    B = cvx.Parameter((m,1),name='B')
    C = cvx.Parameter((n,1),name='C')
    P = cvx.Parameter((m,n),name='P')

    objective = C.T * x

    constraints = [A[i].T * x + cvx.norm(P[i].T * x) <= B[i] for i in range(m)]

    objective = cvx.Minimize(objective)
    problem   = cvx.Problem(objective, constraints)

    canon = Canonicalize(problem, verbose=True)

    # Set values of parameters
    parameters = {
        'A' : np.array([[1,1],[1,1],[1,1]]),
        'B' : np.array([[3],[3],[3]]),

        'C' : np.array([[.1],[.2]]),
        'P' : np.array([[1,2],[3,4],[5,6]])
    }

    canon.assign_values(parameters)

    solution = cvx.solve(canon, verbose = True)

    if solution:
        print('Solution obj:', solution['info']['pcost'])

        # Gather the OG solution variables

        v_indices = [n for n, vn in enumerate(canon.vars.keys()) if 'x' in vn]
        x_solution = [solution['x'][i] for i in v_indices]

        print('Solution   x:', x_solution)
        print('Solution vec:', solution['x'])

        assert( np.allclose(x_solution, [3,-3] ) )

    reset_symbols()
Beispiel #22
0
def test_ecos_leastsquares_constr():

    x = cvx.Variable ((3,1),name='x')
    F = cvx.Parameter((3,3),name='F')
    g = cvx.Parameter((3,1),name='g')

    U = cvx.Parameter((3,1),name='U')
    L = cvx.Parameter((3,1),name='L')

    constraints  = []
    objective = cvx.square(cvx.norm( F*x - g ))

    constraints += [ x <= U ]
    constraints += [ L <= x ]

    objective = cvx.Minimize(objective)
    problem   = cvx.Problem(objective, constraints)

    canon = Canonicalize(problem, verbose=True)

    # Set values of parameters
    parameters = {
        'F' : np.array([[1,2,3],[4,5,6],[7,8,9]]),
        'g' : np.array([[1],[2],[3]]),

        'U' : np.array([[42],[42],[42]]),
        'L' : np.array([[1],[2],[3]])
    }

    canon.assign_values(parameters)

    solution = cvx.solve(canon, verbose = True)

    if solution:
        print('Solution obj:', solution['info']['pcost'])

        # Gather the OG solution variables

        v_indices = [n for n, vn in enumerate(canon.vars.keys()) if 'x' in vn]
        x_solution = [solution['x'][i] for i in v_indices]

        print('Solution   x:', x_solution)
        print('Solution vec:', solution['x'])

        assert( np.allclose(x_solution, [1,2,3] ) )

    reset_symbols()
Beispiel #23
0
def test_ecos_chebyshevcenter():

    import cvx_sym as cvx

    n = 2
    m = 3

    r = cvx.Variable((1,1),name='r')
    x = cvx.Variable((n,1),name='x')

    A = cvx.Parameter((m,n),name='A')
    B = cvx.Parameter((m,1),name='B')

    objective = -r

    constraints  = [A[i,:].T * x + r * cvx.norm(A[i,:]) <= B[i] for i in range(m)]
    constraints += [r >= 0]

    objective = cvx.Minimize(objective)
    problem   = cvx.Problem(objective, constraints)

    canon = Canonicalize(problem, verbose=True)

    # Set values of parameters
    parameters = {
        'A' : np.array([[-1,1],[1,1],[0,-1]]),
        'B' : np.array([[3],[3],[0]]),
    }

    canon.assign_values(parameters)

    solution = cvx.solve(canon, verbose = True)

    if solution:
        print('Solution obj:', solution['info']['pcost'])

        # Gather the OG solution variables

        v_indices = [n for n, vn in enumerate(canon.vars.keys()) if 'x' in vn]
        x_solution = [solution['x'][i] for i in v_indices]

        print('Solution   x:', x_solution)
        print('Solution vec:', solution['x'])

        assert( np.allclose(x_solution, [0, 1.242641] ) )

    reset_symbols()
def test_matrix_least_squares_constr():
    """ Minimize(square(norm(F*x - g))) with x >= p0 """

    x = Variable ((3,1),name='x')
    F = Parameter((3,3),name='F')
    g = Parameter((3,1),name='g')

    objective = square(norm( F*x - g ))

    objective = Minimize(objective)
    problem   = Problem(objective, [x >= 1])

    c = Canonicalize(problem, verbose=True)

    # Test for errors, not asserts, and for solution outcome (via ecos_solution)

    reset_symbols()
def test_reshaping_vector():
    """ Test reshaping a vector (slice of a symbol in this case)"""

    p = Parameter((2, (2 * 2)), name='p')

    sliced = p[1, :]

    print(sliced)

    shaped = reshape(sliced, (2, 2))

    print(shaped)

    assert (str(shaped[0, 0]) == str(p[1][0]))
    assert (str(shaped[0, 1]) == str(p[1][1]))
    assert (str(shaped[1, 0]) == str(p[1][2]))
    assert (str(shaped[1, 1]) == str(p[1][3]))

    reset_symbols()
Beispiel #26
0
def check_curvy_function(function, asserted_curvature):
    print('Testing Curvature of', function.name)

    v = Variable(name='v')

    e = function(v)

    if asserted_curvature > 0:
        assert (e.curvature > 0)
    else:
        assert (e.curvature < 0)

    e = -1 * function(v)

    if asserted_curvature > 0:
        assert (e.curvature < 0)
    else:
        assert (e.curvature > 0)

    reset_symbols()
def test_matmul_constraint():
    """ Test that constraints with matmul are expanded elementwise in canon """

    p = Parameter((3, 1), name='p')
    a = Parameter((3, 3), name='a')
    x = Variable((3, 1), name='x')

    expr = a * x

    print('expr', expr)
    constr = (expr <= p)

    print('constr', constr)
    constr = constr.expand()
    print('-->', constr)
    print()

    assert (len(constr) == 3)
    assert (all([type(a) is le for a in constr]))

    reset_symbols()
Beispiel #28
0
def test_norm_value_expr():

    p = Parameter((3, 1), name='p')

    expr = norm(p)

    value = expr.value({'p[0][0]': 3, 'p[1][0]': 2, 'p[2][0]': 1})

    assert (np.isclose(value, np.linalg.norm([[3], [2], [1]])))

    reset_symbols()

    p = Parameter((1, 3), name='p')

    expr = norm(p)

    value = expr.value({'p[0][0]': 3, 'p[0][1]': 2, 'p[0][2]': 1})

    assert (np.isclose(value, np.linalg.norm([3, 2, 1])))

    reset_symbols()
def test_matrix_sq2norm_constr():
    """ Matrix Form of Minimize(square(norm(v0))) with v0 >= p0"""

    v0 = Variable(name = 'v0')
    v1 = Variable(name = 'v1')

    p0 = Parameter(name = 'p0')
    p1 = Parameter(name = 'p1')

    obj = square(norm(v0))
    con = [v0 >= p0]  # should become -v0 + p0 <= 0

    p = Problem(Minimize(obj), con)
    c = Canonicalize(p, verbose=True)


    assert_c = [0.0, 0.0, 1.0, 0.0]

    assert_A = COO_to_CS({'row':[],'col':[],'val':[]}, (0,4), 'col')

    assert_G =  {'row': [0, 1, 2, 3, 4, 5], 'col': [0, 3, 0, 2, 2, 3],
                'val': [Constant(-1.0), Constant(-1.0), Constant(1.0),
                        Constant(-1.0), Constant(-1.0), Constant(2.0)]}

    assert_h = [(-1.0 * p0), Constant(0.0), Constant(0.0),
                Constant(1.0), Constant(-1.0), Constant(0.0)]

    assert_G = COO_to_CS(assert_G, (len(assert_h), len(c.c)), 'col')

    assert(c.c == assert_c)
    assert(c.A is None)
    assert(c.b is None)

    assert(c.G == assert_G)
    assert(all([c.h[n].value == t.value for n, t in enumerate(assert_h)]))

    assert(c.dims == {'q': [2, 3], 'l': 1})

    reset_symbols()
def test_elementwiselist_into_function():
    """ Test a list input to a scalar function and the elementwise output """

    x = Variable(name='x')
    y = Variable(name='y')
    z = Variable(name='z')
    a = Variable(name='a')
    b = Variable(name='b')
    c = Variable(name='c')

    expr = square([x, y, z, a, b, c])

    print(expr)

    constr = (expr <= 0)

    print(constr)

    assert (type(constr.expr) is sums.sum)
    assert (type(constr.expr.args[0]) is Vector)
    assert (len(constr.expr.args[0].args) == 6)

    reset_symbols()