输入矩阵解决多供给地与多需求地的资源分配的线性最优化问题,
输入:
供给地的数目及其资源量,需求地的数目及其需求量,供给地的地理位置,需求地的地理位置
(编写函数计算供给地和需求地的距离,按两点间距离公式计算)
输出:
使得各个供给地和需求地之间的距离与资源运载量之积的和最小
约束:
需求地资源量等于各个供给地运载的到需求地的和,供给地对各个需求地的运载量之和小于等于其资源总量
import numpy as np
from scipy.optimize import linprog
def distance(point1, point2):
# 计算两点之间的距离,这里可以根据实际情况选择合适的距离计算方法
return np.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def resource_allocation_optimization(ci, dj, supply_locations, demand_locations):
n = len(ci) # 供给地数目
m = len(dj) # 需求地数目
# 构建目标函数系数向量 c
c = np.zeros(n * m)
for i, supply_loc in enumerate(supply_locations):
for j, demand_loc in enumerate(demand_locations):
c[i*m + j] = distance(supply_loc, demand_loc)
# 构建等式约束矩阵 A_eq 和右侧常数向量 b_eq
A_eq = np.zeros((m, n*m))
b_eq = dj
for i in range(m):
A_eq[i, i::m] = 1
# 构建不等式约束矩阵 A_ub 和右侧常数向量 b_ub
A_ub = np.zeros((n, n*m))
b_ub = ci
for i in range(n):
A_ub[i, i*m:(i+1)*m] = 1
# 定义变量的上下界
bounds = [(0, None) for _ in range(n*m)]
# 使用线性规划求解问题
result = linprog(c, A_eq=A_eq, b_eq=b_eq, A_ub=A_ub, b_ub=b_ub, bounds=bounds)
# 输出结果
xij = result.x.reshape(n, m)
total_cost = result.fun
return xij, total_cost
# 示例输入数据
ci = np.array([20,20]) # 供给地的资源量
dj = np.array([3,5,4,7,6,11]) # 需求地的资源需求量
supply_locations = [(5,1), (2,7)] # 供给地的地理位置
demand_locations = [(1.25,1.25),(8.75,0.75),(0.5,4.75),(5.75,5),(3,6.5),(7.25,7.25)] # 需求地的地理位置
# 求解资源分配问题
xij, total_cost = resource_allocation_optimization(ci, dj, supply_locations, demand_locations)
print("资源分配方案:")
print(xij)
print("最小距离与资源运载量之积:", total_cost)
资源分配方案:
[[ 3. 5. 0. 7. 0. 1.]
[ 0. 0. 4. 0. 6. 10.]]
最小距离与资源运载量之积: 135.28154179067644
更改供给地位置,对资源分配进行进一步优化
import numpy as np
from scipy.optimize import minimize
def nsd(x):
a = np.array([1.25, 8.75, 0.5, 5.75, 3, 7.25])
b = np.array([1.25, 0.75, 4.75, 5, 6.5, 7.75])
#s = np.zeros(12)
f1 = sum([np.sqrt((x[12] - a[i])**2 + (x[13] - b[i])**2) * x[i] for i in range(6)])
f2 = sum([np.sqrt((x[14] - a[i])**2 + (x[15] - b[i])**2) * x[i+6] for i in range(6)])
return f1 + f2
x0 = np.array([3, 5, 0, 7, 0, 1, 0, 0, 4, 0, 6, 10, 5, 1, 2, 7])
bounds = [(0, None)]*12 + [(None, None)]*4
A = np.array([[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]])
B = np.array([20, 20])
Aeq = np.zeros((6, 16))
for i in range(6):
Aeq[i, i] = 1
Aeq[i, i+6] = 1
beq = np.array([3, 5, 4, 7, 6, 11])
constraints = [{'type': 'eq', 'fun': lambda x, i=i : Aeq[i] @ x - beq[i]} for i in range(Aeq.shape[0])]
constraints += [{'type': 'ineq', 'fun': lambda x, i=i : B[i] - A[i] @ x} for i in range(A.shape[0])]
res = minimize(nsd, x0, bounds=bounds, constraints=constraints)
print('最优解:', res.x)
print('最小成本:', res.fun)
最优解: [3.00000000e+00 5.00000000e+00 4.00000000e+00 7.00000000e+00
1.00000000e+00 3.33429701e-15 8.63389187e-16 5.83928713e-16
1.22840006e-14 8.27021532e-16 5.00000000e+00 1.10000000e+01
5.69415991e+00 4.92569771e+00 7.24999995e+00 7.74999997e+00]
最小成本: 89.88348555736768