简体   繁体   English

如何节省计算时间以在python中添加约束和求和函数

[英]How to save the computation time to add constraints and sum function in python

I am trying to use quicksum function in added constraints when building model in Python and using Gurobi to solve it. 我试图在Python中构建模型并使用Gurobi来解决时,在添加的约束中使用quicksum函数。 When I use a large-scale case, it will take a long time. 当我使用大型案例时,将花费很长时间。 Any way to improve it? 有什么改善的方法吗? (V[(i,t)] is the inputs and Q[(i,j,t)] is the variable in my model): (V [(i,t)]是输入,而Q [(i,j,t)]是模型中的变量):

for i in range(I):
    for t in range(T):
        m.addConstr(quicksum(Q[(i,j,t)] for j in range(J))<=V[(i,t)])

The Gurobi Documentation says this: Gurobi文档说:

Note that while quicksum is much faster than sum, it isn't the fastest approach for building a large expression. 请注意,虽然quicksum比sum快得多,但这并不是构建大型表达式的最快方法。 Use addTerms or the LinExpr() constructor if you want the quickest possible expression construction. 如果需要最快的表达式构造,请使用addTerms或LinExpr()构造函数。

Based on that comment, you could try one of the options below and compare the performance: 根据该评论,您可以尝试以下选项之一并比较性能:

for i in range(I):
    for t in range(T):
        m.addConstr(LinExpr((1.0, Q[(i,j,t)]) for j in range(J))<=V[(i,t)])

for i in range(I):
    for t in range(T):
        expr = LinExpr()
        m.addConstr(expr.addTerms([1.0]*J, Q[(i,j,t)] for j in range(J))<=V[(i,t)])

In a comment you asked how to expand this to handle nested quicksums: 在注释中,您询问了如何扩展它以处理嵌套的Quicksum:

obj=quicksum(quicksum(Q[(i,j,t)]*g[i,j,t] for i in range(I)) for j in range(J)) for t in range(T))

You can build up your objective function using nested for loops instead of nested quicksums. 您可以使用嵌套的for循环而不是嵌套的quicksum来建立目标函数。 Each call to addTerms does just what it says, it adds additional terms to the existing expression. 每次对addTerms调用都addTerms其所说的进行,它将其他术语添加到现有表达式中。 Just make sure you pull the expression declaration out of the loops: 只需确保将表达式声明从循环中拉出即可:

obj= LinExpr()
for i in range(I):
    for t in range(T):
        obj.addTerms(g[(i,j,t)] for j in range(J), 
                     Q[(i,j,t)] for j in range(J))
m.setObjective(obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM