【发布时间】:2018-04-11 09:25:46
【问题描述】:
我对 python 还是很陌生,或者更确切地说是一般的编码,并试图找到自己的方式。我花了几天几夜在网上搜索并阅读了我在这方面找到的所有提示和文档,但找不到解决我问题的方法。 我的目标实际上是一个非常基本的 LP,找到与每个索引通道的最小值和最大值绑定的最合适的交易量,并最大化每个通道不同的利润。我发现一些代码与我一直在寻找的代码非常接近,并根据我的需要进行了调整
prob = pulp.LpProblem('LaneSelectionOptimization', LpMaximize)
'''Set the variable'''
x = LpVariable.dicts('Lane',Lanes,None,None,LpInteger)
for l in Lanes:
x[l].bounds(MinVols[l], MaxVols[l])
''' Set the objective function '''
prob += lpSum([x[l] * Impacts[l] for l in Lanes]), 'Sum_of_Impact'
''' Set the constraints '''
#to meet the requirements of the high level constrains i.e. total optimized volume shouldn't differ more than +/-10%
prob += lpSum([x[l] for l in Lanes]) <= VOLUME_LIMIT_UPPER
prob += lpSum([x[l] for l in Lanes]) >= VOLUME_LIMIT_LOWER
到目前为止一切都很顺利,它完成了它应该做的事情。
现在我尝试添加另一个约束,它基本上需要在某个列字符串 (SecToSecRel) 上聚合变量,即创建一个小计,该小计应该小于分配给不同表中字符串的值
这是第二个表格的一部分,并且与它对齐的值有效。
Total_Customer_Target = pd.DataFrame({"TOrgNo":data2.iloc[:,1],"SecToSecRel":(data2.iloc[:,2]+data2.iloc[:,3]), "Target 2018":data2.iloc[:,6]})
SRGNRel_Customer_Target_lane = (Total_Customer_Target[Total_Customer_Target.SecToSecRel == SecToSecRel[l]].sum()["Target 2018"])*1.10
然后添加约束....我尝试了各种方法,不幸的是没有保留所有方法。
第一次尝试 - 没用
prob += lpSum([x[l] for l in Lanes if any(SecToSecRel) == SecToSecRel[l]]) <= SRGNRel_Customer_Target_lane,
第二次尝试 - 在中间停止并返回 KeyError
for s in Total_Customer_Target.SecToSecRel:
prob += lpSum([x[l] for l in Lanes if s in SecToSecRel[l]]) <= SRGNRel_Customer_Target_lane
第三次尝试 - 以为我必须摆脱 Key 错误才能让它工作,设置一个默认值 - 但没有工作
for s in Total_Customer_Target.SecToSecRel:
default = 'No Sector Relation'
SecToSecRel.append(Total_Customer_Target.setdefault(s,default))
prob += lpSum([x[l] for l in Lanes if s in SecToSecRel[l]]) <= SRGNRel_Customer_Target_lane,
请问有人可以帮我吗?
【问题讨论】:
标签: python linear-programming pulp