#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# This example reads an LP model from a file and solves it.# If the model can be solved, then it finds the smallest positive variable,# sets its upper bound to zero, and resolves the model two ways:# first with an advanced start, then without an advanced start# (i.e. 'from scratch').importsysimportgurobipyasgpfromgurobipyimportGRBiflen(sys.argv)<2:print("Usage: lpmod.py filename")sys.exit(0)# Read model and determine whether it is an LPmodel=gp.read(sys.argv[1])ifmodel.IsMIP==1:print("The model is not a linear program")sys.exit(1)model.optimize()status=model.Statusifstatus==GRB.INF_OR_UNBDorstatus==GRB.INFEASIBLEorstatus==GRB.UNBOUNDED:print("The model cannot be solved because it is infeasible or unbounded")sys.exit(1)ifstatus!=GRB.OPTIMAL:print(f"Optimization was stopped with status{status}")sys.exit(0)# Find the smallest variable valueminVal=GRB.INFINITYforvinmodel.getVars():ifv.X>0.0001andv.X<minValandv.LB==0.0:minVal=v.XminVar=vprint(f"\n*** Setting{minVar.VarName} from{minVal:g} to zero ***\n")minVar.UB=0.0# Solve from this starting pointmodel.optimize()# Save iteration & time infowarmCount=model.IterCountwarmTime=model.Runtime# Reset the model and resolveprint("\n*** Resetting and solving without an advanced start ***\n")model.reset()model.optimize()coldCount=model.IterCountcoldTime=model.Runtimeprint("")print(f"*** Warm start:{warmCount:g} iterations,{warmTime:g} seconds")print(f"*** Cold start:{coldCount:g} iterations,{coldTime:g} seconds")
Help and Feedback