我在使用Excel的输入数组和PULP中的变量数组来设置约束时遇到问题。
看来该模型仅适用于平方矩阵,而我的最终代码具有365x24的矩阵。下面的代码具有5x6的矩阵,并且在运行时说索引超出范围会引发错误。
我已经提供了到目前为止正在使用的代码。
Sheet11矩阵
91 37 36 38 33 16
1 36 59 29 23 4
25 74 72 39 69 1
22 68 48 70 12 41
98 86 75 16 99 12
Sheet12矩阵
59 63 66 57 4 15
26 33 75 71 21 2
37 88 89 1 90 3
91 48 27 24 23 14
68 13 61 37 77 20
from pulp import *
from pandas import *
import pandas as pd
import numpy as np
import xlrd
model = pulp.LpProblem("Basic Model", pulp.LpMinimize)
YPER = 5
HE = 6
yearlyhours = []
yearlyhours = [(i,j) for i in range(YPER) for j in range(HE)]
book = xlrd.open_workbook('Stack.xlsx')
sheet11 = book.sheet_by_name('Sheet11')
sheet12 = book.sheet_by_name('Sheet12')
sheet13 = book.sheet_by_name('Sheet13')
TEST = [[sheet11.cell_value(i,j) for i in range(YPER)] for j in range(HE)]
YAPR = [[sheet12.cell_value(i,j) for i in range(YPER)] for j in range(HE)]
MAPR = [[sheet13.cell_value(i,j) for i in range(YPER)] for j in range(HE)]
YAHL = pulp.LpVariable.dicts("YAHL", (range(YPER), range(HE)), lowBound=0, cat='Continuous')
MAHL = pulp.LpVariable.dicts("MAHL", (range(YPER), range(HE)), lowBound=0, cat='Continuous')
##OBJECTIVE##
model += pulp.lpSum([YAPR[i][j] * YAHL[i][j] + MAPR[i][j] * MAHL[i][j] for i in range(YPER) for j in range(HE)]), 'Sum_of_Value'
for i,j in yearlyhours:
model += pulp.lpSum([YAHL[i][j] + MAHL[i][j]]) == ([TEST[i][j]])
LpSolverDefault.msg = 1
model.writeLP('Opt.lp')
model.solve()
pulp.LpStatus[model.status]
print("Status:", LpStatus[model.status])
obj = value(model.objective)
print("Total Cost: ${}".format(obj,2))
print('\n')
当更改为非方矩阵时,会给出以下错误消息:
IndexError:列表索引超出范围
在我仍在学习的过程中,任何帮助都很感激。
答案 0 :(得分:0)
您要读取的代码产生6行5列。可变字典结构是5个键,然后内部字典具有6个键。因此,当您尝试同时迭代两个对象时,会出现索引错误。方阵起作用是因为5 x 5与5 x 5相同,所以倒序无关紧要。
>>>YAHL
{
0: {
0: YAHL_0_0,
1: YAHL_0_1,
2: YAHL_0_2,
3: YAHL_0_3,
4: YAHL_0_4,
5: YAHL_0_5
}, ... 4: {
0: YAHL_4_0,
1: YAHL_4_1,
2: YAHL_4_2,
3: YAHL_4_3,
4: YAHL_4_4,
5: YAHL_4_5}}
}
}
>>>TEST
[[91.0, 1.0, 25.0, 22.0, 98.0],
[37.0, 36.0, 74.0, 68.0, 86.0],
[36.0, 59.0, 72.0, 48.0, 75.0],
[38.0, 29.0, 39.0, 70.0, 16.0],
[33.0, 23.0, 69.0, 12.0, 99.0],
[16.0, 4.0, 1.0, 41.0, 12.0]]
>>>for i in range(YPER):
for j in range(HE):
print(TEST[i][j])
print(YAHL[i][j])
91.0
YAHL_0_0
1.0
YAHL_0_1
25.0
YAHL_0_2
22.0
YAHL_0_3
98.0
YAHL_0_4
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-14-a9538e188b1e> in <module>
1 for i in range(YPER):
2 for j in range(HE):
----> 3 print(TEST[i][j])
4 print(YAHL[i][j])
5
IndexError: list index out of range