实验目的:
lingo实现运输问题、Matlab解决运输问题、Python调包实现
实验要求:
报告内容:
Lingo实现:
代码:
model:
sets:
supplys/1..3/: S;
demands/1..4/: D;
links(supplys, demands): c, x;
endsets
data:
S = 7,4,9;
D = 3,6,5,6;
c = 3 11 3 10
1 9 2 8
7 4 10 5;
enddata
min = @sum(links(i,j): c(i,j) * x(i,j));
@for(supplys(i): @sum(demands(j): x(i,j)) = S(i));
@for(demands(j): @sum(supplys(i): x(i,j)) = D(j));
end
Matlab:
代码:
c=[3,11,3,10,1,9,2,8,7,4,10,5];
Aeq=[1,1,1,1,0,0,0,0,0,0,0,0;
0,0,0,0,1,1,1,1,0,0,0,0;
0,0,0,0,0,0,0,0,1,1,1,1;
1,0,0,0,1,0,0,0,1,0,0,0;
0,1,0,0,0,1,0,0,0,1,0,0;
0,0,1,0,0,0,1,0,0,0,1,0;
0,0,0,1,0,0,0,1,0,0,0,1];
beq=[7;4;9;3;6;5;6];
lb=[0;0;0;0;0;0;0;0;0;0;0;0];
ub=[Inf;Inf;Inf;Inf;Inf;Inf;Inf;Inf;Inf;Inf;Inf;Inf];
[x,fval]=linprog(c,[],[],Aeq,beq,lb,ub)
Python实现:
代码:
import pulp
import numpy as np
from pprint import pprint
def transportation_problem(costs, x_max, y_max):
row = len(costs)
col = len(costs[0])
prob = pulp.LpProblem('Transportation Problem', sense=pulp.LpMaximize)
var = [[pulp.LpVariable(f'x{i}{j}', lowBound=0, cat=pulp.LpInteger) for j in range(col)] for i in range(row)]
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
prob += pulp.lpDot(flatten(var), costs.flatten())
for i in range(row):
prob += (pulp.lpSum(var[i]) <= x_max[i])
for j in range(col):
prob += (pulp.lpSum([var[i][j] for i in range(row)]) <= y_max[j])
prob.solve()
return {'objective':pulp.value(prob.objective), 'var': [[pulp.value(var[i][j]) for j in range(col)] for i in range(row)]}
if __name__ == "__main__":
costs = np.array([[3, 11, 3, 10],
[1, 9, 2, 8],
[7, 4, 10, 5]])
max_plant = [7,4,9]
max_cultivation = [3,6,5,6]
res = transportation_problem(costs, max_plant, max_cultivation)
print(f'最大值为{res["objective"]}')
print('各变量的取值为:')
pprint(res['var'])