Example #1
0
def problem0():
    print "\n>>problem 0:\n"    
    problem = glpk("models/samp1.mps")
    problem.solve()
    
    print problem.solution()
    problem = glpk("models/plan.lp")
    problem.solve()
    print problem.solution()
Example #2
0
def problem2():
    print "\n>>problem 2:\n"
    problem = glpk("models/multi.mod","models/multi.dat")
    problem.update()
    problem.solve()
    print problem.supply['GARY','bands']
    print "solution:", problem.solution()
Example #3
0
def problem3():
    print "\n>>problem 3:\n"
    problem = glpk("models/steel.mod","models/steel.dat")
    problem.update()
    problem.solve()
    print "solution:", problem.solution()
    print "problem.total_profit =", problem.total_profit
    print "problem.Make =", problem.Make
Example #4
0
        def glpk_solve(cst_set, names, params):
            size = 1000+1
            ia = intArray(size)
            ja = intArray(size)
            ar = doubleArray(size)
            prob = glp_create_prob()

            glp_set_prob_name(prob, "problem")
            glp_set_obj_dir(prob, GLP_MIN)

            glp_add_rows(prob, len(cst_set.get_constraints()))
            for i in range(len(cst_set.get_constraints())):
                print cst_set.get_constraints()[i]
                glp_set_row_name(prob, i+1, "s"+str(i+1))
                if cst_set.get_constraints()[i].is_equality():
                    glp_set_row_bnds(prob, i+1, GLP_FX, -cst_set.get_constraints()[i].get_constant_val().get_num_si(), 0.0)
                else:
                    glp_set_row_bnds(prob, i+1, GLP_LO, -cst_set.get_constraints()[i].get_constant_val().get_num_si(), 0.0)

            ndims = len(cst_set.get_space().get_var_ids(isl._isl.dim_type.set))
            glp_add_cols(prob, ndims)
            for i in range(ndims):
                glp_set_col_name(prob, i+1, cst_set.get_space().get_var_ids(isl._isl.dim_type.set)[i])
                glp_set_col_kind(prob, i+1, GLP_IV)
                glp_set_col_bnds(prob, i+1, GLP_FR, 0.0, 0.0)

            glp_set_obj_coef(prob, 1, 100.0)
            glp_set_obj_coef(prob, 2, 10.0)
            glp_set_obj_coef(prob, 3, .1)

            count = 1
            for i in range(len(cst_set.get_constraints())):
                for j in range(ndims):
                    value = cst_set.get_constraints()[i].get_coefficient_val(isl._isl.dim_type.set, j).get_num_si()
                    if value != 0:
                        ia[count] = i+1
                        ja[count] = j+1
                        ar[count] = value
                        count = count+1

            glp_load_matrix(prob, count-1, ia, ja, ar)
            glp_write_lp(prob, None, "./lp.lp")
            problem = glpk("./lp.lp")
            problem.solve()
            solution = problem.solution()

            coeff_values, max_diff_values = [], []
            for i in range(ndims):
                name = cst_set.get_space().get_var_ids(isl._isl.dim_type.set)[i]
                print name + " = " + str(solution[name])
                if i > 0 and i <= len(params) + 1:
                    max_diff_values.append(solution[name])
                if i >= (ndims - len(names)):
                    coeff_values.append(solution[name])
            del prob
            return coeff_values, max_diff_values 
Example #5
0
def problem1():
    print "\n>>problem 1:\n"
    problem = glpk("models/net3.mod","models/net3.dat")
    problem.solve()
    sol1 = problem.solution()
    
    problem.pd_cap['NE'] = 10000
    problem.dw_cap['NE', 'BOS'] = 50
    problem.p_supply = 450
    problem.update()
    problem.solve()
    sol2 = problem.solution()
    
    print "solution1:", sol1
    print "solution2:", sol2
Example #6
0
def problem4():
    print "\n>>problem 4:\n"
    problem = glpk("models/steel.mod")
    problem.PROD = ['bands', 'coils']
    problem.rate['bands'] = 200
    problem.rate['coils'] = 140
    problem.profit['bands'] = 25
    problem.profit['coils'] = 30
    problem.market['bands'] = 6000
    problem.market['coils'] = 4000
    problem.avail = 40
    problem.update()
    problem.solve()
    print "problem.solution() =", problem.solution()
    print "problem.sets() =", problem.sets()
    print "problem.parameters() =", problem.parameters()
    print "problem.variables() =", problem.variables()
    print "problem.constraints() =", problem.constraints()
    print "problem.objectives() =", problem.objectives()
    print "problem.Make =", problem.Make
    print "problem.Make['bands'] =", problem.Make['bands']
    print "problem.Make['bands'].value() =", problem.Make['bands'].value()    
    print "problem.total_profit =", problem.total_profit
    print "problem.total_profit.value() =", problem.total_profit.value()
    problem.Make >= 10
    problem.Make['coils'] <= 100
    0 <= problem.total_profit <= 100000

    problem.Make <= 15
    problem.Make['bands'] <= 10
    print problem.Make['bands']._bounds()
    #problem.Time <= 10
    
    
    print "problem.total_profit =", problem.total_profit    
    problem.solve()
    #print "problem.Make.bounds() =", problem.Make._bounds()
    #print "problem.Make['coils'].bounds() =", problem.Make['coils']._bounds()
    #print "problem.Make['bands'].bounds() =", problem.Make['bands']._bounds()       
    print "problem.solution() =", problem.solution()
Example #7
0
def schedule(managers, resources, alloc_req, constrains, res_constrains):
    try:

        group_counter = 1000

        # filter resources to only machines and links (which conform to uniform
        # semantics)
        _resources = copy.deepcopy(resources)
        for irm in resources:
            for res in resources[irm]:
                if resources[irm][res]["Type"] != "Machine" and resources[irm][
                        res]["Type"] != "Link" and resources[irm][res][
                            "Type"].split("-")[0] != "Web":
                    del _resources[irm][res]
        resources = _resources
        # managers: list of managers (not used)
        # print "managers: " + `managers`
        # resources: list of resources of each Manager
        #print "resources: " + `resources`
        # res_constrains: constrains relating several resources
        # alloc_req: an allocation request
        #print "alloc_req: " + `alloc_req`
        # constrains: distance constrains
        #print "constraints: " + `constrains`

        reservation = alloc_req

        resources, enc_dict = encode_resource_names(resources)
        res_constrains = encode_resource_constraints(res_constrains)
        #print "res_constrains': " + `res_constrains`

        # Translate resources to generate the optimization problem
        resources_aux = []
        # used to find the internal id of a resource (integer) using the id
        # given by the IRM
        resources_table = {}
        idx = 0
        for irm in resources:
            for R in resources[irm]:
                # The resource is not a compound resource
                if not "Source" in resources[irm][R]["Attributes"]:
                    newR = Resource(idx)
                    resources_table[R] = idx
                    newR.irm = irm
                    newR.key = R
                    newR.type = resources[irm][R]["Type"]
                    newR.attributes = {}
                    for a in resources[irm][R]["Attributes"]:
                        newR.attributes[a] = resources[irm][R]["Attributes"][a]
                    resources_aux.append(newR)
                    idx = idx + 1

        # Translate compound resources to generate the optimization problem
        # This implementation assumes only 1 type of compound resources, i.e.
        # Network Links
        compound_resources = [[None] * len(resources_aux)
                              for _ in range(len(resources_aux))]
        compound_resources_table = {}

        #print "resources ::::::::::::>", json.dumps(resources, indent=4)
        #print "resources_table ::::::>", json.dumps(resources_table, indent=4)
        for irm in resources:
            for R in resources[irm]:
                # The resource is a compound resource
                if "Source" in resources[irm][R]["Attributes"]:
                    source = resources_table[resources[irm][R]["Attributes"]
                                             ["Source"]]
                    target = resources_table[resources[irm][R]["Attributes"]
                                             ["Target"]]
                    if target < source:
                        aux = source
                        source = target
                        target = aux
                    compound_resources[source][target] = Resource(idx)
                    compound_resources[source][target].key = R
                    compound_resources[source][target].irm = irm
                    compound_resources[source][target].source = resources[irm][
                        R]["Attributes"]["Source"]
                    compound_resources[source][target].target = resources[irm][
                        R]["Attributes"]["Target"]
                    compound_resources_table[R] = compound_resources[source][
                        target]  # save resource in table to get fast access by key
                    idx = idx + 1
                    for a in resources[irm][R]["Attributes"]:
                        compound_resources[source][target].attributes[
                            a] = resources[irm][R]["Attributes"][a]

        # Translate resource constrains to generate the optimization problem
        res_constrains_aux = []
        idx = 0
        for irm in res_constrains:
            for c in res_constrains[irm]:
                constraint = res_constrains[irm][c]["Constraint"]
                attribute = res_constrains[irm][c]["Attribute"]
                #operation = res_constrains[irm][c]["Operation"]
                #threshold = res_constrains[irm][c]["Threshold"]

                # if attribute not in res_constrains_aux:
                #res_constrains_aux[attribute] = [ ]

                newC = Constraint(idx)
                newC.key = c
                newC.operation = " <= "
                split_cons = constraint.split("<=")
                newC.threshold = split_cons[1]
                newC.addends = map(lambda x: x.strip(),
                                   split_cons[0].split("+"))
                newC.attribute = attribute
                res_constrains_aux.append(newC)
                idx = idx + 1

        # Translate allocation request to generate the optimization problem
        reservation_aux = []
        # used to find the internal id of a resource (integer) using the id
        # given by the IRM"
        inverse_resources = {}
        groups = {}
        idx = 0
        for r in alloc_req:
            if "Source" not in r["Attributes"]:
                newr = Resource(idx)
                newr.id = idx
                newr.key = "r" + ` idx `
                if "ID" in r:
                    newr.id_constraint = r["ID"].replace("-", "")
                if "Group" not in r:
                    r["Group"] = "GRP" + str(group_counter)
                    group_counter = group_counter + 1

                newr.group = r["Group"]
                if newr.group not in groups:
                    groups[newr.group] = []
                groups[newr.group].append(idx)
                inverse_resources[newr.key] = idx
                newr.type = r["Type"]
                newr.attributes = {}
                for a in r["Attributes"]:
                    newr.attributes[a] = r["Attributes"][a]
                reservation_aux.append(newr)
                idx = idx + 1

        # Translate compound allocation request to generate the optimization
        # problem
        compound_reservation = [[None] * len(reservation_aux)
                                for _ in range(len(reservation_aux))]
        compound_attributes = set()
        for r in alloc_req:
            if "Source" in r[
                    "Attributes"]:  # The resource is a compound resource
                source = r["Attributes"]["Source"]
                target = r["Attributes"]["Target"]
                #operation = d["ConstraintType"]
                for i in groups[source]:
                    for ip in groups[target]:
                        if i < ip:
                            compound_reservation[i][ip] = {}
                        if ip < i:
                            compound_reservation[ip][i] = {}
                        for a in r["Attributes"]:
                            if a != "Source" and a != "Target":
                                if a not in compound_attributes:
                                    compound_attributes = compound_attributes | {
                                        a
                                    }
                                if i < ip:
                                    compound_reservation[i][ip][a] = {}
                                    compound_reservation[i][ip][a][
                                        "Key"] = "r" + str(idx)
                                    compound_reservation[i][ip][a][
                                        "Value"] = r["Attributes"][a]
                                if ip < i:
                                    compound_reservation[ip][i][a] = {}
                                    compound_reservation[ip][i][a][
                                        "Key"] = "r" + str(idx)
                                    compound_reservation[ip][i][a][
                                        "Value"] = r["Attributes"][a]
                                idx = idx + 1

        # Translate distance constrains request to generate the optimization
        # problem
        distances_aux = [[None] * len(reservation_aux)
                         for _ in range(len(reservation_aux))]
        distance_attributes = set()
        #print "distance_aux before: ", json.dumps(distances_aux, indent=4)
        for d in constrains:
            source = d["Source"]
            target = d["Target"]
            #operation = d["ConstraintType"]
            for i in groups[source]:
                for ip in groups[target]:
                    if i < ip:
                        distances_aux[i][ip] = {}
                    if ip < i:
                        distances_aux[ip][i] = {}
                    for a in d:
                        if a != "Source" and a != "Target" and a != "ConstraintType":
                            if a not in distance_attributes:
                                distance_attributes = distance_attributes | {a}
                            if i < ip:
                                distances_aux[i][ip][a] = d[a]
                            if ip < i:
                                distances_aux[ip][i][a] = d[a]

        #print "distance_aux after: ", json.dumps(distances_aux, indent=4)
        result = []

        # Generates linear optimization problem

        generate_lp("crs.lp", resources_aux, compound_resources,
                    res_constrains_aux, reservation_aux, compound_reservation,
                    distances_aux, compound_attributes, distance_attributes)

        # Creates GLPK object, solves the problem and gets the solution
        lp = glpk("crs.lp")
        value = lp.solve()
        solution = lp.solution()
        #print "solution=", json.dumps(solution, indent=4)

        # Checks if GLPK found a solution
        if glp_get_status(lp._lp) != 5:
            raise Exception("cannot find a schedule!")
        else:
            # Generates result
            result = generate_reservations(solution, resources_aux,
                                           reservation, resources_table,
                                           compound_resources_table)
            if result == []:
                raise Exception("cannot find a schedule!")
            decode_resource_names(result, enc_dict)
        return result
    except Exception, e:
        print "Exception in schedule: %s" % e
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
        raise
Example #8
0
from glpk import *

# create an LP as an instance of class "glpk",
# based on the model "diet.mod" (coming in glpk's "examples")
problem = glpk("models/diet.mod")

# solve
problem.solve()
print "\n\nsolution:", problem.solution()

# define/modify problem data:
# "F" and "a" are, respectively, a "set" and a "param" in "diet.mod";
# now, they can be accessed in Python as members of the "glpk" instance
problem.F += ['Bacalhau']  # add a new food
problem.a['Bacalhau', 'Calorie'] = 87.3  # nutrients
problem.a['Bacalhau', 'Protein'] = 98.7
problem.a['Bacalhau', 'Calcium'] = 17.3
problem.a['Bacalhau', 'Iron'] = 12.3
problem.a['Bacalhau', 'Vitamin-A'] = 12.3

# update and solve
problem.update()
problem.solve()
print "\n\nsolution:", problem.solution()

# one more update
problem.F.remove('Bacalhau')  # remove food
for key in problem.a.keys():
    if 'Bacalhau' in key:
        del problem.a[key]
Example #9
0
from glpk import *

# create an LP as an instance of class "glpk",
# based on the model "diet.mod" (coming in glpk's "examples")
problem = glpk("models/diet.mod")

# solve
problem.solve()
print "\n\nsolution:", problem.solution()

# define/modify problem data:
# "F" and "a" are, respectively, a "set" and a "param" in "diet.mod";
# now, they can be accessed in Python as members of the "glpk" instance
problem.F += ['Bacalhau']	# add a new food
problem.a['Bacalhau','Calorie']    = 87.3	# nutrients
problem.a['Bacalhau','Protein']	   = 98.7
problem.a['Bacalhau','Calcium']	   = 17.3
problem.a['Bacalhau','Iron']	   = 12.3
problem.a['Bacalhau','Vitamin-A']  = 12.3	

# update and solve
problem.update()
problem.solve()
print "\n\nsolution:", problem.solution()

# one more update
problem.F.remove('Bacalhau')	# remove food
for key in problem.a.keys():
    if 'Bacalhau' in key:
        del problem.a[key]