修改python代码以解决一系列线性程序,其中变量的下限增加1

时间:2016-09-06 08:17:23

标签: python gurobi

使用Gurobi和Python我可以针对特定情况最优地解决线性问题。但是,当我给出一个范围,其中一个变量的下限可以以1的增量增加,我无法想出如何编写正确的语法(for循环,while或其他),我想我是遗失了很多可以这么说。其次,如果我要绘制顺序获得的最佳目标值与主题变量下限的每个增量,我该怎么办呢?老实说,我无法想象我将如何保留每个解决方案的最佳值及其相关的下限,以便在最后的单个图中显示。

1 个答案:

答案 0 :(得分:0)

首先,定义一个充当Gurobi模型包装的类。在定义变量时,它应该使用下限作为参数。

class GurobiModel:

    def __init__(self, lowerBound):

        # create an empty Gurobi model object
        self.model = Model()

        # add your variable using the argument as the lower bound
        self.variable1 = self.model.addVar(lb=lowerBound,vtype=GRB.INTEGER, name='variable1')

        # add more variables, constraints, and objective function
        ...

    def solve(self):
        """Solves the model and returns the optimal objective value (or None if model is infeasible)."""
        self.model.optimize()

        if model.status == GRB.Status.OPTIMAL:
            # if model is optimal, return objective value
            return self.model.objVal
        else:
            print('Model is infeasible')
            return None

现在您可以创建一个主函数来创建一个新的GurobiModel对象(为您感兴趣的变量指定下限)并将其解决为最优:

def main():
    N = 50              # number of iterations
    result_set = []     # this stores tuples containing the lower bound and the objective function

    for i in range(N):
        model = GurobiModel(lowerBound = i)
        objVal = model.solve()
        result_set.append((i, objVal))

希望这足以让你入门。可以用不同的方式完成许多工作,但这对于较小的模型来说会很好(例如,如果你的模型非常大,你不希望每次迭代都重建它;使用它来提取变量会更有意义getVarByName()方法并更改下限。