Exemplo n.º 1
0
    def test01_objfunc_rejects_float_idx(self):
        lp = LP()

        self.assertRaises(
            ValueError,
            lambda: lp.setObjective((ar([0, 1.1, 2], dtype=float64),
                                     ar([1, 1, 1], dtype=float64))))
Exemplo n.º 2
0
    def test01_constraint_rejects_float_idx(self):
        lp = LP()

        self.assertRaises(
            ValueError,
            lambda: lp.addConstraint((ar([0, 1.1, 2], dtype=float64),
                                      ar([1, 1, 1], dtype=float64)), ">=", 1))
Exemplo n.º 3
0
        def getLP():

            lp = LP()

            for c, t, b in constraint_arg_list:
                lp.addConstraint(c,t,b)

            lp.setObjective(objective)

            return lp
Exemplo n.º 4
0
    def testOptionRetrieval_BadValues_01(self):

        lp = LP()

        self.assert_(lp.getOption("presolve_rows") == False)

        self.assertRaises(ValueError,
                          lambda: lp.setOption("presolve_rows", True, bad_option = None))

        self.assert_(lp.getOption("presolve_rows") == False)
        self.assert_(lp.getOptionDict()["presolve_rows"] == False)
Exemplo n.º 5
0
    def testOptionRetrieval_BadValues_02(self):

        lp = LP()

        self.assert_(lp.getOption("presolve_rows") == False)

        self.assertRaises(TypeError,
                          lambda: lp.setOption(None, True, presolve_rows = True))

        self.assert_(lp.getOption("presolve_rows") == False)
        self.assert_(lp.getOptionDict()["presolve_rows"] == False)
Exemplo n.º 6
0
    def testOptionRetrieval03(self):

        lp = LP()

        self.assert_(lp.getOption("presolve_rows") == False)

        lp.setOption("presolve_cols", True, presolve_rows = True)
        
        self.assert_(lp.getOption("presolve_rows") == True)
        self.assert_(lp.getOptionDict()["presolve_rows"] == True)

        self.assert_(lp.getOption("presolve_cols") == True)
        self.assert_(lp.getOptionDict()["presolve_cols"] == True)
Exemplo n.º 7
0
    def checkInconsistentSubarrays(self, opts):

        values = {}

        indices = {}
        indices["t"] = (0,3)
        indices["n"] = "a"
        indices["N"] = "a"
        indices["l"] = [0,1,2]
        indices["a"] = ar([0,1,2],dtype=uint)
        indices["f"] = ar([0,1,2],dtype=float64)
        indices["e"] = None  # empty

        A = [[1,0,  0],
             [0,1],      # inconsistent; does this get caught?
             [0,0.5,0]]

        values = {}
        values["L"] = A
        values["l"] = [ar(le) for le in A]
        values["B"] = [[1, 0, 0], [[1,0,0]], [0,1,1]]
        values["C"] = ones((1,3,3) )
        values["D"] = [[1, 0, 0], [1,1,[1]], [0,1,1]]
        values["E"] = [[1, 0, 0], (1,1,1), [0,1,1]]

        targets = {}
        targets["s"] = 1
        targets["l"] = [1,1,1]
        targets["a"] = ar([1,1,1],dtype=uint)
        targets["f"] = ar([1,1,1],dtype=float64)

        lp = LP()

        if opts[0] == "N":
            lp.getIndexBlock(indices["N"], 3)

        io = indices[opts[0]]
        vl = values [opts[1]]
        tr = targets[opts[2]]
        ob = [1,2,3]
        
        if io is None:
            self.assertRaises(ValueError, lambda: lp.addConstraint(vl, ">=", tr))
        else:
            self.assertRaises(ValueError, lambda: lp.addConstraint( (io, vl), ">=", tr))
Exemplo n.º 8
0
    def testOptionRetrieval03(self):

        lp = LP()

        self.assert_(lp.getOption("presolve_rows") == False)

        lp.setOption("presolve_cols", True, presolve_rows = True)

        self.assert_(lp.getOption("presolve_rows") == True)
        self.assert_(lp.getOptionDict()["presolve_rows"] == True)

        self.assert_(lp.getOption("presolve_cols") == True)
        self.assert_(lp.getOptionDict()["presolve_cols"] == True)
Exemplo n.º 9
0
        def getLP():

            lp = LP()

            for c, t, b in constraint_arg_list:
                lp.addConstraint(c, t, b)

            lp.setObjective(objective)

            return lp
Exemplo n.º 10
0
    def testOptionRetrieval_BadValues_02(self):

        lp = LP()

        self.assert_(lp.getOption("presolve_rows") == False)

        self.assertRaises(TypeError,
                          lambda: lp.setOption(None, True, presolve_rows = True))
        
        self.assert_(lp.getOption("presolve_rows") == False)
        self.assert_(lp.getOptionDict()["presolve_rows"] == False)
Exemplo n.º 11
0
    def testOptionRetrieval_BadValues_01(self):

        lp = LP()

        self.assert_(lp.getOption("presolve_rows") == False)

        self.assertRaises(ValueError,
                          lambda: lp.setOption("presolve_rows", True, bad_option = None))
        
        self.assert_(lp.getOption("presolve_rows") == False)
        self.assert_(lp.getOptionDict()["presolve_rows"] == False)
Exemplo n.º 12
0
    def checkInconsistentSubarrays(self, opts):

        values = {}

        indices = {}
        indices["t"] = (0, 3)
        indices["n"] = "a"
        indices["N"] = "a"
        indices["l"] = [0, 1, 2]
        indices["a"] = ar([0, 1, 2], dtype=uint)
        indices["f"] = ar([0, 1, 2], dtype=float64)
        indices["e"] = None  # empty

        A = [
            [1, 0, 0],
            [0, 1],  # inconsistent; does this get caught?
            [0, 0.5, 0]
        ]

        values = {}
        values["L"] = A
        values["l"] = [ar(le) for le in A]
        values["B"] = [[1, 0, 0], [[1, 0, 0]], [0, 1, 1]]
        values["C"] = ones((1, 3, 3))
        values["D"] = [[1, 0, 0], [1, 1, [1]], [0, 1, 1]]
        values["E"] = [[1, 0, 0], (1, 1, 1), [0, 1, 1]]

        targets = {}
        targets["s"] = 1
        targets["l"] = [1, 1, 1]
        targets["a"] = ar([1, 1, 1], dtype=uint)
        targets["f"] = ar([1, 1, 1], dtype=float64)

        lp = LP()

        if opts[0] == "N":
            lp.getIndexBlock(indices["N"], 3)

        io = indices[opts[0]]
        vl = values[opts[1]]
        tr = targets[opts[2]]
        ob = [1, 2, 3]

        if io is None:
            self.assertRaises(ValueError,
                              lambda: lp.addConstraint(vl, ">=", tr))
        else:
            self.assertRaises(ValueError, lambda: lp.addConstraint(
                (io, vl), ">=", tr))
Exemplo n.º 13
0
def lpsolve_infer(ims, prev_boxes, cur_boxes, next_boxes, fw_masks, cur_masks,
                  bw_masks, shift_arr):
    picked_boxes = []
    picked_masks = []
    y_labels = []
    ave_iou = []
    frm_num = len(fw_masks)

    ## calculate the pairwise items based on maskIoU
    pairwise_arr = get_pairwise_arr(ims, prev_boxes, cur_boxes, next_boxes,
                                    fw_masks, cur_masks, bw_masks, shift_arr)

    tmp_masks = []
    for frm_id in xrange(frm_num):
        tmp_masks.append(fw_masks[frm_id])
        tmp_masks.append(cur_masks[frm_id])
        tmp_masks.append(bw_masks[frm_id])
    all_masks = np.asarray(tmp_masks)

    tmp_bboxes = []
    for frm_id in xrange(frm_num):
        tmp_bboxes.append(prev_boxes[frm_id])
        tmp_bboxes.append(cur_boxes[frm_id])
        tmp_bboxes.append(next_boxes[frm_id])
    all_boxes = np.asarray(tmp_bboxes)

    ##====================================================== Construct Graph begining============================================================##
    ##(0)set up parameters:
    edge_num = frm_num * 9 - 3
    node_num = frm_num * 3 + 2
    var_len = edge_num + node_num

    ##(1)set node and edge index
    ## 1.1 val_indexes
    val_indexes = np.zeros(var_len, dtype=int)
    for val_id in xrange(var_len):
        val_indexes[val_id] = val_id

    ##------------------------------------------------------------node indexes------------------------------------------------------------
    ##1.2 node_indexes
    node_indexes = np.zeros(node_num, dtype=int)
    node_indexes[0] = 0  #source node
    node_indexes[-1] = var_len - 1  #sink node

    ##1.2.1 (indexes of(node) in val_indexes)
    for frm_id in xrange(frm_num):
        node_id1 = frm_id * 12 + 4

        if frm_id == frm_num - 1:  ##last frame
            node_id2 = node_id1 + 1
            node_id3 = node_id1 + 2
        else:
            node_id2 = node_id1 + 4  ## other frames
            node_id3 = node_id1 + 8
        t_nodes = [node_id1, node_id2, node_id3]

        ##1.2.2 (indexes of (node)in node_indexes)
        t_id1 = (frm_id + 1) * 3 - 2
        t_id3 = t_id1 + 2
        node_indexes[t_id1:t_id3 + 1] = t_nodes

    ##--------------------------------------------------------------edge indexes--------------------------------------------------------
    ##1.3 edge_indexes
    edge_indexes = np.asarray(list(set(val_indexes) - set(node_indexes)))

    ##-------------------------------------------------------------Coeficient vector-----------------------------------------------------
    ##(2) set cofficent vector
    coef_vec = np.zeros((var_len))

    ##2.1 node cofficient
    coef_vec[node_indexes] = 1  ##set all the node(unary term) as 1

    ##2.2 edge cofficient
    coef_vec[1:4] = 1  #the first three edges linked to the source node
    coef_vec[-4:-1] = 1  #the last three edges linked to the sink node

    ##set up pairwise term(edges)
    pairwise_indexes = edge_indexes[3:-3]
    coef_vec[pairwise_indexes] = pairwise_arr

    print 'pairwise_indexes:', pairwise_indexes
    print pairwise_indexes.shape
    print 'pairwise_arr:', pairwise_arr
    print pairwise_arr.shape

    ##=================================================================Equation constraints========================##
    ## AX=B
    equ_num = 2 + (
        frm_num
    ) * 3 * 2  ## 2 for first and last node(with 3 edges) +  frm_num*6 for every frame(3 nodes with each one with 2)

    ##(3) set A Matrix
    a_mat = np.zeros((equ_num, var_len))

    ##3.1
    a_mat[0,
          1:4] = 1  ## three edges flow out from the source node   x1+x2+x3=1
    a_mat[
        -1, -4:
        -1] = 1  ## three edges flow into the sink node       x(-1)+x(-2)+x(-3)=1

    ##3.2
    ##the first three edges and the three nodes(in the frist frame)
    a_mat[1, 1] = a_mat[2, 2] = a_mat[3, 3] = -1  #x1=x4, x2=x8, x3=x12
    a_mat[1, 4] = a_mat[2, 8] = a_mat[3, 12] = 1

    ##the last three edges and the three nodes(in the last frame)
    a_mat[equ_num - 4, var_len -
          4] = a_mat[equ_num - 3, var_len -
                     3] = a_mat[equ_num - 2, var_len -
                                2] = 1  #x(-1)=x(-4), x(-2)=x(-8), x(-3)=x(-12)
    a_mat[equ_num - 4,
          var_len - 7] = a_mat[equ_num - 3,
                               var_len - 6] = a_mat[equ_num - 2,
                                                    var_len - 5] = -1

    ##3.3
    ##outflow constraints(1 node to 3 edges)
    row_idx = 4
    for frm_id in xrange(frm_num - 1):
        t_base = frm_id * 3 + 1
        for idx in xrange(3):
            t_id = [t_base + idx]
            src_node_idx = node_indexes[t_id]
            brh_edge_idxes = val_indexes[int(src_node_idx +
                                             1):int(src_node_idx + 4)]
            a_mat[row_idx, src_node_idx] = -1
            a_mat[row_idx, brh_edge_idxes] = 1
            row_idx = row_idx + 1

    ##3.3
    ##inflow constraints(3 edges to 1 node)
    for frm_id in xrange(frm_num - 1):
        t_edge_base = frm_id * 9 + 3

        frm_id1 = frm_id + 1
        t_node_base = frm_id1 * 3 + 1  ##node base
        for idx in xrange(3):
            t_node_id = [t_node_base + idx]
            dest_node_idx = node_indexes[t_node_id]
            t_edge_id = [t_edge_base + idx]
            src_edge_id = edge_indexes[t_edge_id][0]
            src_edge_idxes = np.asarray(
                [src_edge_id, src_edge_id + 4, src_edge_id + 8])
            a_mat[row_idx, dest_node_idx] = -1
            a_mat[row_idx, src_edge_idxes] = 1
            row_idx = row_idx + 1

    ##4. set B Vector
    b_vec = np.zeros(equ_num)
    b_vec[0] = b_vec[-1] = 1

    ##===============================================================================Solvers=========================================================
    lp = LP()
    lp.addConstraint(a_mat, "=", b_vec)

    # ##all variables
    lp.setBinary(val_indexes)

    # #set objective
    lp.setObjective(coef_vec, mode='maximize')

    lp.solve()
    val_y = lp.getSolution()

    ##----------------------------------------------------------------------------------------------------------------------------------------
    ## map choosen nodes
    chosen_nodes = val_y[node_indexes]
    y = np.where(chosen_nodes[1:-1] > 0)[0]
    y_labels = np.asarray(y)
    picked_masks = all_masks[y_labels]
    picked_boxes = all_boxes[y_labels]

    ## calculate the edge iou.
    chosen_edges = val_y[edge_indexes]
    e = np.where(chosen_edges[3:-3] > 0)[0]
    e_labels = np.asarray(e)
    ave_iou = np.sum(pairwise_arr[e_labels]) / (frm_num - 1)
    print 'average iou:', ave_iou
    print 'y_label:', y_labels
    return picked_boxes, picked_masks, y_labels, ave_iou
Exemplo n.º 14
0
    def checkLB(self, opts, lb):

        # these are indices to bound
        indices = {}
        indices["t"] = (0,3)
        indices["N"] = "a"
        indices["l"] = [0,1,2]
        indices["a"] = ar([0,1,2],dtype=uint)
        indices["f"] = ar([0,1,2],dtype=float64)

        lbvalues = {}
        lbvalues["s"] = lb
        lbvalues["l"] = [lb, lb, lb]
        lbvalues["a"] = ar([lb, lb, lb])

        lp = LP()

        if opts[0] == "N":
            lp.getIndexBlock(indices["N"], 3)

        lp.setObjective([1,1,1,1,1,1])

        lp.setLowerBound(indices[opts[0]], lbvalues[opts[1]])

        for num_times in range(2):  # make sure it's same anser second time
            lp.solve()

            self.assertAlmostEqual(lp.getObjectiveValue(), lb*3)

            v = lp.getSolution()

            self.assert_(len(v) == 6)
            self.assertAlmostEqual(v[0], lb)
            self.assertAlmostEqual(v[1], lb)
            self.assertAlmostEqual(v[2], lb)

            self.assertAlmostEqual(v[3], 0)
            self.assertAlmostEqual(v[4], 0)
            self.assertAlmostEqual(v[5], 0)
Exemplo n.º 15
0
    def checkUB(self, opts, ub):

        # these are indices to bound
        indices = {}
        indices["t"] = (0,3)
        indices["N"] = "a"
        indices["l"] = [0,1,2]
        indices["a"] = ar([0,1,2],dtype=uint)
        indices["f"] = ar([0,1,2],dtype=float64)

        ubvalues = {}
        ubvalues["s"] = ub
        ubvalues["l"] = [ub, ub, ub]
        ubvalues["a"] = ar([ub, ub, ub])

        lp = LP()

        if opts[0] == "N":
            lp.getIndexBlock(indices["N"], 3)

        lp.setObjective([1,1,1,1,1,1])
        lp.addConstraint( ((3,6), [[1,0,0],[0,1,0],[0,0,1]]), "<=", 10)
        lp.setMaximize()

        lp.setLowerBound(indices[opts[0]], None)
        lp.setUpperBound(indices[opts[0]], ubvalues[opts[1]])

        for num_times in range(2):  # make sure it's same anser second time
            lp.solve()

            self.assertAlmostEqual(lp.getObjectiveValue(), ub*3 + 10 * 3)

            v = lp.getSolution()

            self.assert_(len(v) == 6)
            self.assertAlmostEqual(v[0], ub)
            self.assertAlmostEqual(v[1], ub)
            self.assertAlmostEqual(v[2], ub)

            self.assertAlmostEqual(v[3], 10)
            self.assertAlmostEqual(v[4], 10)
            self.assertAlmostEqual(v[5], 10)
Exemplo n.º 16
0
    def test04_bad_size_05(self):
        lp = LP()

        self.assertRaises(ValueError, lambda: lp.getIndexBlock(0, 2))
Exemplo n.º 17
0
    def test01_r(self):
        lp = LP()

        self.assert_(lp.getIndexBlock("a1", 2) == (0, 2))
Exemplo n.º 18
0
    def checkBadSizingTooSmall(self, opts):

        lp = LP()

        def run_test(c_arg, o_arg):
            if opts[-1] == "c":
                self.assertRaises(ValueError,
                                  lambda: lp.addConstraint(c_arg, ">", 1))
            elif opts[-1] == "o":
                self.assertRaises(ValueError, lambda: lp.setObjective(o_arg))
            else:
                assert False

        indices = {}
        indices["t"] = (0, 5)
        indices["N"] = "a"
        indices["l"] = [0, 1, 2, 3, 4]
        indices["a"] = ar([0, 1, 2, 3, 4])
        indices["f"] = ar([0, 1, 2, 3, 4], dtype=float64)

        weights = {}
        weights["l"] = [1, 1, 1, 1]
        weights["a"] = ar([1, 1, 1, 1])
        weights["f"] = ar([1, 1, 1, 1])

        obj_func = {}
        obj_func["l"] = [1, 2, 3, 4]
        obj_func["a"] = ar([1, 2, 3, 4])
        obj_func["f"] = ar([1, 2, 3, 4], dtype=float64)

        # Some ones used in the dict's case
        il = indices["l"]
        assert len(il) == 5

        wl = weights["l"]
        assert len(wl) == 4

        ol = obj_func["l"]
        assert len(ol) == 4

        if opts[0] == "d" or opts[0] == "T":

            if opts[1] == "2":
                lp.getIndexBlock("b", 3)
                cd = [("a", wl[:2]), ("b", wl[2:])]
                od = [("a", ol[:2]), ("b", ol[2:])]

            elif opts[1] == "4":
                cd = [((0, 2), wl[:2]), ((2, 5), wl[2:])]
                od = [((0, 2), ol[:2]), ((2, 5), ol[2:])]

            elif opts[1] == "5":  # bad for out of order
                cd = [("a", wl[:2]), ((2, 5), wl[2:])]
                od = [("a", ol[:2]), ((2, 5), ol[2:])]

            elif opts[1] in indices.keys() and opts[2] in weights.keys():

                if "N" in opts:
                    lp.getIndexBlock(indices["N"], 5)

                cd = [(indices[opts[1]], weights[opts[2]])]
                od = [(indices[opts[1]], obj_func[opts[2]])]
            else:
                assert False

            if opts[0] == "d":
                run_test(dict(cd), dict(od))
                return
            elif opts[0] == "T":
                run_test(cd, od)
                return
            else:
                assert False
        else:
            assert len(opts) == 3

            # No little n option here
            if "N" in opts:
                lp.getIndexBlock(indices["N"], 5)

            run_test((indices[opts[0]], weights[opts[1]]),
                     (indices[opts[0]], obj_func[opts[1]]))
            return
Exemplo n.º 19
0
    def test03_bad_recall(self):
        lp = LP()

        self.assert_(lp.getIndexBlock(2, "a1") == (0, 2))
        self.assert_(lp.getIndexBlock(4, "a2") == (2, 6))
        self.assertRaises(ValueError, lambda: lp.getIndexBlock(3, "a1"))
Exemplo n.º 20
0
    def test01_constraint_rejects_float_idx(self):
        lp = LP()

        self.assertRaises(ValueError,
                          lambda: lp.addConstraint( (ar([0, 1.1, 2],dtype=float64), ar([1,1,1],dtype=float64) ), ">=", 1))
Exemplo n.º 21
0
    def test02(self):
        lp = LP()

        self.assert_(lp.getIndexBlock(2, "a1") == (0, 2))
        self.assert_(lp.getIndexBlock(4, "a2") == (2, 6))
        self.assert_(lp.getIndexBlock("a1") == (0, 2))
Exemplo n.º 22
0
    def checkLBUBMix(self, opts, lb, ub):

        # these are indices to bound
        lbindices = (0, 3)

        ubindices = {}
        ubindices["t"] = (3, 6)
        ubindices["n"] = "a"
        ubindices["N"] = "a"
        ubindices["l"] = [3, 4, 5]
        ubindices["a"] = ar([3, 4, 5], dtype=uint)
        ubindices["f"] = ar([3, 4, 5], dtype=float64)

        ubvalues = {}
        ubvalues["s"] = ub
        ubvalues["l"] = [ub, ub, ub]
        ubvalues["a"] = ar([ub, ub, ub])

        lbvalues = {}
        lbvalues["s"] = lb
        lbvalues["l"] = [lb, lb, lb]
        lbvalues["a"] = ar([lb, lb, lb])

        lp = LP()

        lp.setLowerBound(lbindices, lbvalues[opts[1]])

        if opts[0] == "N":
            lp.getIndexBlock(ubindices["N"], 3)

        lp.setUpperBound(ubindices[opts[0]], ubvalues[opts[1]])

        lp.setObjective([1, 1, 1, -1, -1, -1])

        for num_times in range(2):  # make sure it's same anser second time
            lp.solve()

            self.assertAlmostEqual(lp.getObjectiveValue(), lb * 3 - ub * 3)

            v = lp.getSolution()

            self.assert_(len(v) == 6)
            self.assertAlmostEqual(v[0], lb)
            self.assertAlmostEqual(v[1], lb)
            self.assertAlmostEqual(v[2], lb)

            self.assertAlmostEqual(v[3], ub)
            self.assertAlmostEqual(v[4], ub)
            self.assertAlmostEqual(v[5], ub)
Exemplo n.º 23
0
    def checkUB(self, opts, ub):

        # these are indices to bound
        indices = {}
        indices["t"] = (0, 3)
        indices["N"] = "a"
        indices["l"] = [0, 1, 2]
        indices["a"] = ar([0, 1, 2], dtype=uint)
        indices["f"] = ar([0, 1, 2], dtype=float64)

        ubvalues = {}
        ubvalues["s"] = ub
        ubvalues["l"] = [ub, ub, ub]
        ubvalues["a"] = ar([ub, ub, ub])

        lp = LP()

        if opts[0] == "N":
            lp.getIndexBlock(indices["N"], 3)

        lp.setObjective([1, 1, 1, 1, 1, 1])
        lp.addConstraint(((3, 6), [[1, 0, 0], [0, 1, 0], [0, 0, 1]]), "<=", 10)
        lp.setMaximize()

        lp.setLowerBound(indices[opts[0]], None)
        lp.setUpperBound(indices[opts[0]], ubvalues[opts[1]])

        for num_times in range(2):  # make sure it's same anser second time
            lp.solve()

            self.assertAlmostEqual(lp.getObjectiveValue(), ub * 3 + 10 * 3)

            v = lp.getSolution()

            self.assert_(len(v) == 6)
            self.assertAlmostEqual(v[0], ub)
            self.assertAlmostEqual(v[1], ub)
            self.assertAlmostEqual(v[2], ub)

            self.assertAlmostEqual(v[3], 10)
            self.assertAlmostEqual(v[4], 10)
            self.assertAlmostEqual(v[5], 10)
Exemplo n.º 24
0
    def test01(self):
        lp = LP()

        self.assert_(lp.getIndexBlock(2, "a1") == (0, 2))
Exemplo n.º 25
0
    def test04_bad_size_05(self):
        lp = LP()

        self.assertRaises(ValueError, lambda: lp.getIndexBlock(0, 2))
Exemplo n.º 26
0
    def test04_bad_size_04(self):
        lp = LP()

        self.assertRaises(ValueError, lambda: lp.getIndexBlock("a1", "a2"))
Exemplo n.º 27
0
def demo():
    print 'demo for using lpsolve...'

    print 'using lpsolve to solve the problem..'
    lp = LP()
    ##Specify constaints
    ##(1)x+y<=3
    ##(2)y+z<=4
    lp.addConstraint([[1, 1, 0], [0, 1, 2]], "<=", [3, 4])
    # Force the first variable to be integer-valued
    ##lp.setInteger(0)

    ##all variables
    lp.setBinary([0, 1, 2])

    #set objective
    lp.setObjective([1, 1, 1], mode='minimize')

    ##return = lpsolve('set_binary', lp, column, must_be_bin)
    lp.solve()

    ##print out the solution
    print lp.getSolution()
Exemplo n.º 28
0
    def test02(self):
        lp = LP()

        self.assert_(lp.getIndexBlock(2, "a1") == (0,2))
        self.assert_(lp.getIndexBlock(4, "a2") == (2,6))
        self.assert_(lp.getIndexBlock("a1") == (0,2))
Exemplo n.º 29
0
    def test02_objfunc_rejects_negative_idx(self):
        lp = LP()

        self.assertRaises(ValueError,
                          lambda: lp.setObjective( (ar([0, -1, 2]), ar([1,1,1],dtype=float64) )))
Exemplo n.º 30
0
    def test03_bad_recall(self):
        lp = LP()

        self.assert_(lp.getIndexBlock(2, "a1") == (0,2))
        self.assert_(lp.getIndexBlock(4, "a2") == (2,6))
        self.assertRaises(ValueError, lambda: lp.getIndexBlock(3, "a1"))
Exemplo n.º 31
0
    def checkBindEach(self, opts):

        idxlist = [{}, {}]

        idxlist[0]["t"] = (0,3)
        idxlist[0]["N"] = "a"
        idxlist[0]["l"] = [0,1,2]
        idxlist[0]["a"] = ar([0,1,2])
        idxlist[0]["r"] = ar([0,0,1,1,2,2])[::2]
        idxlist[0]["f"] = ar([0,1,2],dtype=float64)

        idxlist[1]["t"] = (3,6)
        idxlist[1]["n"] = "b"
        idxlist[1]["l"] = [3,4,5]
        idxlist[1]["a"] = ar([3,4,5])
        idxlist[1]["r"] = ar([3,3,4,4,5,5])[::2]
        idxlist[1]["f"] = ar([3,4,5],dtype=float64)

        lp = LP()

        if opts[0] == "N":
            self.assert_(lp.getIndexBlock(idxlist[0]["N"], 3) == (0,3) )

        # Now bind the second group
        if opts[2] == "g":
            self.assert_(
                lp.bindEach(idxlist[1][opts[1]], ">", idxlist[0][opts[0]])
                == [0,1,2])

        elif opts[2] == "l":
            self.assert_(
                lp.bindEach(idxlist[0][opts[0]], "<", idxlist[1][opts[1]])
                == [0,1,2])

        elif opts[2] == "e":
            self.assert_(
                lp.bindEach(idxlist[0][opts[0]], "=", idxlist[1][opts[1]])
                == [0,1,2])
        elif opts[2] == "E":
            self.assert_(
                lp.bindEach(idxlist[1][opts[1]], "=", idxlist[0][opts[0]])
                == [0,1,2])
        else:
            assert False

        # Forces some to be defined implicitly above to catch that case
        lp.addConstraint( (idxlist[0][opts[0]], 1), ">=", 1)

        lp.setObjective( (idxlist[1][opts[1]], [1,2,3]) )
        lp.setMinimize()

        lp.solve()

        v = lp.getSolution()

        self.assert_(len(v) == 6, "len(v) = %d != 6" % len(v))
        self.assertAlmostEqual(v[0], 1)
        self.assertAlmostEqual(v[1], 0)
        self.assertAlmostEqual(v[2], 0)
        self.assertAlmostEqual(v[3], 1)
        self.assertAlmostEqual(v[4], 0)
        self.assertAlmostEqual(v[5], 0)

        if opts[0] in "nN" and opts[1] in "nN":

            d = lp.getSolutionDict()

            self.assert_(set(d.iterkeys()) == set(["a", "b"]))

            self.assertAlmostEqual(d["a"][0], 1)
            self.assertAlmostEqual(d["a"][1], 0)
            self.assertAlmostEqual(d["a"][2], 0)
            self.assertAlmostEqual(d["b"][0], 1)
            self.assertAlmostEqual(d["b"][1], 0)
            self.assertAlmostEqual(d["b"][2], 0)
Exemplo n.º 32
0
    def test02_reverse_order_mixed(self):
        lp = LP()

        self.assert_(lp.getIndexBlock("a1", 2) == (0, 2))
        self.assert_(lp.getIndexBlock(4, "a2") == (2, 6))
        self.assert_(lp.getIndexBlock("a1", 2) == (0, 2))
Exemplo n.º 33
0
    def test01_r(self):
        lp = LP()

        self.assert_(lp.getIndexBlock("a1", 2) == (0,2))
Exemplo n.º 34
0
    def checkBadSizingTooLarge(self, opts):
        
        lp = LP()

        def run_test(c_arg, o_arg):
            if opts[-1] == "c":
                self.assertRaises(ValueError, lambda: lp.addConstraint(c_arg, ">", 1))
            elif opts[-1] == "o":
                self.assertRaises(ValueError, lambda: lp.setObjective(o_arg))
            else:
                assert False

        indices = {}
        indices["t"] = (0,3)
        indices["N"] = "a"
        indices["l"] = [0,1,2]
        indices["a"] = ar([0,1,2])
        indices["f"] = ar([0,1,2],dtype=float64)

        weights = {}
        weights["l"] = [1,1,1,1]
        weights["a"] = ar([1,1,1,1])
        weights["f"] = ar([1,1,1,1])

        obj_func = {}
        obj_func["l"] = [1,2,3,4]
        obj_func["a"] = ar([1,2,3,4])
        obj_func["f"] = ar([1,2,3,4],dtype=float64)


        # Some ones used in the dict's case
        il = indices["l"] 
        assert len(il) == 3

        wl = weights["l"]
        assert len(wl) == 4

        ol = obj_func["l"]
        assert len(ol) == 4

        if opts[0] == "d" or opts[0] == "T":

            if opts[1] == "2":
                lp.getIndexBlock("b", 1)
                cd = [ ("a", wl[:2]), ("b", wl[2:])]
                od = [ ("a", ol[:2]), ("b", ol[2:])]
            
            elif opts[1] == "3":
                cd = [((0,2), wl[:2]), (2, wl[2:])]
                od = [((0,2), ol[:2]), (2, ol[2:])]

            elif opts[1] == "4":
                cd = [((0,2), wl[:2]), ( (2,3), wl[2:])]
                od = [((0,2), ol[:2]), ( (2,3), ol[2:])]

            elif opts[1] == "5":  # bad for out of order
                cd = [("a", wl[:2]), ( (2,3), wl[2:])]
                od = [("a", ol[:2]), ( (2,3), ol[2:])]
            
            elif opts[1] in indices.keys() and opts[2] in weights.keys():

                if "N" in opts:
                    lp.getIndexBlock(indices["N"], 3)

                cd = [(indices[opts[1]], weights[opts[2]])]
                od = [(indices[opts[1]], obj_func[opts[2]])]
            else:
                assert False

            if opts[0] == "d":
                run_test(dict(cd), dict(od))
                return
            elif opts[0] == "T":
                run_test(cd, od)
                return
            else:
                assert False
        else:
            assert len(opts) == 3
            
            # No little n option here
            if "N" in opts:
                lp.getIndexBlock(indices["N"], 3)
            
            run_test( (indices[opts[0]], weights[opts[1]]),
                      (indices[opts[0]], obj_func[opts[1]]))
            return
Exemplo n.º 35
0
    def test02_reverse_order_mixed(self):
        lp = LP()

        self.assert_(lp.getIndexBlock("a1", 2) == (0,2))
        self.assert_(lp.getIndexBlock(4, "a2") == (2,6))
        self.assert_(lp.getIndexBlock("a1", 2) == (0,2))
Exemplo n.º 36
0
    def checkBindSandwich(self, opts):

        idxlist = [{}, {}]

        idxlist[0]["t"] = (0, 3)
        idxlist[0]["N"] = "a"
        idxlist[0]["l"] = [0, 1, 2]
        idxlist[0]["a"] = ar([0, 1, 2])
        idxlist[0]["r"] = ar([0, 0, 1, 1, 2, 2])[::2]
        idxlist[0]["f"] = ar([0, 1, 2], dtype=float64)

        idxlist[1]["t"] = (3, 6)
        idxlist[1]["n"] = "b"
        idxlist[1]["l"] = [3, 4, 5]
        idxlist[1]["a"] = ar([3, 4, 5])
        idxlist[1]["r"] = ar([3, 3, 4, 4, 5, 5])[::2]
        idxlist[1]["f"] = ar([3, 4, 5], dtype=float64)

        lp = LP()

        if opts[0] == "N":
            self.assert_(lp.getIndexBlock(idxlist[0]["N"], 3) == (0, 3))

        # Now bind the second group

        lp.bindSandwich(idxlist[0][opts[0]], idxlist[1][opts[1]])

        if opts[2] == "u":
            lp.addConstraint((idxlist[0][opts[0]], 1), ">=", 1)
        elif opts[2] == "l":
            lp.addConstraint((idxlist[0][opts[0]], 1), "<=", -1)
            lp.setUnbounded(idxlist[0][opts[0]])
        else:
            assert False

        lp.setObjective((idxlist[1][opts[1]], [1, 2, 3]))
        lp.setMinimize()

        lp.solve()

        v = lp.getSolution()

        v0 = 1 if opts[2] == "u" else -1

        self.assert_(len(v) == 6, "len(v) = %d != 6" % len(v))
        self.assertAlmostEqual(v[0], v0)
        self.assertAlmostEqual(v[1], 0)
        self.assertAlmostEqual(v[2], 0)
        self.assertAlmostEqual(v[3], 1)
        self.assertAlmostEqual(v[4], 0)
        self.assertAlmostEqual(v[5], 0)

        if opts[0] in "nN" and opts[1] in "nN":

            d = lp.getSolutionDict()

            self.assert_(set(d.iterkeys()) == set(["a", "b"]))

            self.assertAlmostEqual(d["a"][0], v0)
            self.assertAlmostEqual(d["a"][1], 0)
            self.assertAlmostEqual(d["a"][2], 0)
            self.assertAlmostEqual(d["b"][0], 1)
            self.assertAlmostEqual(d["b"][1], 0)
            self.assertAlmostEqual(d["b"][2], 0)
Exemplo n.º 37
0
    def test04_bad_size_04(self):
        lp = LP()

        self.assertRaises(ValueError, lambda: lp.getIndexBlock("a1", "a2"))
Exemplo n.º 38
0
    def checkLBUBMix(self, opts, lb, ub):

        # these are indices to bound
        lbindices = (0,3)

        ubindices = {}
        ubindices["t"] = (3,6)
        ubindices["n"] = "a"
        ubindices["N"] = "a"
        ubindices["l"] = [3,4,5]
        ubindices["a"] = ar([3,4,5],dtype=uint)
        ubindices["f"] = ar([3,4,5],dtype=float64)

        ubvalues = {}
        ubvalues["s"] = ub
        ubvalues["l"] = [ub, ub, ub]
        ubvalues["a"] = ar([ub, ub, ub])

        lbvalues = {}
        lbvalues["s"] = lb
        lbvalues["l"] = [lb, lb, lb]
        lbvalues["a"] = ar([lb, lb, lb])

        lp = LP()

        lp.setLowerBound(lbindices, lbvalues[opts[1]])

        if opts[0] == "N":
            lp.getIndexBlock(ubindices["N"], 3)

        lp.setUpperBound(ubindices[opts[0]], ubvalues[opts[1]])

        lp.setObjective([1,1,1,-1,-1,-1])


        for num_times in range(2):  # make sure it's same anser second time
            lp.solve()

            self.assertAlmostEqual(lp.getObjectiveValue(), lb*3 - ub*3)

            v = lp.getSolution()

            self.assert_(len(v) == 6)
            self.assertAlmostEqual(v[0], lb)
            self.assertAlmostEqual(v[1], lb)
            self.assertAlmostEqual(v[2], lb)

            self.assertAlmostEqual(v[3], ub)
            self.assertAlmostEqual(v[4], ub)
            self.assertAlmostEqual(v[5], ub)
Exemplo n.º 39
0
    def test01(self):
        lp = LP()

        self.assert_(lp.getIndexBlock(2, "a1") == (0,2))
Exemplo n.º 40
0
    def checkLB(self, opts, lb):

        # these are indices to bound
        indices = {}
        indices["t"] = (0, 3)
        indices["N"] = "a"
        indices["l"] = [0, 1, 2]
        indices["a"] = ar([0, 1, 2], dtype=uint)
        indices["f"] = ar([0, 1, 2], dtype=float64)

        lbvalues = {}
        lbvalues["s"] = lb
        lbvalues["l"] = [lb, lb, lb]
        lbvalues["a"] = ar([lb, lb, lb])

        lp = LP()

        if opts[0] == "N":
            lp.getIndexBlock(indices["N"], 3)

        lp.setObjective([1, 1, 1, 1, 1, 1])

        lp.setLowerBound(indices[opts[0]], lbvalues[opts[1]])

        for num_times in range(2):  # make sure it's same anser second time
            lp.solve()

            self.assertAlmostEqual(lp.getObjectiveValue(), lb * 3)

            v = lp.getSolution()

            self.assert_(len(v) == 6)
            self.assertAlmostEqual(v[0], lb)
            self.assertAlmostEqual(v[1], lb)
            self.assertAlmostEqual(v[2], lb)

            self.assertAlmostEqual(v[3], 0)
            self.assertAlmostEqual(v[4], 0)
            self.assertAlmostEqual(v[5], 0)
Exemplo n.º 41
0
    def checkBindSandwich(self, opts):

        idxlist = [{}, {}]

        idxlist[0]["t"] = (0,3)
        idxlist[0]["N"] = "a"
        idxlist[0]["l"] = [0,1,2]
        idxlist[0]["a"] = ar([0,1,2])
        idxlist[0]["r"] = ar([0,0,1,1,2,2])[::2]
        idxlist[0]["f"] = ar([0,1,2],dtype=float64)

        idxlist[1]["t"] = (3,6)
        idxlist[1]["n"] = "b"
        idxlist[1]["l"] = [3,4,5]
        idxlist[1]["a"] = ar([3,4,5])
        idxlist[1]["r"] = ar([3,3,4,4,5,5])[::2]
        idxlist[1]["f"] = ar([3,4,5],dtype=float64)

        lp = LP()

        if opts[0] == "N":
            self.assert_(lp.getIndexBlock(idxlist[0]["N"], 3) == (0,3) )

        # Now bind the second group

        lp.bindSandwich(idxlist[0][opts[0]], idxlist[1][opts[1]])

        if opts[2] == "u":
            lp.addConstraint( (idxlist[0][opts[0]], 1), ">=", 1)
        elif opts[2] == "l":
            lp.addConstraint( (idxlist[0][opts[0]], 1), "<=", -1)
            lp.setUnbounded(idxlist[0][opts[0]])
        else:
            assert False

        lp.setObjective( (idxlist[1][opts[1]], [1,2,3]) )
        lp.setMinimize()

        lp.solve()

        v = lp.getSolution()

        v0 = 1 if opts[2] == "u" else -1

        self.assert_(len(v) == 6, "len(v) = %d != 6" % len(v))
        self.assertAlmostEqual(v[0], v0)
        self.assertAlmostEqual(v[1], 0)
        self.assertAlmostEqual(v[2], 0)
        self.assertAlmostEqual(v[3], 1)
        self.assertAlmostEqual(v[4], 0)
        self.assertAlmostEqual(v[5], 0)

        if opts[0] in "nN" and opts[1] in "nN":

            d = lp.getSolutionDict()

            self.assert_(set(d.iterkeys()) == set(["a", "b"]))

            self.assertAlmostEqual(d["a"][0], v0)
            self.assertAlmostEqual(d["a"][1], 0)
            self.assertAlmostEqual(d["a"][2], 0)
            self.assertAlmostEqual(d["b"][0], 1)
            self.assertAlmostEqual(d["b"][1], 0)
            self.assertAlmostEqual(d["b"][2], 0)
Exemplo n.º 42
0
    def testBasicBasis(self):

        # this should work as it's in the examples

        lp = LP()

        lp.addConstraint((0, 1), "<", 3)
        lp.addConstraint((1, 1), "<", 3)

        lp.setMaximize()

        lp.setObjective([1, 1])

        lp.solve(guess=[3, 3])

        self.assert_(lp.getInfo("Iterations") == 0, lp.getInfo("Iterations"))
Exemplo n.º 43
0
    def testBasicBasis(self):
        
        # this should work as it's in the examples

        lp = LP()

        lp.addConstraint( (0, 1), "<", 3)
        lp.addConstraint( (1, 1), "<", 3)

        lp.setMaximize()

        lp.setObjective([1,1])

        lp.solve(guess = [3,3])

        self.assert_(lp.getInfo("Iterations") == 0, lp.getInfo("Iterations"))
Exemplo n.º 44
0
    def checkBindEach(self, opts):

        idxlist = [{}, {}]

        idxlist[0]["t"] = (0, 3)
        idxlist[0]["N"] = "a"
        idxlist[0]["l"] = [0, 1, 2]
        idxlist[0]["a"] = ar([0, 1, 2])
        idxlist[0]["r"] = ar([0, 0, 1, 1, 2, 2])[::2]
        idxlist[0]["f"] = ar([0, 1, 2], dtype=float64)

        idxlist[1]["t"] = (3, 6)
        idxlist[1]["n"] = "b"
        idxlist[1]["l"] = [3, 4, 5]
        idxlist[1]["a"] = ar([3, 4, 5])
        idxlist[1]["r"] = ar([3, 3, 4, 4, 5, 5])[::2]
        idxlist[1]["f"] = ar([3, 4, 5], dtype=float64)

        lp = LP()

        if opts[0] == "N":
            self.assert_(lp.getIndexBlock(idxlist[0]["N"], 3) == (0, 3))

        # Now bind the second group
        if opts[2] == "g":
            self.assert_(
                lp.bindEach(idxlist[1][opts[1]], ">", idxlist[0][opts[0]]) ==
                [0, 1, 2])

        elif opts[2] == "l":
            self.assert_(
                lp.bindEach(idxlist[0][opts[0]], "<", idxlist[1][opts[1]]) ==
                [0, 1, 2])

        elif opts[2] == "e":
            self.assert_(
                lp.bindEach(idxlist[0][opts[0]], "=", idxlist[1][opts[1]]) ==
                [0, 1, 2])
        elif opts[2] == "E":
            self.assert_(
                lp.bindEach(idxlist[1][opts[1]], "=", idxlist[0][opts[0]]) ==
                [0, 1, 2])
        else:
            assert False

        # Forces some to be defined implicitly above to catch that case
        lp.addConstraint((idxlist[0][opts[0]], 1), ">=", 1)

        lp.setObjective((idxlist[1][opts[1]], [1, 2, 3]))
        lp.setMinimize()

        lp.solve()

        v = lp.getSolution()

        self.assert_(len(v) == 6, "len(v) = %d != 6" % len(v))
        self.assertAlmostEqual(v[0], 1)
        self.assertAlmostEqual(v[1], 0)
        self.assertAlmostEqual(v[2], 0)
        self.assertAlmostEqual(v[3], 1)
        self.assertAlmostEqual(v[4], 0)
        self.assertAlmostEqual(v[5], 0)

        if opts[0] in "nN" and opts[1] in "nN":

            d = lp.getSolutionDict()

            self.assert_(set(d.iterkeys()) == set(["a", "b"]))

            self.assertAlmostEqual(d["a"][0], 1)
            self.assertAlmostEqual(d["a"][1], 0)
            self.assertAlmostEqual(d["a"][2], 0)
            self.assertAlmostEqual(d["b"][0], 1)
            self.assertAlmostEqual(d["b"][1], 0)
            self.assertAlmostEqual(d["b"][2], 0)