API Reference¶
- gurobi_modelanalyzer.scale_model(model, method, scale_passes=1, scale_conv_tol=1e-4, scaling_lb=1e-8, scaling_ub=1e8, value_threshold=1e-13, scaling_time_limit=inf, scaling_log='', scaling_log_to_console=1, init_scaling=0, power_of_2=False, env=None)¶
Scale a Gurobi optimization model to improve numerical conditioning.
Creates a scaled copy of the input model using the specified scaling method. The scaled model can be optimized directly and provides methods to recover the solution in the original (unscaled) variable space.
- Parameters:
model – Required Gurobi model to scale.
method –
Scaling method to use. One of:
'equilibration': iteratively scales rows and columns to bring coefficient magnitudes to a similar range. Supports all model types: (MI)LP, (MI)QP, (MI)QCP, and (MI)QCQP.'geometric_mean': scales rows and columns by \(1/\sqrt{a_i^{\max} \cdot a_i^{\min}}\), where \(a_i^{\max}\) and \(a_i^{\min}\) are the largest and smallest absolute nonzero values in the row or column. Supports (MI)LP and (MI)QCP models (linear objective only).'arithmetic_mean': scales rows and columns by the reciprocal of the mean absolute value of their nonzero entries. Supports (MI)LP and (MI)QCP models (linear objective only).See Advanced Usage Guide for the model class taxonomy and a comparison of methods.
scale_passes – Maximum number of scaling iterations. Default: 1.
scale_conv_tol – Convergence tolerance. Scaling stops early when the maximum deviation of the scaling factors from 1 falls below this threshold. Default: 1e-4.
scaling_lb – Lower bound for scaling factors. Prevents extreme downscaling. Default: 1e-8.
scaling_ub – Upper bound for scaling factors. Prevents extreme upscaling. Default: 1e8.
value_threshold – Coefficients with absolute value below this threshold are treated as zero. Default: 1e-13.
scaling_time_limit – Time limit in seconds for the scaling iterations. If reached, the best scaling found so far is used. Default: no limit.
scaling_log – Optional path to a log file. If provided, scaling progress is written to this file. Default: no file.
scaling_log_to_console – Set to 1 (default) to print scaling progress to the console, 0 to suppress.
init_scaling –
Controls use of user-provided initial scaling factors set via the
_init_scalingattribute on variables and constraints:0(default): ignore_init_scaling; run the iterative algorithm from the identity scaling.1: apply_init_scalingas the final scaling and return immediately without running the iterative algorithm.2(warmstart): pre-apply_init_scaling, then run the iterative algorithm on top. The final factors are the product of the user-provided values and the algorithm’s output.power_of_2 – If
True, round each final scaling factor to the nearest power of 2 before building the scaled model. Powers of 2 have exact floating-point representations, so the scaled coefficients carry no round-off error from the scaling factors themselves. Applied after all scaling passes and after anyinit_scalingaccumulation. Default:False.env – Optional Gurobi environment (
gurobipy.Env) to use for the scaled model.
- Returns:
A ScaledModel object containing the scaled model with scaling information attached. Selected variable and constraint attributes (start values, hints, priorities, basis statuses, lazy flags) are automatically inherited from the original model; see Advanced Usage Guide for the full list.
- Raises:
ValueError – If the model contains general constraints (nonlinear, indicator, abs, min/max, piecewise-linear, etc.). These constraint types are not supported by the scaling module.
ValueError – If init_scaling is not 0, 1, or 2.
TypeError – If power_of_2 is not a boolean.
- gurobi_modelanalyzer.read_scaling_file(path, model)¶
Parse a
.sclscaling input file and apply the specified initial scaling factors to the Gurobi model’s variables and constraints.The function sets
_init_scalingand, where applicable,_scaleattributes directly on thegurobipy.Varandgurobipy.Constrobjects of model. After calling this function, passinit_scaling=2toscale_model()to run the iterative algorithm as a warmstart on top of the loaded factors, orinit_scaling=1to apply them without any further iteration.Malformed lines and unrecognised variable or constraint names issue
UserWarningvia Python’s standardwarningsmachinery.See Scaling Files for a description of the
.sclfile format and usage examples.- Parameters:
path (str) – Path to the
.sclscaling input file.model – Gurobi model whose objects will receive
_init_scaling/_scaleattributes.
- Returns:
None
ScaledModel¶
ScaledModel is a subclass of gurobipy.Model returned by
scale_model(). It adds methods and properties for recovering
unscaled solutions and computing violations in the original variable space.
- ScaledModel.getVarsUnscaled()¶
Return a list of ScaledVar objects, one per variable in the model. Each object exposes both the scaled solution value (
X) and the unscaled value (Xunsc). Must be called after optimization.- Returns:
List of ScaledVar objects.
- ScaledModel.getConstrsUnscaled()¶
Return a list of ScaledConstr objects, one per linear constraint. After calling
computeUnscVio(), each object exposes the unscaled constraint violation viaUnscViolation.- Returns:
List of ScaledConstr objects.
- ScaledModel.getQConstrsUnscaled()¶
Return a list of ScaledQConstr objects, one per quadratic constraint. After calling
computeUnscVio(), each object exposes the unscaled constraint violation viaUnscViolation.- Returns:
List of ScaledQConstr objects.
- ScaledModel.computeUnscVio()¶
Compute constraint and bound violations in the original (unscaled) variable space. Must be called after optimization. Populates
UnscViolationon all constraint wrappers andUnscBoundViolationon all variable wrappers, and sets theMaxUnscVio,MaxUnscConstrVio, andMaxUnscBoundVioproperties. The original model is stored automatically byscale_model().
- ScaledModel.computeUnscObj()¶
Compute the objective value in the original (unscaled) variable space using the unscaled solution values from
getVarsUnscaled(). Must be called after optimization. Result is stored inScaledModel.UnscObjVal.- Returns:
None(access the result viaScaledModel.UnscObjVal).
- ScaledModel.write_scaling(path, lock_factors=True)¶
Export the scaling factors computed by
scale_model()to a.sclfile. The file can later be passed toread_scaling_file()or togurobi_clsvia--scaling-fileto reproduce or continue from the same scaling.All variables and constraints are written, including those with a factor of 1.0. When
lock_factors=True, a factor of 1.0 withlock_flag=0locks that object at the identity scaling and prevents the algorithm from modifying it on re-import.- Parameters:
path (str) – Output file path (conventionally with
.sclextension).lock_factors (bool) – If
True(default), all entries are written withlock_flag=0, meaning the factors are kept fixed when the file is re-imported and the algorithm cannot modify them. IfFalse,lock_flag=1is written so the factors act as a warmstart.
- Returns:
None
- ScaledModel.UnscObjVal¶
Unscaled objective value computed by
computeUnscObj().Noneuntil that method is called.
- ScaledModel.MaxUnscVio¶
Maximum unscaled violation across all constraints and variable bounds. Available after calling
computeUnscVio().
- ScaledModel.MaxUnscConstrVio¶
Maximum unscaled violation across all linear and quadratic constraints. Available after calling
computeUnscVio().
- ScaledModel.MaxUnscBoundVio¶
Maximum unscaled variable bound violation. Available after calling
computeUnscVio().
- ScaledModel.ScalingTime¶
Wall-clock time in seconds taken by the scaling procedure.
- ScaledModel.ColScaling¶
Diagonal column scaling matrix as a
scipy.sparsematrix. Entry \(i\) contains the scaling factor applied to variable \(i\).
- ScaledModel.RowScaling¶
Diagonal row scaling matrix as a
scipy.sparsematrix. Entry \(i\) contains the scaling factor applied to constraint \(i\).
ScaledVar¶
Wrapper around a gurobipy.Var object returned by
ScaledModel.getVarsUnscaled(). All standard Gurobi variable
attributes (e.g. VarName, LB, UB) are forwarded to the
underlying variable.
- ScaledVar.X¶
Solution value in the scaled model space.
- ScaledVar.Xunsc¶
Solution value recovered in the original (unscaled) space: \(x_i = s_i \cdot y_i\), where \(s_i\) is the column scaling factor and \(y_i\) is the scaled solution value.
- ScaledVar.scaling_factor¶
Column scaling factor \(s_i\) applied to this variable by
scale_model(). Always positive.
- ScaledVar.UnscBoundViolation¶
Unscaled bound violation for this variable. Available after calling
ScaledModel.computeUnscVio().
ScaledConstr / ScaledQConstr¶
Wrappers around gurobipy.Constr and gurobipy.QConstr objects returned
by ScaledModel.getConstrsUnscaled() and
ScaledModel.getQConstrsUnscaled() respectively. All standard
Gurobi constraint attributes are forwarded to the underlying object.
- ScaledConstr.UnscViolation¶
- ScaledQConstr.UnscViolation¶
Unscaled constraint violation. Available after calling
ScaledModel.computeUnscVio().
- ScaledConstr.scaling_factor¶
- ScaledQConstr.scaling_factor¶
Row scaling factor applied to this constraint by
scale_model(). Always positive.