python - 纸浆优化错误 - LPVariable 对象不支持索引
问题描述
尝试添加位于第 31 行的约束时,我一直遇到错误,模型 += ([MAHL[i][j] for (i,j) in yearlyhours]) <= 40
我不确定如何正确设置此约束。我想说的是,在 i 和 j 的每个索引处,特定值需要小于 40,并对所有 i、j 对执行此操作。
我对 PULP 非常陌生,并试图启动并运行一个基本模型。输入数据只是一堆 365 行长和 24 列宽的随机值。
from pulp import *
import pandas as pd
import numpy as np
import xlrd
model = pulp.LpProblem("Basic Model", pulp.LpMaximize)
YPER = 365
HE = 24
yearlyhours = [(i,j) for i in range(YPER) for j in range(HE)]
xlsx = pd.ExcelFile('IvA.xlsx')
df1 = pd.read_excel(xlsx, 'Sheet5')
df2 = pd.read_excel(xlsx, 'Sheet3')
df3 = pd.read_excel(xlsx, 'Sheet2')
MAHL = pulp.LpVariable('MAHL', (YPER, HE), cat='Integer')
MALL = pulp.LpVariable('MALL', cat='Integer')
DAHL = pulp.LpVariable('DAHL', cat='Integer')
DALL = pulp.LpVariable('DALL', cat='Integer')
book = xlrd.open_workbook('IvA.xlsx')
sheet10 = book.sheet_by_name('Sheet10')
sheet11 = book.sheet_by_name('Sheet11')
DAPRICE = [[sheet10.cell_value(r, c) for c in range(sheet10.ncols)] for r in range(sheet10.nrows)]
LOAD = [[sheet11.cell_value(r, c) for c in range(sheet11.ncols)] for r in range(sheet11.nrows)]
#model += (MAHL[i][j] for i in range(YPER) for j in range(HE)) <= 40
model += ([MAHL[i][j] for (i,j) in yearlyhours]) <= 40
model += (pulp.lpSum([DAPRICE[i][j] * LOAD[i][j] for i in range(YPER) for j in range(HE)]))
model.solve()
pulp.LpStatus[model.status]
print("Status:", LpStatus[model.status])
obj = value(model.objective)
print(obj)
我尝试了一些解决方案,另外一个被注释掉了。
Traceback (most recent call last):
File "bs.py", line 31, in <module>
model += ([MAHL[i][j] for (i,j) in yearlyhours]) <= 40
File "bs.py", line 31, in <listcomp>
model += ([MAHL[i][j] for (i,j) in yearlyhours]) <= 40
TypeError: 'LpVariable' object does not support indexing
解决方案
您已定义MAHL
为 a pulp.LpVariable
,它(如错误状态)不支持索引,因为它对 LP 变量进行建模。
您可能希望使用pulp.LpVariable.dicts
.
例子:
MAHL = pulp.LpVariable.dicts('MAHL', yearlyhours, cat=pulp.LpInteger)
并将其称为
model += pulp.lpSum([MAHL[(i,j)] for (i,j) in yearlyhours]) <= 40
推荐阅读
- amazon-web-services - 如何将 IP (AWS Lightsail) 重定向到其他托管服务器 (IONOS) 中的现有子域
- python - 命令“python setup.py egg_info”在 /tmp/pip-build-dlih6aks/MarkupSafe/ 中失败,错误代码为 1
- github - 如何使用 github 对 Sourcetree 进行身份验证?
- katalon-recorder - Katalon 记录器 PHPUnit 格式化程序
- git - 为什么我收到那个错误?致命:在上游源中找不到远程分支 redux-basics
- asp.net - 带有 # 特殊字符的输入参数的 ASP .Net“获取”Web API 控制器 URL 不起作用
- ruby-on-rails - 如何在 rails minitest 中为系统测试添加 -f 标志?
- java - 在 Android 应用的片段中未检测到手势
- php - 同时数据库插入请求期间的主键错误
- django - 我在 django 中有一个模型表单,每当我提交表单时,我都会收到自定义成功消息和默认消息如何抑制默认值