forked from vietnq68/mrp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mrp.py
101 lines (75 loc) · 2.55 KB
/
mrp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from pulp import *
import data
import data2
import data3
bom = data2.data['bom']
materials = data2.data['materials']
# needed number of each part for the level that part appears
# for example ['A_1','A_2','B_1',...] is number of A in level 1,2 and number of B in level 1
lp_vars = []
# variables for Simplex problem
A_eq = []
B_eq = []
B_ineq = []
A_ineq = []
objective = []
def get_variables():
for part, num in materials.iteritems():
for level, bill in bom.iteritems():
if part in bill[0]:
lp_var = LpVariable(name=part + '_' + level,
lowBound=0,
upBound=num,
cat=LpInteger if isinstance(bill[1], int) else LpContinuous)
lp_vars.append(lp_var)
def get_objective():
# objective will be finding maximize of produced products, a number called K
for var in lp_vars:
objective.append(0)
objective.append(1) # coef for K
def get_inequality_constraints():
for part, num in materials.iteritems():
row = []
for var in lp_vars:
row.append(1 if part == var.name.split('_') else 0)
row.append(0) # coef for K
A_ineq.append(row)
B_ineq.append(num)
def get_equality_constraints():
for level, bill in bom.iteritems():
row = []
coef = bill[1]
options = bill[0]
for var in lp_vars:
if var.name.split('_')[0] in options and var.name.split('_')[1] == level:
row.append(1)
else:
row.append(0)
row.append(-coef) # coef for K
A_eq.append(row)
B_eq.append(0)
def main():
prob = LpProblem("Dong bo san pham", LpMaximize)
get_variables()
get_objective()
get_equality_constraints()
get_inequality_constraints()
lp_vars.append(LpVariable('K', 0, cat=LpInteger))
num_of_vars = len(lp_vars)
# objective
prob += lpSum([objective[i] * lp_vars[i] for i in xrange(num_of_vars)])
# equality constraints
for i in xrange(len(A_eq)):
prob += lpSum([A_eq[i][j] * lp_vars[j] for j in xrange(num_of_vars)]) == B_eq[i]
# inequality constraints
for i in xrange(len(A_ineq)):
prob += lpSum([A_ineq[i][j] * lp_vars[j] for j in xrange(num_of_vars)]) <= B_ineq[i]
prob.solve()
# Solution
materials_dict = {}
for v in prob.variables():
materials_dict[v.name] = v.varValue
print "objective=", value(prob.objective)
print materials_dict
if __name__ == '__main__':
main()