GurobiPersistent
(class from pyomo.solvers.plugins.solvers.gurobi_persistent
)
- class pyomo.solvers.plugins.solvers.gurobi_persistent.GurobiPersistent(**kwds)[source]
Bases:
PersistentSolver
,GurobiDirect
A class that provides a persistent interface to Gurobi. Direct solver interfaces do not use any file io. Rather, they interface directly with the python bindings for the specific solver. Persistent solver interfaces are similar except that they “remember” their model. Thus, persistent solver interfaces allow incremental changes to the solver model (e.g., the gurobi python model or the cplex python model). Note that users are responsible for notifying the persistent solver interfaces when changes are made to the corresponding pyomo model.
- Keyword Arguments:
model (ConcreteModel) – Passing a model to the constructor is equivalent to calling the set_instance method.
type (str) – String indicating the class type of the solver instance.
name (str) – String representing either the class type of the solver instance or an assigned name.
doc (str) – Documentation for the solver
options (dict) – Dictionary of solver options
Methods
__init__
(**kwds)Constructor
add_block
(block)Add a single Pyomo Block to the solver's model.
add_column
(model, var, obj_coef, ...)Add a column to the solver's and Pyomo model
add_constraint
(con)Add a single constraint to the solver's model.
add_sos_constraint
(con)Add a single SOS constraint to the solver's model (if supported).
add_var
(var)Add a single variable to the solver's model.
available
([exception_flag])Returns True if the solver is available.
cbCut
(con)Add a cut within a callback.
cbGet
(what)cbGetNodeRel
(vars)cbGetSolution
(vars)cbLazy
(con)cbSetSolution
(vars, solution)cbUseSolution
()close
()Frees local Gurobi resources used by this solver instance.
Frees all Gurobi models used by this solver, and frees the global default Gurobi environment.
config_block
([init])default_variable_value
()get_gurobi_param_info
(param)Get information about a gurobi parameter.
get_linear_constraint_attr
(con, attr)Get the value of an attribute on a gurobi linear constraint.
get_model_attr
(attr)Get the value of an attribute on the Gurobi model.
get_quadratic_constraint_attr
(con, attr)Get the value of an attribute on a gurobi quadratic constraint.
get_sos_attr
(con, attr)Get the value of an attribute on a gurobi sos constraint.
get_var_attr
(var, attr)Get the value of an attribute on a gurobi var.
has_capability
(cap)Returns a boolean value representing whether a solver supports a specific feature.
True if set_instance has been called and this solver interface has a pyomo model and a solver model.
True if the solver is present and has a valid license (if applicable)
load_duals
([cons_to_load])Load the duals into the 'dual' suffix.
load_rc
(vars_to_load)Load the reduced costs into the 'rc' suffix.
load_slacks
([cons_to_load])Load the values of the slack variables into the 'slack' suffix.
load_vars
([vars_to_load])Load the values from the solver's variables into the corresponding pyomo variables.
Returns the current problem format.
remove_block
(block)Remove a single block from the solver's model.
remove_constraint
(con)Remove a single constraint from the solver's model.
Remove a single SOS constraint from the solver's model.
remove_var
(var)Remove a single variable from the solver's model.
reset
()Reset the state of the solver
Returns the current results format.
set_callback
([func])Specify a callback for gurobi to use.
set_gurobi_param
(param, val)Set a gurobi parameter.
set_instance
(model, **kwds)This method is used to translate the Pyomo model provided to an instance of the solver's Python model.
set_linear_constraint_attr
(con, attr, val)Set the value of an attribute on a gurobi linear constraint.
set_objective
(obj)Set the solver's objective.
set_options
(istr)set_problem_format
(format)Set the current problem format (if it's valid) and update the results format to something valid for this problem format.
set_results_format
(format)Set the current results format (if it's valid for the current problem format).
set_var_attr
(var, attr, val)Set the value of an attribute on a gurobi variable.
solve
(*args, **kwds)Solve the model.
update
()update_var
(var)Update a single variable in the solver's model.
version
()Returns a 4-tuple describing the solver executable version.
True is the solver can accept a warm-start solution
write
(filename)Write the model to a file (e.g., and lp file).
Attributes
keepfiles
log_file
soln_file
suffixes
symbolic_solver_labels
tee
warm_start_file_name
warm_start_solve
A results object return from the solve method.
Member Documentation
- add_block(block)
Add a single Pyomo Block to the solver’s model.
This will keep any existing model components intact.
- Parameters:
block (Block (scalar Block or single BlockData))
- add_column(model, var, obj_coef, constraints, coefficients)
Add a column to the solver’s and Pyomo model
This will add the Pyomo variable var to the solver’s model, and put the coefficients on the associated constraints in the solver model. If the obj_coef is not zero, it will add obj_coef*var to the objective of both the Pyomo and solver’s model.
- add_constraint(con)
Add a single constraint to the solver’s model.
This will keep any existing model components intact.
- Parameters:
con (Constraint (scalar Constraint or single ConstraintData))
- add_sos_constraint(con)
Add a single SOS constraint to the solver’s model (if supported).
This will keep any existing model components intact.
- Parameters:
con (SOSConstraint)
- add_var(var)
Add a single variable to the solver’s model.
This will keep any existing model components intact.
- Parameters:
var (Var)
- available(exception_flag=True)
Returns True if the solver is available.
- Parameters:
exception_flag (bool) – If True, raise an exception instead of returning False if the solver is unavailable (defaults to False)
In general,
available()
does not need to be called by the user, as the check is run automatically when solving a model. However it is useful for a simple retry loop when using a shared Gurobi license:with SolverFactory('gurobi', solver_io='python') as opt: while not available(exception_flag=False): time.sleep(1) opt.solve(model)
- cbCut(con)[source]
Add a cut within a callback.
- Parameters:
con (pyomo.core.base.constraint.ConstraintData) – The cut to add
- cbLazy(con)[source]
- Parameters:
con (pyomo.core.base.constraint.ConstraintData) – The lazy constraint to add
- close()
Frees local Gurobi resources used by this solver instance.
All Gurobi models created by the solver are freed. If the solver was created with
manage_env=True
, this method also closes the Gurobi environment used by this solver instance. Calling.close()
achieves the same result as exiting the solver context (although using context managers is preferred where possible):opt = SolverFactory('gurobi', solver_io='python', manage_env=True) try: opt.solve(model) finally: opt.close() # Gurobi models and environments created by `opt` are freed
As with the context manager, if
manage_env=False
(the default) was used, only the Gurobi models created by this solver are freed. The default global Gurobi environment will still be active:opt = SolverFactory('gurobi', solver_io='python') try: opt.solve(model) finally: opt.close() # Gurobi models created by `opt` are freed; however the # default/global Gurobi environment is still active
- close_global()
Frees all Gurobi models used by this solver, and frees the global default Gurobi environment.
The default environment is used by all
GurobiDirect
solvers started withmanage_env=False
(the default). To guarantee that all Gurobi resources are freed, all instantiatedGurobiDirect
solvers must also be correctly closed.The following example will free all Gurobi resources assuming the user did not create any other models (e.g. via another
GurobiDirect
object withmanage_env=False
):opt = SolverFactory('gurobi', solver_io='python') try: opt.solve(model) finally: opt.close_global() # All Gurobi models created by `opt` are freed and the default # Gurobi environment is closed
- get_linear_constraint_attr(con, attr)[source]
Get the value of an attribute on a gurobi linear constraint.
- Parameters:
con (pyomo.core.base.constraint.ConstraintData) – The pyomo constraint for which the corresponding gurobi constraint attribute should be retrieved.
attr (str) –
The attribute to get. Options are:
Sense RHS ConstrName Pi Slack CBasis DStart Lazy IISConstr SARHSLow SARHSUp FarkasDual
- get_model_attr(attr)[source]
Get the value of an attribute on the Gurobi model.
- Parameters:
attr (str) –
The attribute to get. See Gurobi documentation for descriptions of the attributes.
Options are:
NumVars NumConstrs NumSOS NumQConstrs NumgGenConstrs NumNZs DNumNZs NumQNZs NumQCNZs NumIntVars NumBinVars NumPWLObjVars ModelName ModelSense ObjCon ObjVal ObjBound ObjBoundC PoolObjBound PoolObjVal MIPGap Runtime Status SolCount IterCount BarIterCount NodeCount IsMIP IsQP IsQCP IsMultiObj IISMinimal MaxCoeff MinCoeff MaxBound MinBound MaxObjCoeff MinObjCoeff MaxRHS MinRHS MaxQCCoeff MinQCCoeff MaxQCLCoeff MinQCLCoeff MaxQCRHS MinQCRHS MaxQObjCoeff MinQObjCoeff Kappa KappaExact FarkasProof TuneResultCount LicenseExpiration BoundVio BoundSVio BoundVioIndex BoundSVioIndex BoundVioSum BoundSVioSum ConstrVio ConstrSVio ConstrVioIndex ConstrSVioIndex ConstrVioSum ConstrSVioSum ConstrResidual ConstrSResidual ConstrResidualIndex ConstrSResidualIndex ConstrResidualSum ConstrSResidualSum DualVio DualSVio DualVioIndex DualSVioIndex DualVioSum DualSVioSum DualResidual DualSResidual DualResidualIndex DualSResidualIndex DualResidualSum DualSResidualSum ComplVio ComplVioIndex ComplVioSum IntVio IntVioIndex IntVioSum
- get_quadratic_constraint_attr(con, attr)[source]
Get the value of an attribute on a gurobi quadratic constraint.
- Parameters:
con (pyomo.core.base.constraint.ConstraintData) – The pyomo constraint for which the corresponding gurobi constraint attribute should be retrieved.
attr (str) –
The attribute to get. Options are:
QCSense QCRHS QCName QCPi QCSlack IISQConstr
- get_sos_attr(con, attr)[source]
Get the value of an attribute on a gurobi sos constraint.
- Parameters:
con (pyomo.core.base.sos.SOSConstraintData) – The pyomo SOS constraint for which the corresponding gurobi SOS constraint attribute should be retrieved.
attr (str) –
The attribute to get. Options are:
IISSOS
- get_var_attr(var, attr)[source]
Get the value of an attribute on a gurobi var.
- Parameters:
var (pyomo.core.base.var.VarData) – The pyomo var for which the corresponding gurobi var attribute should be retrieved.
attr (str) –
The attribute to get. Options are:
LB UB Obj VType VarName X Xn RC BarX Start VarHintVal VarHintPri BranchPriority VBasis PStart IISLB IISUB PWLObjCvx SAObjLow SAObjUp SALBLow SALBUp SAUBLow SAUBUp UnbdRay
- has_capability(cap)
Returns a boolean value representing whether a solver supports a specific feature. Defaults to ‘False’ if the solver is unaware of an option. Expects a string.
Example: # prints True if solver supports sos1 constraints, and False otherwise print(solver.has_capability(‘sos1’)
# prints True is solver supports ‘feature’, and False otherwise print(solver.has_capability(‘feature’)
- has_instance()
True if set_instance has been called and this solver interface has a pyomo model and a solver model.
- Returns:
tmp
- Return type:
- license_is_valid()
True if the solver is present and has a valid license (if applicable)
- load_duals(cons_to_load=None)
Load the duals into the ‘dual’ suffix. The ‘dual’ suffix must live on the parent model.
- Parameters:
cons_to_load (list of Constraint)
- load_rc(vars_to_load)
Load the reduced costs into the ‘rc’ suffix. The ‘rc’ suffix must live on the parent model.
- load_slacks(cons_to_load=None)
Load the values of the slack variables into the ‘slack’ suffix. The ‘slack’ suffix must live on the parent model.
- Parameters:
cons_to_load (list of Constraint)
- load_vars(vars_to_load=None)
Load the values from the solver’s variables into the corresponding pyomo variables.
- problem_format()
Returns the current problem format.
- remove_block(block)
Remove a single block from the solver’s model.
This will keep any other model components intact.
WARNING: Users must call remove_block BEFORE modifying the block.
- Parameters:
block (Block (scalar Block or a single BlockData))
- remove_constraint(con)
Remove a single constraint from the solver’s model.
This will keep any other model components intact.
- Parameters:
con (Constraint (scalar Constraint or single ConstraintData))
- remove_sos_constraint(con)
Remove a single SOS constraint from the solver’s model.
This will keep any other model components intact.
- Parameters:
con (SOSConstraint)
- remove_var(var)
Remove a single variable from the solver’s model.
This will keep any other model components intact.
- Parameters:
var (Var (scalar Var or single VarData))
- results_format()
Returns the current results format.
- set_callback(func=None)[source]
Specify a callback for gurobi to use.
- Parameters:
func (function) –
The function to call. The function should have three arguments. The first will be the pyomo model being solved. The second will be the GurobiPersistent instance. The third will be an enum member of gurobipy.GRB.Callback. This will indicate where in the branch and bound algorithm gurobi is at. For example, suppose we want to solve
\begin{array}{ll} \min & 2x + y \\ \mathrm{s.t.} & y \geq (x-2)^2 \\ & 0 \leq x \leq 4 \\ & y \geq 0 \\ & y \in \mathbb{Z} \end{array}as an MILP using extended cutting planes in callbacks.
from gurobipy import GRB import pyomo.environ as pe from pyomo.core.expr.taylor_series import taylor_series_expansion m = pe.ConcreteModel() m.x = pe.Var(bounds=(0, 4)) m.y = pe.Var(within=pe.Integers, bounds=(0, None)) m.obj = pe.Objective(expr=2*m.x + m.y) m.cons = pe.ConstraintList() # for the cutting planes def _add_cut(xval): # a function to generate the cut m.x.value = xval return m.cons.add(m.y >= taylor_series_expansion((m.x - 2)**2)) _add_cut(0) # start with 2 cuts at the bounds of x _add_cut(4) # this is an arbitrary choice opt = pe.SolverFactory('gurobi_persistent') opt.set_instance(m) opt.set_gurobi_param('PreCrush', 1) opt.set_gurobi_param('LazyConstraints', 1) def my_callback(cb_m, cb_opt, cb_where): if cb_where == GRB.Callback.MIPSOL: cb_opt.cbGetSolution(vars=[m.x, m.y]) if m.y.value < (m.x.value - 2)**2 - 1e-6: cb_opt.cbLazy(_add_cut(m.x.value)) opt.set_callback(my_callback) opt.solve()
>>> assert abs(m.x.value - 1) <= 1e-6 >>> assert abs(m.y.value - 1) <= 1e-6
- set_gurobi_param(param, val)[source]
Set a gurobi parameter.
- Parameters:
param (str) – The gurobi parameter to set. Options include any gurobi parameter. Please see the Gurobi documentation for options.
val (any) – The value to set the parameter to. See Gurobi documentation for possible values.
- set_instance(model, **kwds)
This method is used to translate the Pyomo model provided to an instance of the solver’s Python model. This discards any existing model and starts from scratch.
- Parameters:
model (ConcreteModel) – The pyomo model to be used with the solver.
- Keyword Arguments:
symbolic_solver_labels (bool) – If True, the solver’s components (e.g., variables, constraints) will be given names that correspond to the Pyomo component names.
skip_trivial_constraints (bool) – If True, then any constraints with a constant body will not be added to the solver model. Be careful with this. If a trivial constraint is skipped then that constraint cannot be removed from a persistent solver (an error will be raised if a user tries to remove a non-existent constraint).
output_fixed_variable_bounds (bool) – If False then an error will be raised if a fixed variable is used in one of the solver constraints. This is useful for catching bugs. Ordinarily a fixed variable should appear as a constant value in the solver constraints. If True, then the error will not be raised.
- set_linear_constraint_attr(con, attr, val)[source]
Set the value of an attribute on a gurobi linear constraint.
- Parameters:
con (pyomo.core.base.constraint.ConstraintData) – The pyomo constraint for which the corresponding gurobi constraint attribute should be modified.
attr (str) –
The attribute to be modified. Options are:
CBasis DStart Lazy
val (any) – See gurobi documentation for acceptable values.
- set_objective(obj)
Set the solver’s objective. Note that, at least for now, any existing objective will be discarded. Other than that, any existing model components will remain intact.
- Parameters:
obj (Objective)
- set_problem_format(format)
Set the current problem format (if it’s valid) and update the results format to something valid for this problem format.
- set_results_format(format)
Set the current results format (if it’s valid for the current problem format).
- set_var_attr(var, attr, val)[source]
Set the value of an attribute on a gurobi variable.
- Parameters:
con (pyomo.core.base.var.VarData) – The pyomo var for which the corresponding gurobi var attribute should be modified.
attr (str) –
The attribute to be modified. Options are:
Start VarHintVal VarHintPri BranchPriority VBasis PStart
val (any) – See gurobi documentation for acceptable values.
- solve(*args, **kwds)
Solve the model.
- Keyword Arguments:
suffixes (list of str) – The strings should represent suffixes support by the solver. Examples include ‘dual’, ‘slack’, and ‘rc’.
options (dict) – Dictionary of solver options. See the solver documentation for possible solver options.
warmstart (bool) – If True, the solver will be warmstarted.
keepfiles (bool) – If True, the solver log file will be saved.
logfile (str) – Name to use for the solver log file.
load_solutions (bool) – If True and a solution exists, the solution will be loaded into the Pyomo model.
report_timing (bool) – If True, then timing information will be printed.
tee (bool) – If True, then the solver log will be printed.
- update_var(var)[source]
Update a single variable in the solver’s model.
This will update bounds, fix/unfix the variable as needed, and update the variable type.
- Parameters:
var (Var (scalar Var or single VarData))
- version()
Returns a 4-tuple describing the solver executable version.
- warm_start_capable()
True is the solver can accept a warm-start solution
- write(filename)[source]
Write the model to a file (e.g., and lp file).
- Parameters:
filename (str) – Name of the file to which the model should be written.
- results
A results object return from the solve method.