我正在学习使用CVXPY解决优化问题,因此我从以下简单的设施位置分配问题开始。
CVXPY中的代码为:
Fi = np.array([1,1,1]) # Fixed cost of each facility
Ci = np.array([15, 10, 10]) # Capacity of each facility
Dj = np.array([5, 5, 5, 3, 3, 4]) # Demand of each facility
Cij = np.ones(m,n)
n = len(Dj)
m = len(Fi)
# Decision Variables
Xij = cvx.Bool(m,n) # (m,n) vector
Yi = cvx.Bool(m) # column vector of length (m,1)
# Objective
fixed_cost = cvx.sum_entries(Fi*Yi)
var_cost = cvx.sum_entries(Cij.T * Dj *Xij)
total_cost = fixed_cost + var_cost
objective = cvx.Minimize(total_cost)
# Maximum facility locations to be selected?
constraints.append(cvx.sum_entries(Yi)==2)
# Sum of demands allocated to a facility shall be <= facility capacity -
# Capacity Fixed Cost
constraints.append(cvx.sum_entries(Dj * Xij.T, axis=0) <= Ci*Yi)
# Every demand point shall be supplied by only one facility.
constraints.append(cvx.sum_entries(Xij, axis=1) == 1)
# Solve the problem
prob = cvx.Problem(objective, constraints)
prob.solve(solver=cvx.GLPK_MI)
# Print the values
#print("status:", prob.status)
print("optimal value", prob.value)
print("Selected Facility Locations", Yi.value)
print("Assigned Nodes", Xij.value, )
根据最后一个约束,需求位置只能由一个设施提供,但是 Xij.value 的输出显示错误的结果。
Using CVXPY version: 0.4.10
status: optimal
optimal value 91.0
Selected Facility Locations [[1.]
[0.]
[1.]]
Assigned Nodes to Facility 1) [[1. 0. 0. 0. 0. 0.]]
Assigned Nodes to Facility 2) [[1. 0. 0. 0. 0. 0.]]
Assigned Nodes to Facility 3) [[1. 0. 0. 0. 0. 0.]]
Xij.value应该是这样的:
Using CVXPY version: 0.4.10
status: optimal
optimal value 91.0
Selected Facility Locations [[1.]
[1.]
[0.]]
Assigned Nodes to Facility 1) [[1. 1. 1. 0. 0. 0.]]
Assigned Nodes to Facility 2) [[0. 0. 0. 1. 1. 1.]]
Assigned Nodes to Facility 3) [[0. 0. 0. 0. 0. 0.]]
表示选择了设施1和2。 前三个点分配给设施1,接下来的三个点分配给设施2。