使用带有 numpy 数组的 PuLP 解决 LP

Solving LP using PuLP with numpy array

我想在 PuLP 中使用 numpy 矩阵来设置约束。

我有一个 2x4x4 的 numpy 矩阵,我想使用这个矩阵作为约束,但我遇到的问题是如何使用它。实际上我在索引方面遇到了问题,因为我必须遍历所有变量并修复约束。 这些是矩阵。

P = np.array([[[0.7, 0.3,0,0],
               [0,0.7,0.3,0],
               [0,0,0.6,0.4],
               [0,0,0,1]],
              [[0.7,0.3,0,0],
               [0.7,0.3,0,0],
               [0.7,0.3,0,0],
               [0.7,0.3,0,0]]])
C = np.array([[100,80,50,10],[-100,-100,-100,-100]])
beta = 0.9

P矩阵是概率矩阵,第二个是成本矩阵。 每个 4x4 矩阵都描述了从一种状态到另一种状态的转移概率。 我的约束是

这里V是可变的

我要假设两件事;

  1. 在最后一个约束中,你指的是 right-hand 侧的 C[d][i],而不是 C[i][d]... 因为 P.shape[0] = d = 2,并且 C.shape[0] = 2.
  2. 您希望约束适用于所有 d 以及所有 i

假设以上,下面应该做你想做的:

from pulp import *
import numpy as np 

P = np.array([[[0.7, 0.3,0,0],
               [0,0.7,0.3,0],
               [0,0,0.6,0.4],
               [0,0,0,1]],
              [[0.7,0.3,0,0],
               [0.7,0.3,0,0],
               [0.7,0.3,0,0],
               [0.7,0.3,0,0]]])

C = np.array([[100,80,50,10],[-100,-100,-100,-100]])

beta = 0.9

set_D = range(0, P.shape[0])
set_I = range(0, P.shape[1])

# Generate proble, & Create variables
prob = LpProblem("numpy_constraints", LpMinimize)
V = pulp.LpVariable.dicts("V", set_I, cat='Continuous')

# Make up an objective, let's say sum of V_i
prob += lpSum([V[i] for i in set_I])

# Apply constraints
for d in set_D:
    for i in set_I:
        prob += V[i] - beta*lpSum([P[d][i][j]*V[j] for j in set_I]) >= C[d][i]

# Solve problem
prob.solve()

# Print results:
V_soln = np.array([V[i].varValue for i in set_I])
print (("Status:"), LpStatus[prob.status])
print("V_soln: ")
print(V_soln)

我得到以下信息。我没有检查你的约束是否满足,但它们应该是。

Status: Optimal
V_soln: 
[690.23142 575.50231 492.35502 490.23142]