Example #1
0
File: test_prob.py Project: c-l/sco
    def test_abs_expr_to_grb_expr(self):
        """
        min |x + 1| s.t. x <= -4
        """
        aff = AffExpr(np.ones((1,1)), np.ones((1,1)))
        abs_expr = AbsExpr(aff)

        aff = AffExpr(np.ones((1,1)), np.zeros((1,1)))
        comp = LEqExpr(aff, np.array([[-4]]))

        model = grb.Model()
        prob = Prob(model)


        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)
        model.update()

        abs_grb_expr, abs_grb_cnt = prob._abs_expr_to_grb_expr(abs_expr, var)
        model.update()
        model.setObjective(abs_grb_expr[0,0])

        bexpr = BoundExpr(comp, var)
        prob.add_cnt_expr(bexpr)

        model.optimize()
        var.update()
        self.assertTrue(np.allclose(var.get_value(), np.array([[-4]])))
        # makes assumption about the construction of the Gurobi variable, needs
        # to be changed TODO
        pos = abs_grb_expr[0,0].getVar(0).X
        neg = abs_grb_expr[0,0].getVar(1).X
        self.assertTrue(np.allclose(pos, 0.0))
        self.assertTrue(np.allclose(neg, 3.0))
Example #2
0
    def test_hinge_expr_to_grb_expr2(self):
        """
        min max(0, x+1) st. x == 1
        """
        aff = AffExpr(np.ones((1, 1)), np.ones((1, 1)))
        hinge = HingeExpr(aff)
        model = grb.Model()
        prob = Prob(model)

        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)
        model.update()

        hinge_grb_expr, hinge_grb_cnt = prob._hinge_expr_to_grb_expr(
            hinge, var)
        model.update()
        obj = hinge_grb_expr[0, 0]
        model.setObjective(obj)

        aff = AffExpr(np.ones((1, 1)), np.zeros((1, 1)))
        comp = EqExpr(aff, np.array([[1.0]]))
        bound_expr = BoundExpr(comp, var)
        prob.add_cnt_expr(bound_expr)

        model.optimize()
        var.update()
        self.assertTrue(np.allclose(var.get_value(), np.array([[1.0]])))
        self.assertTrue(np.allclose(obj.X, 2.0))
Example #3
0
File: test_prob.py Project: c-l/sco
    def test_hinge_expr_to_grb_expr2(self):
        """
        min max(0, x+1) st. x == 1
        """
        aff = AffExpr(np.ones((1,1)), np.ones((1,1)))
        hinge = HingeExpr(aff)
        model = grb.Model()
        prob = Prob(model)

        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)
        model.update()

        hinge_grb_expr, hinge_grb_cnt = prob._hinge_expr_to_grb_expr(hinge, var)
        model.update()
        obj = hinge_grb_expr[0,0]
        model.setObjective(obj)

        aff = AffExpr(np.ones((1,1)), np.zeros((1,1)))
        comp = EqExpr(aff, np.array([[1.0]]))
        bound_expr = BoundExpr(comp, var)
        prob.add_cnt_expr(bound_expr)

        model.optimize()
        var.update()
        self.assertTrue(np.allclose(var.get_value(), np.array([[1.0]])))
        self.assertTrue(np.allclose(obj.X, 2.0))
    def __init__(self,
                 num_nodes,
                 num_bits,
                 node_capacity,
                 conservation_factor,
                 confidence_factor,
                 init_num_nodes,
                 alpha,
                 beta,
                 gamma,
                 delta_in,
                 delta_out,
                 plot_degree_dist=False):
        self.num_nodes = num_nodes
        self.num_bits = num_bits
        self.prob = Prob(num_bits, conservation_factor, confidence_factor)
        self.scale_free_graph = generate_scale_free(num_nodes, init_num_nodes,
                                                    alpha, beta, gamma,
                                                    delta_in, delta_out)
        self.nodes_memory = [
            MemoryQueue(node_capacity) for _ in range(num_nodes)
        ]

        if plot_degree_dist:
            plot_degree_distribution(
                self.scale_free_graph.compute_outdegree_distribution(),
                int(0.08 * num_nodes), 'Outdegree Distribution')

            plot_degree_distribution(
                self.scale_free_graph.compute_indegree_distribution(),
                int(0.08 * num_nodes), 'Indegree Distribution')
Example #5
0
    def test_abs_expr_to_grb_expr(self):
        """
        min |x + 1| s.t. x <= -4
        """
        aff = AffExpr(np.ones((1, 1)), np.ones((1, 1)))
        abs_expr = AbsExpr(aff)

        aff = AffExpr(np.ones((1, 1)), np.zeros((1, 1)))
        comp = LEqExpr(aff, np.array([[-4]]))

        model = grb.Model()
        prob = Prob(model)

        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)
        model.update()

        abs_grb_expr, abs_grb_cnt = prob._abs_expr_to_grb_expr(abs_expr, var)
        model.update()
        model.setObjective(abs_grb_expr[0, 0])

        bexpr = BoundExpr(comp, var)
        prob.add_cnt_expr(bexpr)

        model.optimize()
        var.update()
        self.assertTrue(np.allclose(var.get_value(), np.array([[-4]])))
        # makes assumption about the construction of the Gurobi variable, needs
        # to be changed TODO
        pos = abs_grb_expr[0, 0].getVar(0).X
        neg = abs_grb_expr[0, 0].getVar(1).X
        self.assertTrue(np.allclose(pos, 0.0))
        self.assertTrue(np.allclose(neg, 3.0))
Example #6
0
File: test_prob.py Project: c-l/sco
 def test_expr_to_grb_expr_w_expr(self):
     model = grb.Model()
     prob = Prob(model)
     expr = Expr(f)
     bexpr = BoundExpr(f, None)
     with self.assertRaises(Exception) as e:
         prob._expr_to_grb_expr(bexpr)
     self.assertTrue("Expression cannot be converted" in e.exception.message)
Example #7
0
 def test_expr_to_grb_expr_w_expr(self):
     model = grb.Model()
     prob = Prob(model)
     expr = Expr(f)
     bexpr = BoundExpr(f, None)
     with self.assertRaises(Exception) as e:
         prob._expr_to_grb_expr(bexpr)
     self.assertTrue(
         "Expression cannot be converted" in e.exception.message)
Example #8
0
 def test_expr_to_grb_expr_w_comp_expr(self):
     model = grb.Model()
     prob = Prob(model)
     aff = AffExpr(-2 * np.ones((1, 1)), np.zeros((1, 1)))
     val = np.zeros((1, 1))
     cexpr = CompExpr(aff, val)
     bexpr = BoundExpr(cexpr, None)
     with self.assertRaises(Exception) as e:
         prob._expr_to_grb_expr(bexpr)
     self.assertTrue("Comparison" in e.exception.message)
Example #9
0
File: test_prob.py Project: c-l/sco
 def test_expr_to_grb_expr_w_comp_expr(self):
     model = grb.Model()
     prob = Prob(model)
     aff = AffExpr(-2*np.ones((1,1)), np.zeros((1,1)))
     val = np.zeros((1,1))
     cexpr = CompExpr(aff, val)
     bexpr = BoundExpr(cexpr, None)
     with self.assertRaises(Exception) as e:
         prob._expr_to_grb_expr(bexpr)
     self.assertTrue("Comparison" in e.exception.message)
Example #10
0
    def test_get_max_cnt_violation_leq_cnts(self):
        model = grb.Model()
        prob = Prob(model)
        dummy_var = Variable(np.zeros((1, 1)), np.zeros((1, 1)))
        f = lambda x: np.array([[1, 3]])

        f_expr = Expr(f)
        leq_expr = LEqExpr(f_expr, np.array([[1, 1]]))
        bexpr = BoundExpr(leq_expr, dummy_var)
        prob.add_cnt_expr(bexpr)
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 2.0))

        f_expr = Expr(f)
        f_expr.f = lambda x: np.array([[2, 1]])
        leq_expr.expr = f_expr
        leq_expr.val = np.array([[1, 1]])
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 1.0))

        f_expr = Expr(f)
        f_expr.f = lambda x: np.array([[2, -2]])
        leq_expr.expr = f_expr
        leq_expr.val = np.array([[1, 1]])
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 1.0))

        f_expr = Expr(f)
        f_expr.f = lambda x: np.array([[2, -2]])
        leq_expr.expr = f_expr
        leq_expr.val = np.array([[2, -2]])
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 0.0))

        f_expr = Expr(f)
        f_expr.f = lambda x: np.array([[2, 0]])
        leq_expr.expr = f_expr
        leq_expr.val = np.array([[2, -2]])
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 2.0))
Example #11
0
File: test_prob.py Project: c-l/sco
    def test_callback(self):
        x = {}
        def test():
            x[1] = 2
        callback = test
        model = grb.Model()
        prob = Prob(model, callback)

        prob.find_closest_feasible_point()
        self.assertTrue(1 in x)
        x[1] = 3
        prob.optimize()
        self.assertTrue(1 in x)
Example #12
0
File: test_prob.py Project: c-l/sco
    def test_add_obj_expr_nonquad(self):
        expr = Expr(f)
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)

        bexpr = BoundExpr(expr, var)
        prob.add_obj_expr(bexpr)

        self.assertTrue(bexpr not in prob._quad_obj_exprs)
        self.assertTrue(bexpr in prob._nonquad_obj_exprs)
        self.assertTrue(var in prob._vars)
Example #13
0
File: test_prob.py Project: c-l/sco
    def test_get_max_cnt_violation_leq_cnts(self):
        model = grb.Model()
        prob = Prob(model)
        dummy_var = Variable(np.zeros((1,1)), np.zeros((1,1)))
        f = lambda x: np.array([[1,3]])

        f_expr = Expr(f)
        leq_expr = LEqExpr(f_expr, np.array([[1,1]]))
        bexpr = BoundExpr(leq_expr, dummy_var)
        prob.add_cnt_expr(bexpr)
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 2.0))

        f_expr = Expr(f)
        f_expr.f = lambda x: np.array([[2,1]])
        leq_expr.expr = f_expr
        leq_expr.val = np.array([[1,1]])
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 1.0))

        f_expr = Expr(f)
        f_expr.f = lambda x: np.array([[2,-2]])
        leq_expr.expr = f_expr
        leq_expr.val = np.array([[1,1]])
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 1.0))

        f_expr = Expr(f)
        f_expr.f = lambda x: np.array([[2,-2]])
        leq_expr.expr = f_expr
        leq_expr.val = np.array([[2, -2]])
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 0.0))

        f_expr = Expr(f)
        f_expr.f = lambda x: np.array([[2, 0]])
        leq_expr.expr = f_expr
        leq_expr.val = np.array([[2, -2]])
        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 2.0))
Example #14
0
    def test_optimize_multidim_quad_obj(self):
        Q = np.array([[2, 0], [0, 0]])
        A = np.array([[-4, 0]])
        quad = QuadExpr(Q, A, np.zeros((1, 1)))
        model = grb.Model()
        prob = Prob(model)
        grb_var1 = model.addVar(lb=-1 * GRB.INFINITY,
                                ub=GRB.INFINITY,
                                name='x1')
        grb_var2 = model.addVar(lb=-1 * GRB.INFINITY,
                                ub=GRB.INFINITY,
                                name='x2')
        grb_vars = np.array([[grb_var1], [grb_var2]])
        var = Variable(grb_vars)

        bexpr_quad = BoundExpr(quad, var)
        prob.add_obj_expr(bexpr_quad)

        self.assertTrue(bexpr_quad in prob._quad_obj_exprs)
        self.assertTrue(var in prob._vars)

        prob.update_obj(penalty_coeff=0)
        prob.optimize()
        var_value = var.get_value()
        value = np.zeros((2, 1))
        value[0, 0] = 2
        self.assertTrue(np.allclose(var_value, value))
Example #15
0
    def test_add_obj_expr_nonquad(self):
        expr = Expr(f)
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)

        bexpr = BoundExpr(expr, var)
        prob.add_obj_expr(bexpr)

        self.assertTrue(bexpr not in prob._quad_obj_exprs)
        self.assertTrue(bexpr in prob._nonquad_obj_exprs)
        self.assertTrue(var in prob._vars)
Example #16
0
File: test_prob.py Project: c-l/sco
    def test_add_cnt_expr_eq_aff(self):
        aff = AffExpr(np.ones((1,1)), np.zeros((1,1)))
        comp = EqExpr(aff, np.array([[2]]))
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)
        model.update()

        bexpr = BoundExpr(comp, var)
        prob.add_cnt_expr(bexpr)

        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[2]])))
Example #17
0
File: test_prob.py Project: c-l/sco
    def test_add_obj_expr_quad(self):
        quad = QuadExpr(2*np.eye(1), -2*np.ones((1,1)), np.zeros((1,1)))
        aff = AffExpr(-2*np.ones((1,1)), np.zeros((1,1)))
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)

        bexpr_quad = BoundExpr(quad, var)
        bexpr_aff = BoundExpr(aff, var)
        prob.add_obj_expr(bexpr_quad)
        prob.add_obj_expr(bexpr_aff)

        self.assertTrue(bexpr_aff in prob._quad_obj_exprs)
        self.assertTrue(bexpr_quad in prob._quad_obj_exprs)
        self.assertTrue(var in prob._vars)
Example #18
0
File: test_prob.py Project: c-l/sco
    def test_find_closest_feasible_point_eq_cnts(self):
        model = grb.Model()
        prob = Prob(model)
        grb_var1 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x1')
        grb_var2 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x2')
        grb_vars = np.array([[grb_var1],[grb_var2]])
        var = Variable(grb_vars, np.zeros((2,1)))

        model.update()

        val = np.array([[5.0],[-10.0]])
        aff_expr = AffExpr(np.eye(2), np.zeros((2,1)))
        eq_expr = EqExpr(aff_expr, val)
        bexpr = BoundExpr(eq_expr, var)
        prob.add_cnt_expr(bexpr)
        prob.find_closest_feasible_point()
        self.assertTrue(np.allclose(var.get_value(), val))
Example #19
0
File: test_prob.py Project: c-l/sco
    def test_convexify_leq(self):
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)

        model.update()
        grb_cnt = model.addConstr(grb_var, GRB.EQUAL, 0)
        model.optimize()
        var.update()

        e = Expr(f)
        eq = LEqExpr(e, np.array([[4]]))
        bexpr = BoundExpr(eq, var)
        prob.add_cnt_expr(bexpr)

        prob.convexify()
        self.assertTrue(len(prob._penalty_exprs) == 1)
        self.assertTrue(isinstance(prob._penalty_exprs[0].expr, HingeExpr))
Example #20
0
    def test_optimize_just_quad_obj(self):
        quad = QuadExpr(2 * np.eye(1), -2 * np.ones((1, 1)), np.zeros((1, 1)))
        aff = AffExpr(-2 * np.ones((1, 1)), np.zeros((1, 1)))
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)

        bexpr_quad = BoundExpr(quad, var)
        bexpr_aff = BoundExpr(aff, var)
        prob.add_obj_expr(bexpr_quad)
        prob.add_obj_expr(bexpr_aff)

        self.assertTrue(bexpr_aff in prob._quad_obj_exprs)
        self.assertTrue(bexpr_quad in prob._quad_obj_exprs)
        self.assertTrue(var in prob._vars)

        prob.update_obj(penalty_coeff=0)
        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[2.0]])))
Example #21
0
    def test_find_closest_feasible_point_leq_cnts(self):
        cnt_vals = [np.ones((2,1)), np.array([[-1.0],[1.0]]), \
            np.array([[-1.0],[-1.0]])]
        true_var_vals = [np.zeros((2,1)), np.array([[-1.0],[0.0]]), \
            -1*np.ones((2,1))]

        for true_var_val, cnt_val in zip(true_var_vals, cnt_vals):
            model = grb.Model()
            prob = Prob(model)
            grb_var1 = model.addVar(lb=-1 * GRB.INFINITY,
                                    ub=GRB.INFINITY,
                                    name='x1')
            grb_var2 = model.addVar(lb=-1 * GRB.INFINITY,
                                    ub=GRB.INFINITY,
                                    name='x2')
            grb_vars = np.array([[grb_var1], [grb_var2]])
            var = Variable(grb_vars, np.zeros((2, 1)))

            model.update()

            aff_expr = AffExpr(np.eye(2), np.zeros((2, 1)))
            leq_expr = LEqExpr(aff_expr, cnt_val)
            bexpr = BoundExpr(leq_expr, var)
            prob.add_cnt_expr(bexpr)
            prob.find_closest_feasible_point()
            self.assertTrue(np.allclose(var.get_value(), true_var_val))
Example #22
0
def test_prob(ut,
              x0,
              x_true,
              f=zerofunc,
              g=neginffunc,
              h=zerofunc,
              Q=np.zeros((N, N)),
              q=np.zeros((1, N)),
              A_ineq=np.zeros((1, N)),
              b_ineq=np.zeros((1, 1)),
              A_eq=np.zeros((1, 1)),
              b_eq=np.zeros((1, 1))):

    if not np.allclose(A_eq, np.zeros((1,1)))\
        or not np.allclose(b_eq, np.zeros((1,1))):
        raise NotImplementedError
    model = grb.Model()
    prob = Prob(model)

    grb_var1 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x1')
    grb_var2 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x2')
    grb_vars = np.array([[grb_var1], [grb_var2]])
    var = Variable(grb_vars, value=x0)
    model.update()

    quad_obj = BoundExpr(QuadExpr(Q, q, np.zeros((1, 1))), var)
    prob.add_obj_expr(quad_obj)
    nonquad_obj = BoundExpr(Expr(f), var)
    prob.add_obj_expr(nonquad_obj)

    cnts = []
    lin_ineq = LEqExpr(AffExpr(A_ineq, -b_ineq), np.zeros(b_ineq.shape))
    lin_ineq = BoundExpr(lin_ineq, var)
    cnts.append(lin_ineq)

    nonlin_ineq = LEqExpr(Expr(g), np.zeros(g(np.zeros((2, 1))).shape))
    nonlin_ineq = BoundExpr(nonlin_ineq, var)
    cnts.append(nonlin_ineq)

    nonlin_eq = EqExpr(Expr(h), np.zeros(g(np.zeros((2, 1))).shape))
    nonlin_eq = BoundExpr(nonlin_eq, var)
    cnts.append(nonlin_eq)

    for cnt in cnts:
        prob.add_cnt_expr(cnt)

    solv.solve(prob, method='penalty_sqp')
    x_sol = var.get_value()
    ut.assertTrue(np.allclose(x_sol, x_true, atol=1e-4))
Example #23
0
File: test_prob.py Project: c-l/sco
    def test_find_closest_feasible_point_leq_cnts(self):
        cnt_vals = [np.ones((2,1)), np.array([[-1.0],[1.0]]), \
            np.array([[-1.0],[-1.0]])]
        true_var_vals = [np.zeros((2,1)), np.array([[-1.0],[0.0]]), \
            -1*np.ones((2,1))]

        for true_var_val, cnt_val in zip(true_var_vals, cnt_vals):
            model = grb.Model()
            prob = Prob(model)
            grb_var1 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x1')
            grb_var2 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x2')
            grb_vars = np.array([[grb_var1],[grb_var2]])
            var = Variable(grb_vars, np.zeros((2,1)))

            model.update()

            aff_expr = AffExpr(np.eye(2), np.zeros((2,1)))
            leq_expr = LEqExpr(aff_expr, cnt_val)
            bexpr = BoundExpr(leq_expr, var)
            prob.add_cnt_expr(bexpr)
            prob.find_closest_feasible_point()
            self.assertTrue(np.allclose(var.get_value(), true_var_val))
Example #24
0
File: test_prob.py Project: c-l/sco
    def test_optimize_just_quad_obj(self):
        quad = QuadExpr(2*np.eye(1), -2*np.ones((1,1)), np.zeros((1,1)))
        aff = AffExpr(-2*np.ones((1,1)), np.zeros((1,1)))
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)

        bexpr_quad = BoundExpr(quad, var)
        bexpr_aff = BoundExpr(aff, var)
        prob.add_obj_expr(bexpr_quad)
        prob.add_obj_expr(bexpr_aff)

        self.assertTrue(bexpr_aff in prob._quad_obj_exprs)
        self.assertTrue(bexpr_quad in prob._quad_obj_exprs)
        self.assertTrue(var in prob._vars)

        prob.update_obj(penalty_coeff=0)
        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[2.0]])))
Example #25
0
    def test_add_cnt_leq_aff(self):
        quad = QuadExpr(2 * np.eye(1), -2 * np.ones((1, 1)), np.zeros((1, 1)))

        aff = AffExpr(np.ones((1, 1)), np.zeros((1, 1)))
        comp = LEqExpr(aff, np.array([[-4]]))
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)
        model.update()

        bexpr_quad = BoundExpr(quad, var)
        prob.add_obj_expr(bexpr_quad)

        bexpr = BoundExpr(comp, var)
        prob.add_cnt_expr(bexpr)

        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[-4]])))
Example #26
0
    def test_get_max_cnt_violation_mult_cnts(self):
        model = grb.Model()
        prob = Prob(model)
        dummy_var = Variable(np.zeros((1, 1)), np.zeros((1, 1)))
        f1 = lambda x: np.array([[1, 3]])
        f2 = lambda x: np.array([[0, 0]])

        f1_expr = Expr(f1)
        leq_expr = LEqExpr(f1_expr, np.array([[1, 1]]))
        bexpr = BoundExpr(leq_expr, dummy_var)
        prob.add_cnt_expr(bexpr)

        f2_expr = Expr(f2)
        eq_expr = EqExpr(f2_expr, np.array([[1, 1]]))
        bexpr = BoundExpr(eq_expr, dummy_var)
        prob.add_cnt_expr(bexpr)

        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 2.0))
Example #27
0
    def test_callback(self):
        x = {}

        def test():
            x[1] = 2

        callback = test
        model = grb.Model()
        prob = Prob(model, callback)

        prob.find_closest_feasible_point()
        self.assertTrue(1 in x)
        x[1] = 3
        prob.optimize()
        self.assertTrue(1 in x)
Example #28
0
    def test_pos_grb_var_manager(self):
        model = grb.Model()
        prob = Prob(model)
        init_num = 1
        inc_num = 10
        shape = (2, 7)
        pos_grb_manager = PosGRBVarManager(model,
                                           init_num=init_num,
                                           inc_num=inc_num)
        pgm = pos_grb_manager
        PosGRBVarManager.INC_NUM = 2
        self.assertTrue(len(pgm._grb_vars) == init_num)
        var = pgm.next()
        test_grb_var_pos(self, var)
        self.assertTrue(len(pgm._grb_vars) == inc_num + init_num)
        a = pgm.get_array(shape)
        for x in a.flatten():
            test_grb_var_pos(self, x)

        self.assertTrue(a.shape == shape)
        self.assertTrue(len(pgm._grb_vars) == init_num + 2 * inc_num)
Example #29
0
    def test_add_obj_expr_quad(self):
        quad = QuadExpr(2 * np.eye(1), -2 * np.ones((1, 1)), np.zeros((1, 1)))
        aff = AffExpr(-2 * np.ones((1, 1)), np.zeros((1, 1)))
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)

        bexpr_quad = BoundExpr(quad, var)
        bexpr_aff = BoundExpr(aff, var)
        prob.add_obj_expr(bexpr_quad)
        prob.add_obj_expr(bexpr_aff)

        self.assertTrue(bexpr_aff in prob._quad_obj_exprs)
        self.assertTrue(bexpr_quad in prob._quad_obj_exprs)
        self.assertTrue(var in prob._vars)
Example #30
0
def test_prob(ut, x0, x_true, f=zerofunc, g=neginffunc, h=zerofunc,
    Q=np.zeros((N,N)), q=np.zeros((1,N)), A_ineq=np.zeros((1,N)),
    b_ineq=np.zeros((1,1)), A_eq=np.zeros((1,1)), b_eq=np.zeros((1,1))):

    if not np.allclose(A_eq, np.zeros((1,1)))\
        or not np.allclose(b_eq, np.zeros((1,1))):
        raise NotImplementedError
    model = grb.Model()
    prob = Prob(model)

    grb_var1 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x1')
    grb_var2 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x2')
    grb_vars = np.array([[grb_var1], [grb_var2]])
    var = Variable(grb_vars, value=x0)
    model.update()

    quad_obj = BoundExpr(QuadExpr(Q, q, np.zeros((1,1))), var)
    prob.add_obj_expr(quad_obj)
    nonquad_obj = BoundExpr(Expr(f), var)
    prob.add_obj_expr(nonquad_obj)

    cnts = []
    lin_ineq = LEqExpr(AffExpr(A_ineq, -b_ineq), np.zeros(b_ineq.shape))
    lin_ineq = BoundExpr(lin_ineq, var)
    cnts.append(lin_ineq)

    nonlin_ineq = LEqExpr(Expr(g), np.zeros(g(np.zeros((2,1))).shape))
    nonlin_ineq = BoundExpr(nonlin_ineq, var)
    cnts.append(nonlin_ineq)

    nonlin_eq = EqExpr(Expr(h), np.zeros(g(np.zeros((2,1))).shape))
    nonlin_eq = BoundExpr(nonlin_eq, var)
    cnts.append(nonlin_eq)

    for cnt in cnts:
        prob.add_cnt_expr(cnt)

    solv.solve(prob, method='penalty_sqp')
    x_sol = var.get_value()
    ut.assertTrue(np.allclose(x_sol, x_true, atol=1e-4))
Example #31
0
File: test_prob.py Project: c-l/sco
    def test_get_max_cnt_violation_mult_cnts(self):
        model = grb.Model()
        prob = Prob(model)
        dummy_var = Variable(np.zeros((1,1)), np.zeros((1,1)))
        f1 = lambda x: np.array([[1,3]])
        f2 = lambda x: np.array([[0,0]])

        f1_expr = Expr(f1)
        leq_expr = LEqExpr(f1_expr, np.array([[1,1]]))
        bexpr = BoundExpr(leq_expr, dummy_var)
        prob.add_cnt_expr(bexpr)

        f2_expr = Expr(f2)
        eq_expr = EqExpr(f2_expr, np.array([[1,1]]))
        bexpr = BoundExpr(eq_expr, dummy_var)
        prob.add_cnt_expr(bexpr)

        self.assertTrue(np.allclose(prob.get_max_cnt_violation(), 2.0))
Example #32
0
File: test_prob.py Project: c-l/sco
    def test_optimize_multidim_quad_obj(self):
        Q = np.array([[2,0], [0,0]])
        A = np.array([[-4, 0]])
        quad = QuadExpr(Q, A, np.zeros((1,1)))
        model = grb.Model()
        prob = Prob(model)
        grb_var1 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x1')
        grb_var2 = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x2')
        grb_vars = np.array([[grb_var1], [grb_var2]])
        var = Variable(grb_vars)

        bexpr_quad = BoundExpr(quad, var)
        prob.add_obj_expr(bexpr_quad)

        self.assertTrue(bexpr_quad in prob._quad_obj_exprs)
        self.assertTrue(var in prob._vars)

        prob.update_obj(penalty_coeff=0)
        prob.optimize()
        var_value = var.get_value()
        value = np.zeros((2,1))
        value[0,0] = 2
        self.assertTrue(np.allclose(var_value, value))
Example #33
0
    def test_convexify_leq(self):
        model = grb.Model()
        prob = Prob(model)
        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)

        model.update()
        grb_cnt = model.addConstr(grb_var, GRB.EQUAL, 0)
        model.optimize()
        var.update()

        e = Expr(f)
        eq = LEqExpr(e, np.array([[4]]))
        bexpr = BoundExpr(eq, var)
        prob.add_cnt_expr(bexpr)

        prob.convexify()
        self.assertTrue(len(prob._penalty_exprs) == 1)
        self.assertTrue(isinstance(prob._penalty_exprs[0].expr, HingeExpr))
Example #34
0
    def test_find_closest_feasible_point_eq_cnts(self):
        model = grb.Model()
        prob = Prob(model)
        grb_var1 = model.addVar(lb=-1 * GRB.INFINITY,
                                ub=GRB.INFINITY,
                                name='x1')
        grb_var2 = model.addVar(lb=-1 * GRB.INFINITY,
                                ub=GRB.INFINITY,
                                name='x2')
        grb_vars = np.array([[grb_var1], [grb_var2]])
        var = Variable(grb_vars, np.zeros((2, 1)))

        model.update()

        val = np.array([[5.0], [-10.0]])
        aff_expr = AffExpr(np.eye(2), np.zeros((2, 1)))
        eq_expr = EqExpr(aff_expr, val)
        bexpr = BoundExpr(eq_expr, var)
        prob.add_cnt_expr(bexpr)
        prob.find_closest_feasible_point()
        self.assertTrue(np.allclose(var.get_value(), val))
Example #35
0
File: test_prob.py Project: c-l/sco
    def test_get_approx_value_lin_constr(self):
        """
        min x^2 st. x == 4
        when convexified,
        min x^2 + penalty_coeff*|x-4|
        when penalty_coeff == 1, solution is x = 0.5 and the value is 3.75
        (according to Wolfram Alpha)

        when penalty_coeff == 2, solution is x = 1.0 and the value is 7.0
        (according to Wolfram Alpha)
        """
        quad = QuadExpr(2*np.eye(1), np.zeros((1,1)), np.zeros((1,1)))
        e = Expr(f)
        eq = EqExpr(e, np.array([[4]]))

        model = grb.Model()
        prob = Prob(model)

        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)
        model.update()

        obj = BoundExpr(quad, var)
        prob.add_obj_expr(obj)
        bexpr = BoundExpr(eq, var)
        prob.add_cnt_expr(bexpr)

        prob.optimize() # needed to set an initial value
        prob.convexify()
        prob.update_obj(penalty_coeff=1.0)
        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[0.5]])))
        self.assertTrue(np.allclose(prob.get_approx_value(1.0), np.array([[3.75]])))

        prob.update_obj(penalty_coeff=2.0)
        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[1.0]])))
        self.assertTrue(np.allclose(prob.get_approx_value(2.0), np.array([[7]])))
Example #36
0
File: test_prob.py Project: c-l/sco
    def test_get_value_and_get_approx_value_nonlin_constr(self):
        """
        min x^2 -2x + 1 st. x^2 == 4
        when convexified at x = 1,
        min x^2 -2x + 1 + penalty_coeff*|2x-5|
        when penalty_coeff == 0.5, solution is x = 1.5 and the value is 1.25
        (according to Wolfram Alpha)

        approx value should be 1.25
        value should be 1.125
        """
        quad = QuadExpr(2*np.eye(1), -2*np.ones((1,1)), np.ones((1,1)))
        quad_cnt = QuadExpr(2*np.eye(1), np.zeros((1,1)), np.zeros((1,1)))
        eq = EqExpr(quad_cnt, np.array([[4]]))

        model = grb.Model()
        prob = Prob(model)

        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars, np.array([[1.0]]))
        model.update()

        obj = BoundExpr(quad, var)
        prob.add_obj_expr(obj)
        bexpr = BoundExpr(eq, var)
        prob.add_cnt_expr(bexpr)

        prob.convexify()
        prob.update_obj(penalty_coeff=0.5)
        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[1.5]])))
        self.assertTrue(np.allclose(prob.get_approx_value(0.5), np.array([[1.25]])))
        self.assertTrue(np.allclose(prob.get_value(0.5), np.array([[1.125]])))
class RumourSpreadModel:
    def __init__(self,
                 num_nodes,
                 num_bits,
                 node_capacity,
                 conservation_factor,
                 confidence_factor,
                 init_num_nodes,
                 alpha,
                 beta,
                 gamma,
                 delta_in,
                 delta_out,
                 plot_degree_dist=False):
        self.num_nodes = num_nodes
        self.num_bits = num_bits
        self.prob = Prob(num_bits, conservation_factor, confidence_factor)
        self.scale_free_graph = generate_scale_free(num_nodes, init_num_nodes,
                                                    alpha, beta, gamma,
                                                    delta_in, delta_out)
        self.nodes_memory = [
            MemoryQueue(node_capacity) for _ in range(num_nodes)
        ]

        if plot_degree_dist:
            plot_degree_distribution(
                self.scale_free_graph.compute_outdegree_distribution(),
                int(0.08 * num_nodes), 'Outdegree Distribution')

            plot_degree_distribution(
                self.scale_free_graph.compute_indegree_distribution(),
                int(0.08 * num_nodes), 'Indegree Distribution')

    def get_graph(self):

        return self.scale_free_graph

    def get_nodes_memory(self):

        return self.nodes_memory

    def distort_info(self, x):

        bit_pos = randint(0, self.num_bits - 1)
        return (x ^ (1 << bit_pos))

    def get_distorted_info(self):

        distorted_info = []
        for node_memory in self.nodes_memory:

            if node_memory.is_empty():
                distorted_info.append(None)
                continue

            most_freq_info = node_memory.get_most_freq_elem()
            distortion_prob = self.prob.compute_distortion_prob(
                node_memory.compute_entropy())

            if random() <= distortion_prob:
                dist_info = self.distort_info(most_freq_info)
                node_memory.distort_in_memory(most_freq_info, dist_info)
                distorted_info.append(dist_info)
            else:
                distorted_info.append(most_freq_info)

        return distorted_info

    def update_node_memory(self, buffer_info):

        nodes_outdegree = self.scale_free_graph.compute_outdegrees()
        max_nbr_outdegree = [0] * self.num_nodes
        min_nbr_outdegree = [self.num_nodes] * self.num_nodes

        for node in range(self.num_nodes):
            nbr_list = self.scale_free_graph.adj_list[node]
            degree = nodes_outdegree[node]

            for nbr in nbr_list:
                max_nbr_outdegree[nbr] = max(max_nbr_outdegree[nbr], degree)
                min_nbr_outdegree[nbr] = min(min_nbr_outdegree[nbr], degree)

        for node in range(self.num_nodes):

            if buffer_info[node] is None:
                continue

            nbr_list = self.scale_free_graph.adj_list[node]
            degree = nodes_outdegree[node]

            for nbr in nbr_list:
                acceptance_prob = self.prob.compute_acceptance_prob(
                    degree, max_nbr_outdegree[nbr], min_nbr_outdegree[nbr])

                if random() <= acceptance_prob:
                    self.nodes_memory[nbr].insert(buffer_info[node])

    def inject_info(self, info_propagators):

        for node, info in info_propagators.items():
            self.nodes_memory[node].insert(info)

    def simulate_step(self):

        distorted_info = self.get_distorted_info()
        self.update_node_memory(distorted_info)

    def simulate(self, info_propagators, time_steps, callback_list):

        self.inject_info(info_propagators)
        for t in range(time_steps):
            self.simulate_step()

            for callback in callback_list:
                callback.call_after_step(self, t)

        return [callback.get_result() for callback in callback_list]
Example #38
0
    def test_get_value_and_get_approx_value_nonlin_constr(self):
        """
        min x^2 -2x + 1 st. x^2 == 4
        when convexified at x = 1,
        min x^2 -2x + 1 + penalty_coeff*|2x-5|
        when penalty_coeff == 0.5, solution is x = 1.5 and the value is 1.25
        (according to Wolfram Alpha)

        approx value should be 1.25
        value should be 1.125
        """
        quad = QuadExpr(2 * np.eye(1), -2 * np.ones((1, 1)), np.ones((1, 1)))
        quad_cnt = QuadExpr(2 * np.eye(1), np.zeros((1, 1)), np.zeros((1, 1)))
        eq = EqExpr(quad_cnt, np.array([[4]]))

        model = grb.Model()
        prob = Prob(model)

        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars, np.array([[1.0]]))
        model.update()

        obj = BoundExpr(quad, var)
        prob.add_obj_expr(obj)
        bexpr = BoundExpr(eq, var)
        prob.add_cnt_expr(bexpr)

        prob.convexify()
        prob.update_obj(penalty_coeff=0.5)
        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[1.5]])))
        self.assertTrue(
            np.allclose(prob.get_approx_value(0.5), np.array([[1.25]])))
        self.assertTrue(np.allclose(prob.get_value(0.5), np.array([[1.125]])))
Example #39
0
    def test_get_approx_value_lin_constr(self):
        """
        min x^2 st. x == 4
        when convexified,
        min x^2 + penalty_coeff*|x-4|
        when penalty_coeff == 1, solution is x = 0.5 and the value is 3.75
        (according to Wolfram Alpha)

        when penalty_coeff == 2, solution is x = 1.0 and the value is 7.0
        (according to Wolfram Alpha)
        """
        quad = QuadExpr(2 * np.eye(1), np.zeros((1, 1)), np.zeros((1, 1)))
        e = Expr(f)
        eq = EqExpr(e, np.array([[4]]))

        model = grb.Model()
        prob = Prob(model)

        grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x')
        grb_vars = np.array([[grb_var]])
        var = Variable(grb_vars)
        model.update()

        obj = BoundExpr(quad, var)
        prob.add_obj_expr(obj)
        bexpr = BoundExpr(eq, var)
        prob.add_cnt_expr(bexpr)

        prob.optimize()  # needed to set an initial value
        prob.convexify()
        prob.update_obj(penalty_coeff=1.0)
        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[0.5]])))
        self.assertTrue(
            np.allclose(prob.get_approx_value(1.0), np.array([[3.75]])))

        prob.update_obj(penalty_coeff=2.0)
        prob.optimize()
        self.assertTrue(np.allclose(var.get_value(), np.array([[1.0]])))
        self.assertTrue(
            np.allclose(prob.get_approx_value(2.0), np.array([[7]])))