自己看了一下利用pulp库和numpy库来解决运输问题,写了点解析
这个是问题:
import pulp
def Transportation_problem(cost, x_max, y_max):
y_len = len(cost) #求解x,y轴的长度
x_len = len(cost[0])
#建立问题
my_problem = pulp.LpProblem("Transportation_problem", sense=pulp.LpMaximize)
#这个是用于创建变量Xi,j,cat传参表示取整数
var = [[pulp.LpVariable(f"x{y}{x}", lowBound=0, upBound=None, cat=pulp.LpInteger) for x in range(x_len)] for y in range(y_len)]
#这个函数的作用相当于将一个多维数组扁平化,变成一维数组,这里如果使用的是numpy中的ndarray对象可以直接调用flatten方法(使用下面两条语句也可以达到同样的效果)
#ndvar = np.array(var)
#my_problem += pulp.lpDot(ndvar.flatten(), cost.flatten())
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
my_problem += pulp.lpDot(flatten(var), cost.flatten()) #将两个一维数组相乘,得出最值函数的表达式(价格函数),加入到问题中
#每一行相加应该小于这一行的总和的最大值
for y in range(y_len): #每一行上的约束条件
my_problem += pulp.lpSum(var[y]) <= x_max[y]
#每一列相加小于这一列的最大值
for x in range(x_len): #每一列上的约束条件
my_problem += pulp.lpSum([var[y][x] for y in range(y_len)]) <= y_max[x]
my_problem.solve()
#返回最优解和取得最优解时的分配
return {"objective": pulp.value(my_problem.objective), "var": [[pulp.value(var[y][x]) for y in range(y_len)] for x in range(x_len)]}
cost = np.array(
[
[500, 550, 630, 1000, 800, 700],
[800, 700, 600, 950, 900, 930],
[1000, 960, 840, 650, 600, 700],
[1200, 1040, 980, 860, 880, 780],
]
)
x_max = np.array([76, 88, 96, 40])
y_max = np.array([42, 56, 44, 39, 60, 59])
result = Transportation_problem(cost, x_max, y_max)
print(result)