Modify a python code to solve a sequence of linear programs where a lower bound of a variable is being incremented by 1
<p>Using Gurobi and Python I could optimally solve a linear problem for a given situation. However, when I am given a range in which a lower bound for one of the variable can increase in an increment of 1, I could not figure how to write the right syntax (for loop, while, or other), I think I am missing alot so to speak. Secondly, If I were to plot the optimal objective value sequentially obtained versus each increment of the lower bound of subject variable, how can I go about it? Honestly, I could not exactly imagine how would I retain for every solve its optimal value with its relevant lower bound individually to be shown in a single plot at the end. </p>

<p>First, define a class that acts as a wrapper for a Gurobi model. It should take a lower bound as an argument which you'll use when defining your variable.</p>

<pre><code>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
</code></pre>

<p>Now you can create a main function that creates a new GurobiModel object (with a specified lower bound for your variable of interest) and solves it to optimality:</p>

<pre><code>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))
</code></pre>

<p>Hopefully this is enough to get you started. There's lots that could be done differently, but this will be fine for smaller models (for example, if your model is quite large, you wouldn't want to rebuild it in entirety every iteration; it would make more sense to extract the variable using the getVarByName() method and change the lower bound).</p>

python gurobi