Created
January 7, 2016 06:19
-
-
Save dragstar328/883a7c384991016cfa48 to your computer and use it in GitHub Desktop.
PULP example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pulp as lp | |
from pulp import lpSum | |
from pulp import LpVariable | |
def mixture(): | |
prob = lp.LpProblem("example mixture", lp.LpMinimize) | |
# Parameters | |
elements = ["Lead", "Zinc", "Tin"] | |
alloy_no = range(1, 10) | |
alloy = {1:{"Lead": 0.2, "Zinc": 0.3, "Tin": 0.5}, | |
2:{"Lead": 0.5, "Zinc": 0.4, "Tin": 0.1}, | |
3:{"Lead": 0.3, "Zinc": 0.2, "Tin": 0.5}, | |
4:{"Lead": 0.3, "Zinc": 0.4, "Tin": 0.3}, | |
5:{"Lead": 0.3, "Zinc": 0.3, "Tin": 0.4}, | |
6:{"Lead": 0.6, "Zinc": 0.3, "Tin": 0.1}, | |
7:{"Lead": 0.4, "Zinc": 0.5, "Tin": 0.1}, | |
8:{"Lead": 0.1, "Zinc": 0.3, "Tin": 0.6}, | |
9:{"Lead": 0.1, "Zinc": 0.1, "Tin": 0.8}} | |
costs = {1: 7.3, | |
2: 6.9, | |
3: 7.3, | |
4: 7.5, | |
5: 7.6, | |
6: 6.0, | |
7: 5.8, | |
8: 4.3, | |
9: 4.1} | |
target = {"Lead": 0.3, | |
"Zinc": 0.3, | |
"Tin" : 0.4} | |
# Variable | |
alloy_vars = LpVariable.dicts("Alloy", alloy_no, 0) | |
# Objective | |
prob += lpSum([costs[i]*alloy_vars[i] for i in alloy_no]) | |
# Constraints | |
for i in alloy_no: | |
prob += lpSum([alloy[i][j] for j in elements]) == 1 | |
for j in elements: | |
prob += lpSum([alloy[i][j] * alloy_vars[i] for i in alloy_no]) == target[j] | |
print prob | |
stat = prob.solve() | |
print lp.LpStatus[stat] | |
if lp.LpStatus[stat] == "Optimal": | |
for v in prob.variables(): | |
print v.name, "=", v.varValue | |
print "Cost = ", lp.value(prob.objective) | |
def transport(): | |
prob = lp.LpProblem("example transport", lp.LpMinimize) | |
# Parameters | |
fact = [1, 2] | |
dest = ["a", "b", "c"] | |
upper = {1: 250, 2:450} | |
demands = {"a":200, "b":200, "c":200} | |
cost = {1:{"a":3.4, "b":2.2, "c":2.9}, | |
2:{"a":3.4, "b":2.4, "c":2.5}} | |
# Variable | |
trans_var = lp.LpVariable.dicts("dest", (fact, dest), 0) | |
# Objective | |
Routes = [(i, j) for i in fact for j in dest] | |
prob += lpSum([cost[i][j] * trans_var[i][j] for (i, j) in Routes]) | |
# Constraints | |
for i in fact: | |
prob += lpSum([trans_var[i][j] for j in dest]) <= upper[i] | |
for j in dest: | |
prob += lpSum([trans_var[i][j] for i in fact]) == demands[j] | |
# Result | |
print prob | |
stat = prob.solve() | |
print lp.LpStatus[stat] | |
if lp.LpStatus[stat] == "Optimal": | |
for v in prob.variables(): | |
print v.name, "=", v.varValue | |
print "Cost = ", lp.value(prob.objective) | |
if '__main__' == __name__: | |
mixture() | |
transport() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment