我想使用带有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 是可变的。
答案 0 :(得分:1)
我要假设两件事;
P.shape[0] = d = 2
和C.shape[0] = 2
。 / li>
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]