ortools.linear_solver.pywraplp
1# This file was automatically generated by SWIG (https://www.swig.org). 2# Version 4.1.1 3# 4# Do not make changes to this file unless you know what you are doing - modify 5# the SWIG interface file instead. 6 7from sys import version_info as _swig_python_version_info 8# Import the low-level C/C++ module 9if __package__ or "." in __name__: 10 from . import _pywraplp 11else: 12 import _pywraplp 13 14try: 15 import builtins as __builtin__ 16except ImportError: 17 import __builtin__ 18 19def _swig_repr(self): 20 try: 21 strthis = "proxy of " + self.this.__repr__() 22 except __builtin__.Exception: 23 strthis = "" 24 return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) 25 26 27def _swig_setattr_nondynamic_instance_variable(set): 28 def set_instance_attr(self, name, value): 29 if name == "this": 30 set(self, name, value) 31 elif name == "thisown": 32 self.this.own(value) 33 elif hasattr(self, name) and isinstance(getattr(type(self), name), property): 34 set(self, name, value) 35 else: 36 raise AttributeError("You cannot add instance attributes to %s" % self) 37 return set_instance_attr 38 39 40def _swig_setattr_nondynamic_class_variable(set): 41 def set_class_attr(cls, name, value): 42 if hasattr(cls, name) and not isinstance(getattr(cls, name), property): 43 set(cls, name, value) 44 else: 45 raise AttributeError("You cannot add class attributes to %s" % cls) 46 return set_class_attr 47 48 49def _swig_add_metaclass(metaclass): 50 """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" 51 def wrapper(cls): 52 return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) 53 return wrapper 54 55 56class _SwigNonDynamicMeta(type): 57 """Meta class to enforce nondynamic attributes (no new attributes) for a class""" 58 __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__) 59 60 61 62import numbers 63from ortools.linear_solver.python.linear_solver_natural_api import OFFSET_KEY 64from ortools.linear_solver.python.linear_solver_natural_api import inf 65from ortools.linear_solver.python.linear_solver_natural_api import LinearExpr 66from ortools.linear_solver.python.linear_solver_natural_api import ProductCst 67from ortools.linear_solver.python.linear_solver_natural_api import Sum 68from ortools.linear_solver.python.linear_solver_natural_api import SumArray 69from ortools.linear_solver.python.linear_solver_natural_api import SumCst 70from ortools.linear_solver.python.linear_solver_natural_api import LinearConstraint 71from ortools.linear_solver.python.linear_solver_natural_api import VariableExpr 72 73class Solver(object): 74 r""" 75 This mathematical programming (MP) solver class is the main class 76 though which users build and solve problems. 77 """ 78 79 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 80 __repr__ = _swig_repr 81 CLP_LINEAR_PROGRAMMING = _pywraplp.Solver_CLP_LINEAR_PROGRAMMING 82 GLPK_LINEAR_PROGRAMMING = _pywraplp.Solver_GLPK_LINEAR_PROGRAMMING 83 GLOP_LINEAR_PROGRAMMING = _pywraplp.Solver_GLOP_LINEAR_PROGRAMMING 84 PDLP_LINEAR_PROGRAMMING = _pywraplp.Solver_PDLP_LINEAR_PROGRAMMING 85 SCIP_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_SCIP_MIXED_INTEGER_PROGRAMMING 86 GLPK_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_GLPK_MIXED_INTEGER_PROGRAMMING 87 CBC_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_CBC_MIXED_INTEGER_PROGRAMMING 88 BOP_INTEGER_PROGRAMMING = _pywraplp.Solver_BOP_INTEGER_PROGRAMMING 89 SAT_INTEGER_PROGRAMMING = _pywraplp.Solver_SAT_INTEGER_PROGRAMMING 90 GUROBI_LINEAR_PROGRAMMING = _pywraplp.Solver_GUROBI_LINEAR_PROGRAMMING 91 GUROBI_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_GUROBI_MIXED_INTEGER_PROGRAMMING 92 CPLEX_LINEAR_PROGRAMMING = _pywraplp.Solver_CPLEX_LINEAR_PROGRAMMING 93 CPLEX_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_CPLEX_MIXED_INTEGER_PROGRAMMING 94 XPRESS_LINEAR_PROGRAMMING = _pywraplp.Solver_XPRESS_LINEAR_PROGRAMMING 95 XPRESS_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_XPRESS_MIXED_INTEGER_PROGRAMMING 96 97 def __init__(self, name, problem_type): 98 r""" Create a solver with the given name and underlying solver backend.""" 99 _pywraplp.Solver_swiginit(self, _pywraplp.new_Solver(name, problem_type)) 100 __swig_destroy__ = _pywraplp.delete_Solver 101 102 @staticmethod 103 def CreateSolver(solver_id): 104 r""" 105 Recommended factory method to create a MPSolver instance, especially in 106 non C++ languages. 107 108 It returns a newly created solver instance if successful, or a nullptr 109 otherwise. This can occur if the relevant interface is not linked in, or if 110 a needed license is not accessible for commercial solvers. 111 112 Ownership of the solver is passed on to the caller of this method. 113 It will accept both string names of the OptimizationProblemType enum, as 114 well as a short version (i.e. "SCIP_MIXED_INTEGER_PROGRAMMING" or "SCIP"). 115 116 solver_id is case insensitive, and the following names are supported: 117 - CLP_LINEAR_PROGRAMMING or CLP 118 - CBC_MIXED_INTEGER_PROGRAMMING or CBC 119 - GLOP_LINEAR_PROGRAMMING or GLOP 120 - BOP_INTEGER_PROGRAMMING or BOP 121 - SAT_INTEGER_PROGRAMMING or SAT or CP_SAT 122 - SCIP_MIXED_INTEGER_PROGRAMMING or SCIP 123 - GUROBI_LINEAR_PROGRAMMING or GUROBI_LP 124 - GUROBI_MIXED_INTEGER_PROGRAMMING or GUROBI or GUROBI_MIP 125 - CPLEX_LINEAR_PROGRAMMING or CPLEX_LP 126 - CPLEX_MIXED_INTEGER_PROGRAMMING or CPLEX or CPLEX_MIP 127 - XPRESS_LINEAR_PROGRAMMING or XPRESS_LP 128 - XPRESS_MIXED_INTEGER_PROGRAMMING or XPRESS or XPRESS_MIP 129 - GLPK_LINEAR_PROGRAMMING or GLPK_LP 130 - GLPK_MIXED_INTEGER_PROGRAMMING or GLPK or GLPK_MIP 131 """ 132 return _pywraplp.Solver_CreateSolver(solver_id) 133 134 @staticmethod 135 def SupportsProblemType(problem_type): 136 r""" 137 Whether the given problem type is supported (this will depend on the 138 targets that you linked). 139 """ 140 return _pywraplp.Solver_SupportsProblemType(problem_type) 141 142 def Clear(self): 143 r""" 144 Clears the objective (including the optimization direction), all variables 145 and constraints. All the other properties of the MPSolver (like the time 146 limit) are kept untouched. 147 """ 148 return _pywraplp.Solver_Clear(self) 149 150 def NumVariables(self): 151 r""" Returns the number of variables.""" 152 return _pywraplp.Solver_NumVariables(self) 153 154 def variables(self): 155 r""" 156 Returns the array of variables handled by the MPSolver. (They are listed in 157 the order in which they were created.) 158 """ 159 return _pywraplp.Solver_variables(self) 160 161 def variable(self, index): 162 r"""Returns the variable at position index.""" 163 return _pywraplp.Solver_variable(self, index) 164 165 def LookupVariable(self, var_name): 166 r""" 167 Looks up a variable by name, and returns nullptr if it does not exist. The 168 first call has a O(n) complexity, as the variable name index is lazily 169 created upon first use. Will crash if variable names are not unique. 170 """ 171 return _pywraplp.Solver_LookupVariable(self, var_name) 172 173 def Var(self, lb, ub, integer, name): 174 r""" 175 Creates a variable with the given bounds, integrality requirement and 176 name. Bounds can be finite or +/- MPSolver::infinity(). The MPSolver owns 177 the variable (i.e. the returned pointer is borrowed). Variable names are 178 optional. If you give an empty name, name() will auto-generate one for you 179 upon request. 180 """ 181 return _pywraplp.Solver_Var(self, lb, ub, integer, name) 182 183 def NumVar(self, lb, ub, name): 184 r""" Creates a continuous variable.""" 185 return _pywraplp.Solver_NumVar(self, lb, ub, name) 186 187 def IntVar(self, lb, ub, name): 188 r""" Creates an integer variable.""" 189 return _pywraplp.Solver_IntVar(self, lb, ub, name) 190 191 def BoolVar(self, name): 192 r""" Creates a boolean variable.""" 193 return _pywraplp.Solver_BoolVar(self, name) 194 195 def NumConstraints(self): 196 r""" Returns the number of constraints.""" 197 return _pywraplp.Solver_NumConstraints(self) 198 199 def constraints(self): 200 r""" 201 Returns the array of constraints handled by the MPSolver. 202 203 They are listed in the order in which they were created. 204 """ 205 return _pywraplp.Solver_constraints(self) 206 207 def constraint(self, index): 208 r""" Returns the constraint at the given index.""" 209 return _pywraplp.Solver_constraint(self, index) 210 211 def LookupConstraint(self, constraint_name): 212 r""" 213 Looks up a constraint by name, and returns nullptr if it does not exist. 214 215 The first call has a O(n) complexity, as the constraint name index is 216 lazily created upon first use. Will crash if constraint names are not 217 unique. 218 """ 219 return _pywraplp.Solver_LookupConstraint(self, constraint_name) 220 221 def Constraint(self, *args): 222 r""" 223 *Overload 1:* 224 225 Creates a linear constraint with given bounds. 226 227 Bounds can be finite or +/- MPSolver::infinity(). The MPSolver class 228 assumes ownership of the constraint. 229 230 :rtype: :py:class:`MPConstraint` 231 :return: a pointer to the newly created constraint. 232 233 | 234 235 *Overload 2:* 236 Creates a constraint with -infinity and +infinity bounds. 237 238 | 239 240 *Overload 3:* 241 Creates a named constraint with given bounds. 242 243 | 244 245 *Overload 4:* 246 Creates a named constraint with -infinity and +infinity bounds. 247 """ 248 return _pywraplp.Solver_Constraint(self, *args) 249 250 def Objective(self): 251 r""" Returns the mutable objective object.""" 252 return _pywraplp.Solver_Objective(self) 253 OPTIMAL = _pywraplp.Solver_OPTIMAL 254 r""" optimal.""" 255 FEASIBLE = _pywraplp.Solver_FEASIBLE 256 r""" feasible, or stopped by limit.""" 257 INFEASIBLE = _pywraplp.Solver_INFEASIBLE 258 r""" proven infeasible.""" 259 UNBOUNDED = _pywraplp.Solver_UNBOUNDED 260 r""" proven unbounded.""" 261 ABNORMAL = _pywraplp.Solver_ABNORMAL 262 r""" abnormal, i.e., error of some kind.""" 263 MODEL_INVALID = _pywraplp.Solver_MODEL_INVALID 264 r""" the model is trivially invalid (NaN coefficients, etc).""" 265 NOT_SOLVED = _pywraplp.Solver_NOT_SOLVED 266 r""" not been solved yet.""" 267 268 def Solve(self, *args): 269 r""" 270 *Overload 1:* 271 Solves the problem using the default parameter values. 272 273 | 274 275 *Overload 2:* 276 Solves the problem using the specified parameter values. 277 """ 278 return _pywraplp.Solver_Solve(self, *args) 279 280 def ComputeConstraintActivities(self): 281 r""" 282 Advanced usage: compute the "activities" of all constraints, which are the 283 sums of their linear terms. The activities are returned in the same order 284 as constraints(), which is the order in which constraints were added; but 285 you can also use MPConstraint::index() to get a constraint's index. 286 """ 287 return _pywraplp.Solver_ComputeConstraintActivities(self) 288 289 def VerifySolution(self, tolerance, log_errors): 290 r""" 291 Advanced usage: Verifies the *correctness* of the solution. 292 293 It verifies that all variables must be within their domains, all 294 constraints must be satisfied, and the reported objective value must be 295 accurate. 296 297 Usage: 298 - This can only be called after Solve() was called. 299 - "tolerance" is interpreted as an absolute error threshold. 300 - For the objective value only, if the absolute error is too large, 301 the tolerance is interpreted as a relative error threshold instead. 302 - If "log_errors" is true, every single violation will be logged. 303 - If "tolerance" is negative, it will be set to infinity(). 304 305 Most users should just set the --verify_solution flag and not bother using 306 this method directly. 307 """ 308 return _pywraplp.Solver_VerifySolution(self, tolerance, log_errors) 309 310 def InterruptSolve(self): 311 r""" 312 Interrupts the Solve() execution to terminate processing if possible. 313 314 If the underlying interface supports interruption; it does that and returns 315 true regardless of whether there's an ongoing Solve() or not. The Solve() 316 call may still linger for a while depending on the conditions. If 317 interruption is not supported; returns false and does nothing. 318 MPSolver::SolverTypeSupportsInterruption can be used to check if 319 interruption is supported for a given solver type. 320 """ 321 return _pywraplp.Solver_InterruptSolve(self) 322 323 def FillSolutionResponseProto(self, response): 324 r""" Encodes the current solution in a solution response protocol buffer.""" 325 return _pywraplp.Solver_FillSolutionResponseProto(self, response) 326 327 @staticmethod 328 def SolveWithProto(model_request, response, interrupt=None): 329 r""" 330 Solves the model encoded by a MPModelRequest protocol buffer and fills the 331 solution encoded as a MPSolutionResponse. The solve is stopped prematurely 332 if interrupt is non-null at set to true during (or before) solving. 333 Interruption is only supported if SolverTypeSupportsInterruption() returns 334 true for the requested solver. Passing a non-null interruption with any 335 other solver type immediately returns an MPSOLVER_INCOMPATIBLE_OPTIONS 336 error. 337 338 Note(user): This attempts to first use `DirectlySolveProto()` (if 339 implemented). Consequently, this most likely does *not* override any of 340 the default parameters of the underlying solver. This behavior *differs* 341 from `MPSolver::Solve()` which by default sets the feasibility tolerance 342 and the gap limit (as of 2020/02/11, to 1e-7 and 0.0001, respectively). 343 """ 344 return _pywraplp.Solver_SolveWithProto(model_request, response, interrupt) 345 346 def ExportModelToProto(self, output_model): 347 r""" Exports model to protocol buffer.""" 348 return _pywraplp.Solver_ExportModelToProto(self, output_model) 349 350 def SetSolverSpecificParametersAsString(self, parameters): 351 r""" 352 Advanced usage: pass solver specific parameters in text format. 353 354 The format is solver-specific and is the same as the corresponding solver 355 configuration file format. Returns true if the operation was successful. 356 """ 357 return _pywraplp.Solver_SetSolverSpecificParametersAsString(self, parameters) 358 FREE = _pywraplp.Solver_FREE 359 AT_LOWER_BOUND = _pywraplp.Solver_AT_LOWER_BOUND 360 AT_UPPER_BOUND = _pywraplp.Solver_AT_UPPER_BOUND 361 FIXED_VALUE = _pywraplp.Solver_FIXED_VALUE 362 BASIC = _pywraplp.Solver_BASIC 363 364 @staticmethod 365 def infinity(): 366 r""" 367 Infinity. 368 369 You can use -MPSolver::infinity() for negative infinity. 370 """ 371 return _pywraplp.Solver_infinity() 372 373 def EnableOutput(self): 374 r""" Enables solver logging.""" 375 return _pywraplp.Solver_EnableOutput(self) 376 377 def SuppressOutput(self): 378 r""" Suppresses solver logging.""" 379 return _pywraplp.Solver_SuppressOutput(self) 380 381 def iterations(self): 382 r""" Returns the number of simplex iterations.""" 383 return _pywraplp.Solver_iterations(self) 384 385 def nodes(self): 386 r""" 387 Returns the number of branch-and-bound nodes evaluated during the solve. 388 389 Only available for discrete problems. 390 """ 391 return _pywraplp.Solver_nodes(self) 392 393 def SolverVersion(self): 394 r""" Returns a string describing the underlying solver and its version.""" 395 return _pywraplp.Solver_SolverVersion(self) 396 397 def ComputeExactConditionNumber(self): 398 r""" 399 Advanced usage: computes the exact condition number of the current scaled 400 basis: L1norm(B) * L1norm(inverse(B)), where B is the scaled basis. 401 402 This method requires that a basis exists: it should be called after Solve. 403 It is only available for continuous problems. It is implemented for GLPK 404 but not CLP because CLP does not provide the API for doing it. 405 406 The condition number measures how well the constraint matrix is conditioned 407 and can be used to predict whether numerical issues will arise during the 408 solve: the model is declared infeasible whereas it is feasible (or 409 vice-versa), the solution obtained is not optimal or violates some 410 constraints, the resolution is slow because of repeated singularities. 411 412 The rule of thumb to interpret the condition number kappa is: 413 - o kappa <= 1e7: virtually no chance of numerical issues 414 - o 1e7 < kappa <= 1e10: small chance of numerical issues 415 - o 1e10 < kappa <= 1e13: medium chance of numerical issues 416 - o kappa > 1e13: high chance of numerical issues 417 418 The computation of the condition number depends on the quality of the LU 419 decomposition, so it is not very accurate when the matrix is ill 420 conditioned. 421 """ 422 return _pywraplp.Solver_ComputeExactConditionNumber(self) 423 424 def NextSolution(self): 425 r""" 426 Some solvers (MIP only, not LP) can produce multiple solutions to the 427 problem. Returns true when another solution is available, and updates the 428 MPVariable* objects to make the new solution queryable. Call only after 429 calling solve. 430 431 The optimality properties of the additional solutions found, and whether or 432 not the solver computes them ahead of time or when NextSolution() is called 433 is solver specific. 434 435 As of 2020-02-10, only Gurobi and SCIP support NextSolution(), see 436 linear_solver_interfaces_test for an example of how to configure these 437 solvers for multiple solutions. Other solvers return false unconditionally. 438 """ 439 return _pywraplp.Solver_NextSolution(self) 440 441 def set_time_limit(self, time_limit_milliseconds): 442 return _pywraplp.Solver_set_time_limit(self, time_limit_milliseconds) 443 444 def wall_time(self): 445 return _pywraplp.Solver_wall_time(self) 446 447 def LoadModelFromProto(self, input_model): 448 return _pywraplp.Solver_LoadModelFromProto(self, input_model) 449 450 def LoadModelFromProtoKeepNames(self, input_model): 451 return _pywraplp.Solver_LoadModelFromProtoKeepNames(self, input_model) 452 453 def LoadModelFromProtoWithUniqueNamesOrDie(self, input_model): 454 return _pywraplp.Solver_LoadModelFromProtoWithUniqueNamesOrDie(self, input_model) 455 456 def LoadSolutionFromProto(self, *args): 457 return _pywraplp.Solver_LoadSolutionFromProto(self, *args) 458 459 def ExportModelAsLpFormat(self, obfuscated): 460 return _pywraplp.Solver_ExportModelAsLpFormat(self, obfuscated) 461 462 def ExportModelAsMpsFormat(self, fixed_format, obfuscated): 463 return _pywraplp.Solver_ExportModelAsMpsFormat(self, fixed_format, obfuscated) 464 465 def SetHint(self, variables, values): 466 r""" 467 Set a hint for solution. 468 469 If a feasible or almost-feasible solution to the problem is already known, 470 it may be helpful to pass it to the solver so that it can be used. A 471 solver that supports this feature will try to use this information to 472 create its initial feasible solution. 473 474 Note that it may not always be faster to give a hint like this to the 475 solver. There is also no guarantee that the solver will use this hint or 476 try to return a solution "close" to this assignment in case of multiple 477 optimal solutions. 478 """ 479 return _pywraplp.Solver_SetHint(self, variables, values) 480 481 def SetNumThreads(self, num_theads): 482 r""" Sets the number of threads to be used by the solver.""" 483 return _pywraplp.Solver_SetNumThreads(self, num_theads) 484 485 def Add(self, constraint, name=''): 486 if isinstance(constraint, bool): 487 if constraint: 488 return self.RowConstraint(0, 0, name) 489 else: 490 return self.RowConstraint(1, 1, name) 491 else: 492 return constraint.Extract(self, name) 493 494 def Sum(self, expr_array): 495 result = SumArray(expr_array) 496 return result 497 498 def RowConstraint(self, *args): 499 return self.Constraint(*args) 500 501 def Minimize(self, expr): 502 objective = self.Objective() 503 objective.Clear() 504 objective.SetMinimization() 505 if isinstance(expr, numbers.Number): 506 objective.SetOffset(expr) 507 else: 508 coeffs = expr.GetCoeffs() 509 objective.SetOffset(coeffs.pop(OFFSET_KEY, 0.0)) 510 for v, c, in list(coeffs.items()): 511 objective.SetCoefficient(v, float(c)) 512 513 def Maximize(self, expr): 514 objective = self.Objective() 515 objective.Clear() 516 objective.SetMaximization() 517 if isinstance(expr, numbers.Number): 518 objective.SetOffset(expr) 519 else: 520 coeffs = expr.GetCoeffs() 521 objective.SetOffset(coeffs.pop(OFFSET_KEY, 0.0)) 522 for v, c, in list(coeffs.items()): 523 objective.SetCoefficient(v, float(c)) 524 525 526 @staticmethod 527 def Infinity(): 528 return _pywraplp.Solver_Infinity() 529 530 def SetTimeLimit(self, x): 531 return _pywraplp.Solver_SetTimeLimit(self, x) 532 533 def WallTime(self): 534 return _pywraplp.Solver_WallTime(self) 535 536 def Iterations(self): 537 return _pywraplp.Solver_Iterations(self) 538 539# Register Solver in _pywraplp: 540_pywraplp.Solver_swigregister(Solver) 541 542def __lshift__(*args): 543 return _pywraplp.__lshift__(*args) 544class Objective(object): 545 r""" A class to express a linear objective.""" 546 547 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 548 549 def __init__(self, *args, **kwargs): 550 raise AttributeError("No constructor defined") 551 __repr__ = _swig_repr 552 553 def Clear(self): 554 r""" 555 Clears the offset, all variables and coefficients, and the optimization 556 direction. 557 """ 558 return _pywraplp.Objective_Clear(self) 559 560 def SetCoefficient(self, var, coeff): 561 r""" 562 Sets the coefficient of the variable in the objective. 563 564 If the variable does not belong to the solver, the function just returns, 565 or crashes in non-opt mode. 566 """ 567 return _pywraplp.Objective_SetCoefficient(self, var, coeff) 568 569 def GetCoefficient(self, var): 570 r""" 571 Gets the coefficient of a given variable in the objective 572 573 It returns 0 if the variable does not appear in the objective). 574 """ 575 return _pywraplp.Objective_GetCoefficient(self, var) 576 577 def SetOffset(self, value): 578 r""" Sets the constant term in the objective.""" 579 return _pywraplp.Objective_SetOffset(self, value) 580 581 def offset(self): 582 r""" Gets the constant term in the objective.""" 583 return _pywraplp.Objective_offset(self) 584 585 def SetOptimizationDirection(self, maximize): 586 r""" Sets the optimization direction (maximize: true or minimize: false).""" 587 return _pywraplp.Objective_SetOptimizationDirection(self, maximize) 588 589 def SetMinimization(self): 590 r""" Sets the optimization direction to minimize.""" 591 return _pywraplp.Objective_SetMinimization(self) 592 593 def SetMaximization(self): 594 r""" Sets the optimization direction to maximize.""" 595 return _pywraplp.Objective_SetMaximization(self) 596 597 def maximization(self): 598 r""" Is the optimization direction set to maximize?""" 599 return _pywraplp.Objective_maximization(self) 600 601 def minimization(self): 602 r""" Is the optimization direction set to minimize?""" 603 return _pywraplp.Objective_minimization(self) 604 605 def Value(self): 606 r""" 607 Returns the objective value of the best solution found so far. 608 609 It is the optimal objective value if the problem has been solved to 610 optimality. 611 612 Note: the objective value may be slightly different than what you could 613 compute yourself using ``MPVariable::solution_value();`` please use the 614 --verify_solution flag to gain confidence about the numerical stability of 615 your solution. 616 """ 617 return _pywraplp.Objective_Value(self) 618 619 def BestBound(self): 620 r""" 621 Returns the best objective bound. 622 623 In case of minimization, it is a lower bound on the objective value of the 624 optimal integer solution. Only available for discrete problems. 625 """ 626 return _pywraplp.Objective_BestBound(self) 627 628 def Offset(self): 629 return _pywraplp.Objective_Offset(self) 630 __swig_destroy__ = _pywraplp.delete_Objective 631 632# Register Objective in _pywraplp: 633_pywraplp.Objective_swigregister(Objective) 634class Variable(object): 635 r""" The class for variables of a Mathematical Programming (MP) model.""" 636 637 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 638 639 def __init__(self, *args, **kwargs): 640 raise AttributeError("No constructor defined") 641 642 def name(self): 643 r""" Returns the name of the variable.""" 644 return _pywraplp.Variable_name(self) 645 646 def SetInteger(self, integer): 647 r""" Sets the integrality requirement of the variable.""" 648 return _pywraplp.Variable_SetInteger(self, integer) 649 650 def integer(self): 651 r""" Returns the integrality requirement of the variable.""" 652 return _pywraplp.Variable_integer(self) 653 654 def solution_value(self): 655 r""" 656 Returns the value of the variable in the current solution. 657 658 If the variable is integer, then the value will always be an integer (the 659 underlying solver handles floating-point values only, but this function 660 automatically rounds it to the nearest integer; see: man 3 round). 661 """ 662 return _pywraplp.Variable_solution_value(self) 663 664 def index(self): 665 r""" Returns the index of the variable in the MPSolver::variables_.""" 666 return _pywraplp.Variable_index(self) 667 668 def lb(self): 669 r""" Returns the lower bound.""" 670 return _pywraplp.Variable_lb(self) 671 672 def ub(self): 673 r""" Returns the upper bound.""" 674 return _pywraplp.Variable_ub(self) 675 676 def SetBounds(self, lb, ub): 677 r""" Sets both the lower and upper bounds.""" 678 return _pywraplp.Variable_SetBounds(self, lb, ub) 679 680 def reduced_cost(self): 681 r""" 682 Advanced usage: returns the reduced cost of the variable in the current 683 solution (only available for continuous problems). 684 """ 685 return _pywraplp.Variable_reduced_cost(self) 686 687 def basis_status(self): 688 r""" 689 Advanced usage: returns the basis status of the variable in the current 690 solution (only available for continuous problems). 691 692 See also: MPSolver::BasisStatus. 693 """ 694 return _pywraplp.Variable_basis_status(self) 695 696 def branching_priority(self): 697 r""" 698 Advanced usage: Certain MIP solvers (e.g. Gurobi or SCIP) allow you to set 699 a per-variable priority for determining which variable to branch on. 700 701 A value of 0 is treated as default, and is equivalent to not setting the 702 branching priority. The solver looks first to branch on fractional 703 variables in higher priority levels. As of 2019-05, only Gurobi and SCIP 704 support setting branching priority; all other solvers will simply ignore 705 this annotation. 706 """ 707 return _pywraplp.Variable_branching_priority(self) 708 709 def SetBranchingPriority(self, priority): 710 return _pywraplp.Variable_SetBranchingPriority(self, priority) 711 712 def __str__(self): 713 return _pywraplp.Variable___str__(self) 714 715 def __repr__(self): 716 return _pywraplp.Variable___repr__(self) 717 718 def __getattr__(self, name): 719 return getattr(VariableExpr(self), name) 720 721 722 def SolutionValue(self): 723 return _pywraplp.Variable_SolutionValue(self) 724 725 def Integer(self): 726 return _pywraplp.Variable_Integer(self) 727 728 def Lb(self): 729 return _pywraplp.Variable_Lb(self) 730 731 def Ub(self): 732 return _pywraplp.Variable_Ub(self) 733 734 def SetLb(self, x): 735 return _pywraplp.Variable_SetLb(self, x) 736 737 def SetUb(self, x): 738 return _pywraplp.Variable_SetUb(self, x) 739 740 def ReducedCost(self): 741 return _pywraplp.Variable_ReducedCost(self) 742 __swig_destroy__ = _pywraplp.delete_Variable 743 744# Register Variable in _pywraplp: 745_pywraplp.Variable_swigregister(Variable) 746class Constraint(object): 747 r""" 748 The class for constraints of a Mathematical Programming (MP) model. 749 750 A constraint is represented as a linear equation or inequality. 751 """ 752 753 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 754 755 def __init__(self, *args, **kwargs): 756 raise AttributeError("No constructor defined") 757 __repr__ = _swig_repr 758 759 def name(self): 760 r""" Returns the name of the constraint.""" 761 return _pywraplp.Constraint_name(self) 762 763 def Clear(self): 764 r""" Clears all variables and coefficients. Does not clear the bounds.""" 765 return _pywraplp.Constraint_Clear(self) 766 767 def SetCoefficient(self, var, coeff): 768 r""" 769 Sets the coefficient of the variable on the constraint. 770 771 If the variable does not belong to the solver, the function just returns, 772 or crashes in non-opt mode. 773 """ 774 return _pywraplp.Constraint_SetCoefficient(self, var, coeff) 775 776 def GetCoefficient(self, var): 777 r""" 778 Gets the coefficient of a given variable on the constraint (which is 0 if 779 the variable does not appear in the constraint). 780 """ 781 return _pywraplp.Constraint_GetCoefficient(self, var) 782 783 def lb(self): 784 r""" Returns the lower bound.""" 785 return _pywraplp.Constraint_lb(self) 786 787 def ub(self): 788 r""" Returns the upper bound.""" 789 return _pywraplp.Constraint_ub(self) 790 791 def SetBounds(self, lb, ub): 792 r""" Sets both the lower and upper bounds.""" 793 return _pywraplp.Constraint_SetBounds(self, lb, ub) 794 795 def set_is_lazy(self, laziness): 796 r""" 797 Advanced usage: sets the constraint "laziness". 798 799 **This is only supported for SCIP and has no effect on other 800 solvers.** 801 802 When **laziness** is true, the constraint is only considered by the Linear 803 Programming solver if its current solution violates the constraint. In this 804 case, the constraint is definitively added to the problem. This may be 805 useful in some MIP problems, and may have a dramatic impact on performance. 806 807 For more info see: http://tinyurl.com/lazy-constraints. 808 """ 809 return _pywraplp.Constraint_set_is_lazy(self, laziness) 810 811 def index(self): 812 r""" Returns the index of the constraint in the MPSolver::constraints_.""" 813 return _pywraplp.Constraint_index(self) 814 815 def dual_value(self): 816 r""" 817 Advanced usage: returns the dual value of the constraint in the current 818 solution (only available for continuous problems). 819 """ 820 return _pywraplp.Constraint_dual_value(self) 821 822 def basis_status(self): 823 r""" 824 Advanced usage: returns the basis status of the constraint. 825 826 It is only available for continuous problems). 827 828 Note that if a constraint "linear_expression in [lb, ub]" is transformed 829 into "linear_expression + slack = 0" with slack in [-ub, -lb], then this 830 status is the same as the status of the slack variable with AT_UPPER_BOUND 831 and AT_LOWER_BOUND swapped. 832 833 See also: MPSolver::BasisStatus. 834 """ 835 return _pywraplp.Constraint_basis_status(self) 836 837 def Lb(self): 838 return _pywraplp.Constraint_Lb(self) 839 840 def Ub(self): 841 return _pywraplp.Constraint_Ub(self) 842 843 def SetLb(self, x): 844 return _pywraplp.Constraint_SetLb(self, x) 845 846 def SetUb(self, x): 847 return _pywraplp.Constraint_SetUb(self, x) 848 849 def DualValue(self): 850 return _pywraplp.Constraint_DualValue(self) 851 __swig_destroy__ = _pywraplp.delete_Constraint 852 853# Register Constraint in _pywraplp: 854_pywraplp.Constraint_swigregister(Constraint) 855class MPSolverParameters(object): 856 r""" 857 This class stores parameter settings for LP and MIP solvers. Some parameters 858 are marked as advanced: do not change their values unless you know what you 859 are doing! 860 861 For developers: how to add a new parameter: 862 - Add the new Foo parameter in the DoubleParam or IntegerParam enum. 863 - If it is a categorical param, add a FooValues enum. 864 - Decide if the wrapper should define a default value for it: yes 865 if it controls the properties of the solution (example: 866 tolerances) or if it consistently improves performance, no 867 otherwise. If yes, define kDefaultFoo. 868 - Add a foo_value_ member and, if no default value is defined, a 869 foo_is_default_ member. 870 - Add code to handle Foo in Set...Param, Reset...Param, 871 Get...Param, Reset and the constructor. 872 - In class MPSolverInterface, add a virtual method SetFoo, add it 873 to SetCommonParameters or SetMIPParameters, and implement it for 874 each solver. Sometimes, parameters need to be implemented 875 differently, see for example the INCREMENTALITY implementation. 876 - Add a test in linear_solver_test.cc. 877 878 TODO(user): store the parameter values in a protocol buffer 879 instead. We need to figure out how to deal with the subtleties of 880 the default values. 881 """ 882 883 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 884 __repr__ = _swig_repr 885 RELATIVE_MIP_GAP = _pywraplp.MPSolverParameters_RELATIVE_MIP_GAP 886 r""" Limit for relative MIP gap.""" 887 PRIMAL_TOLERANCE = _pywraplp.MPSolverParameters_PRIMAL_TOLERANCE 888 r""" 889 Advanced usage: tolerance for primal feasibility of basic solutions. 890 891 This does not control the integer feasibility tolerance of integer 892 solutions for MIP or the tolerance used during presolve. 893 """ 894 DUAL_TOLERANCE = _pywraplp.MPSolverParameters_DUAL_TOLERANCE 895 r""" Advanced usage: tolerance for dual feasibility of basic solutions.""" 896 PRESOLVE = _pywraplp.MPSolverParameters_PRESOLVE 897 r""" Advanced usage: presolve mode.""" 898 LP_ALGORITHM = _pywraplp.MPSolverParameters_LP_ALGORITHM 899 r""" Algorithm to solve linear programs.""" 900 INCREMENTALITY = _pywraplp.MPSolverParameters_INCREMENTALITY 901 r""" Advanced usage: incrementality from one solve to the next.""" 902 SCALING = _pywraplp.MPSolverParameters_SCALING 903 r""" Advanced usage: enable or disable matrix scaling.""" 904 PRESOLVE_OFF = _pywraplp.MPSolverParameters_PRESOLVE_OFF 905 r""" Presolve is off.""" 906 PRESOLVE_ON = _pywraplp.MPSolverParameters_PRESOLVE_ON 907 r""" Presolve is on.""" 908 DUAL = _pywraplp.MPSolverParameters_DUAL 909 r""" Dual simplex.""" 910 PRIMAL = _pywraplp.MPSolverParameters_PRIMAL 911 r""" Primal simplex.""" 912 BARRIER = _pywraplp.MPSolverParameters_BARRIER 913 r""" Barrier algorithm.""" 914 INCREMENTALITY_OFF = _pywraplp.MPSolverParameters_INCREMENTALITY_OFF 915 r""" Start solve from scratch.""" 916 INCREMENTALITY_ON = _pywraplp.MPSolverParameters_INCREMENTALITY_ON 917 r""" 918 Reuse results from previous solve as much as the underlying solver 919 allows. 920 """ 921 SCALING_OFF = _pywraplp.MPSolverParameters_SCALING_OFF 922 r""" Scaling is off.""" 923 SCALING_ON = _pywraplp.MPSolverParameters_SCALING_ON 924 r""" Scaling is on.""" 925 926 def __init__(self): 927 r""" The constructor sets all parameters to their default value.""" 928 _pywraplp.MPSolverParameters_swiginit(self, _pywraplp.new_MPSolverParameters()) 929 930 def SetDoubleParam(self, param, value): 931 r""" Sets a double parameter to a specific value.""" 932 return _pywraplp.MPSolverParameters_SetDoubleParam(self, param, value) 933 934 def SetIntegerParam(self, param, value): 935 r""" Sets a integer parameter to a specific value.""" 936 return _pywraplp.MPSolverParameters_SetIntegerParam(self, param, value) 937 938 def GetDoubleParam(self, param): 939 r""" Returns the value of a double parameter.""" 940 return _pywraplp.MPSolverParameters_GetDoubleParam(self, param) 941 942 def GetIntegerParam(self, param): 943 r""" Returns the value of an integer parameter.""" 944 return _pywraplp.MPSolverParameters_GetIntegerParam(self, param) 945 __swig_destroy__ = _pywraplp.delete_MPSolverParameters 946 947# Register MPSolverParameters in _pywraplp: 948_pywraplp.MPSolverParameters_swigregister(MPSolverParameters) 949cvar = _pywraplp.cvar 950MPSolverParameters.kDefaultRelativeMipGap = _pywraplp.cvar.MPSolverParameters_kDefaultRelativeMipGap 951MPSolverParameters.kDefaultPrimalTolerance = _pywraplp.cvar.MPSolverParameters_kDefaultPrimalTolerance 952MPSolverParameters.kDefaultDualTolerance = _pywraplp.cvar.MPSolverParameters_kDefaultDualTolerance 953MPSolverParameters.kDefaultPresolve = _pywraplp.cvar.MPSolverParameters_kDefaultPresolve 954MPSolverParameters.kDefaultIncrementality = _pywraplp.cvar.MPSolverParameters_kDefaultIncrementality 955 956class ModelExportOptions(object): 957 r""" Export options.""" 958 959 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 960 __repr__ = _swig_repr 961 962 def __init__(self): 963 _pywraplp.ModelExportOptions_swiginit(self, _pywraplp.new_ModelExportOptions()) 964 __swig_destroy__ = _pywraplp.delete_ModelExportOptions 965 966# Register ModelExportOptions in _pywraplp: 967_pywraplp.ModelExportOptions_swigregister(ModelExportOptions) 968 969def ExportModelAsLpFormat(*args): 970 return _pywraplp.ExportModelAsLpFormat(*args) 971 972def ExportModelAsMpsFormat(*args): 973 return _pywraplp.ExportModelAsMpsFormat(*args) 974 975def FindErrorInModelProto(input_model): 976 return _pywraplp.FindErrorInModelProto(input_model) 977 978def setup_variable_operator(opname): 979 setattr(Variable, opname, 980 lambda self, *args: getattr(VariableExpr(self), opname)(*args)) 981for opname in LinearExpr.OVERRIDDEN_OPERATOR_METHODS: 982 setup_variable_operator(opname)
74class Solver(object): 75 r""" 76 This mathematical programming (MP) solver class is the main class 77 though which users build and solve problems. 78 """ 79 80 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 81 __repr__ = _swig_repr 82 CLP_LINEAR_PROGRAMMING = _pywraplp.Solver_CLP_LINEAR_PROGRAMMING 83 GLPK_LINEAR_PROGRAMMING = _pywraplp.Solver_GLPK_LINEAR_PROGRAMMING 84 GLOP_LINEAR_PROGRAMMING = _pywraplp.Solver_GLOP_LINEAR_PROGRAMMING 85 PDLP_LINEAR_PROGRAMMING = _pywraplp.Solver_PDLP_LINEAR_PROGRAMMING 86 SCIP_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_SCIP_MIXED_INTEGER_PROGRAMMING 87 GLPK_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_GLPK_MIXED_INTEGER_PROGRAMMING 88 CBC_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_CBC_MIXED_INTEGER_PROGRAMMING 89 BOP_INTEGER_PROGRAMMING = _pywraplp.Solver_BOP_INTEGER_PROGRAMMING 90 SAT_INTEGER_PROGRAMMING = _pywraplp.Solver_SAT_INTEGER_PROGRAMMING 91 GUROBI_LINEAR_PROGRAMMING = _pywraplp.Solver_GUROBI_LINEAR_PROGRAMMING 92 GUROBI_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_GUROBI_MIXED_INTEGER_PROGRAMMING 93 CPLEX_LINEAR_PROGRAMMING = _pywraplp.Solver_CPLEX_LINEAR_PROGRAMMING 94 CPLEX_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_CPLEX_MIXED_INTEGER_PROGRAMMING 95 XPRESS_LINEAR_PROGRAMMING = _pywraplp.Solver_XPRESS_LINEAR_PROGRAMMING 96 XPRESS_MIXED_INTEGER_PROGRAMMING = _pywraplp.Solver_XPRESS_MIXED_INTEGER_PROGRAMMING 97 98 def __init__(self, name, problem_type): 99 r""" Create a solver with the given name and underlying solver backend.""" 100 _pywraplp.Solver_swiginit(self, _pywraplp.new_Solver(name, problem_type)) 101 __swig_destroy__ = _pywraplp.delete_Solver 102 103 @staticmethod 104 def CreateSolver(solver_id): 105 r""" 106 Recommended factory method to create a MPSolver instance, especially in 107 non C++ languages. 108 109 It returns a newly created solver instance if successful, or a nullptr 110 otherwise. This can occur if the relevant interface is not linked in, or if 111 a needed license is not accessible for commercial solvers. 112 113 Ownership of the solver is passed on to the caller of this method. 114 It will accept both string names of the OptimizationProblemType enum, as 115 well as a short version (i.e. "SCIP_MIXED_INTEGER_PROGRAMMING" or "SCIP"). 116 117 solver_id is case insensitive, and the following names are supported: 118 - CLP_LINEAR_PROGRAMMING or CLP 119 - CBC_MIXED_INTEGER_PROGRAMMING or CBC 120 - GLOP_LINEAR_PROGRAMMING or GLOP 121 - BOP_INTEGER_PROGRAMMING or BOP 122 - SAT_INTEGER_PROGRAMMING or SAT or CP_SAT 123 - SCIP_MIXED_INTEGER_PROGRAMMING or SCIP 124 - GUROBI_LINEAR_PROGRAMMING or GUROBI_LP 125 - GUROBI_MIXED_INTEGER_PROGRAMMING or GUROBI or GUROBI_MIP 126 - CPLEX_LINEAR_PROGRAMMING or CPLEX_LP 127 - CPLEX_MIXED_INTEGER_PROGRAMMING or CPLEX or CPLEX_MIP 128 - XPRESS_LINEAR_PROGRAMMING or XPRESS_LP 129 - XPRESS_MIXED_INTEGER_PROGRAMMING or XPRESS or XPRESS_MIP 130 - GLPK_LINEAR_PROGRAMMING or GLPK_LP 131 - GLPK_MIXED_INTEGER_PROGRAMMING or GLPK or GLPK_MIP 132 """ 133 return _pywraplp.Solver_CreateSolver(solver_id) 134 135 @staticmethod 136 def SupportsProblemType(problem_type): 137 r""" 138 Whether the given problem type is supported (this will depend on the 139 targets that you linked). 140 """ 141 return _pywraplp.Solver_SupportsProblemType(problem_type) 142 143 def Clear(self): 144 r""" 145 Clears the objective (including the optimization direction), all variables 146 and constraints. All the other properties of the MPSolver (like the time 147 limit) are kept untouched. 148 """ 149 return _pywraplp.Solver_Clear(self) 150 151 def NumVariables(self): 152 r""" Returns the number of variables.""" 153 return _pywraplp.Solver_NumVariables(self) 154 155 def variables(self): 156 r""" 157 Returns the array of variables handled by the MPSolver. (They are listed in 158 the order in which they were created.) 159 """ 160 return _pywraplp.Solver_variables(self) 161 162 def variable(self, index): 163 r"""Returns the variable at position index.""" 164 return _pywraplp.Solver_variable(self, index) 165 166 def LookupVariable(self, var_name): 167 r""" 168 Looks up a variable by name, and returns nullptr if it does not exist. The 169 first call has a O(n) complexity, as the variable name index is lazily 170 created upon first use. Will crash if variable names are not unique. 171 """ 172 return _pywraplp.Solver_LookupVariable(self, var_name) 173 174 def Var(self, lb, ub, integer, name): 175 r""" 176 Creates a variable with the given bounds, integrality requirement and 177 name. Bounds can be finite or +/- MPSolver::infinity(). The MPSolver owns 178 the variable (i.e. the returned pointer is borrowed). Variable names are 179 optional. If you give an empty name, name() will auto-generate one for you 180 upon request. 181 """ 182 return _pywraplp.Solver_Var(self, lb, ub, integer, name) 183 184 def NumVar(self, lb, ub, name): 185 r""" Creates a continuous variable.""" 186 return _pywraplp.Solver_NumVar(self, lb, ub, name) 187 188 def IntVar(self, lb, ub, name): 189 r""" Creates an integer variable.""" 190 return _pywraplp.Solver_IntVar(self, lb, ub, name) 191 192 def BoolVar(self, name): 193 r""" Creates a boolean variable.""" 194 return _pywraplp.Solver_BoolVar(self, name) 195 196 def NumConstraints(self): 197 r""" Returns the number of constraints.""" 198 return _pywraplp.Solver_NumConstraints(self) 199 200 def constraints(self): 201 r""" 202 Returns the array of constraints handled by the MPSolver. 203 204 They are listed in the order in which they were created. 205 """ 206 return _pywraplp.Solver_constraints(self) 207 208 def constraint(self, index): 209 r""" Returns the constraint at the given index.""" 210 return _pywraplp.Solver_constraint(self, index) 211 212 def LookupConstraint(self, constraint_name): 213 r""" 214 Looks up a constraint by name, and returns nullptr if it does not exist. 215 216 The first call has a O(n) complexity, as the constraint name index is 217 lazily created upon first use. Will crash if constraint names are not 218 unique. 219 """ 220 return _pywraplp.Solver_LookupConstraint(self, constraint_name) 221 222 def Constraint(self, *args): 223 r""" 224 *Overload 1:* 225 226 Creates a linear constraint with given bounds. 227 228 Bounds can be finite or +/- MPSolver::infinity(). The MPSolver class 229 assumes ownership of the constraint. 230 231 :rtype: :py:class:`MPConstraint` 232 :return: a pointer to the newly created constraint. 233 234 | 235 236 *Overload 2:* 237 Creates a constraint with -infinity and +infinity bounds. 238 239 | 240 241 *Overload 3:* 242 Creates a named constraint with given bounds. 243 244 | 245 246 *Overload 4:* 247 Creates a named constraint with -infinity and +infinity bounds. 248 """ 249 return _pywraplp.Solver_Constraint(self, *args) 250 251 def Objective(self): 252 r""" Returns the mutable objective object.""" 253 return _pywraplp.Solver_Objective(self) 254 OPTIMAL = _pywraplp.Solver_OPTIMAL 255 r""" optimal.""" 256 FEASIBLE = _pywraplp.Solver_FEASIBLE 257 r""" feasible, or stopped by limit.""" 258 INFEASIBLE = _pywraplp.Solver_INFEASIBLE 259 r""" proven infeasible.""" 260 UNBOUNDED = _pywraplp.Solver_UNBOUNDED 261 r""" proven unbounded.""" 262 ABNORMAL = _pywraplp.Solver_ABNORMAL 263 r""" abnormal, i.e., error of some kind.""" 264 MODEL_INVALID = _pywraplp.Solver_MODEL_INVALID 265 r""" the model is trivially invalid (NaN coefficients, etc).""" 266 NOT_SOLVED = _pywraplp.Solver_NOT_SOLVED 267 r""" not been solved yet.""" 268 269 def Solve(self, *args): 270 r""" 271 *Overload 1:* 272 Solves the problem using the default parameter values. 273 274 | 275 276 *Overload 2:* 277 Solves the problem using the specified parameter values. 278 """ 279 return _pywraplp.Solver_Solve(self, *args) 280 281 def ComputeConstraintActivities(self): 282 r""" 283 Advanced usage: compute the "activities" of all constraints, which are the 284 sums of their linear terms. The activities are returned in the same order 285 as constraints(), which is the order in which constraints were added; but 286 you can also use MPConstraint::index() to get a constraint's index. 287 """ 288 return _pywraplp.Solver_ComputeConstraintActivities(self) 289 290 def VerifySolution(self, tolerance, log_errors): 291 r""" 292 Advanced usage: Verifies the *correctness* of the solution. 293 294 It verifies that all variables must be within their domains, all 295 constraints must be satisfied, and the reported objective value must be 296 accurate. 297 298 Usage: 299 - This can only be called after Solve() was called. 300 - "tolerance" is interpreted as an absolute error threshold. 301 - For the objective value only, if the absolute error is too large, 302 the tolerance is interpreted as a relative error threshold instead. 303 - If "log_errors" is true, every single violation will be logged. 304 - If "tolerance" is negative, it will be set to infinity(). 305 306 Most users should just set the --verify_solution flag and not bother using 307 this method directly. 308 """ 309 return _pywraplp.Solver_VerifySolution(self, tolerance, log_errors) 310 311 def InterruptSolve(self): 312 r""" 313 Interrupts the Solve() execution to terminate processing if possible. 314 315 If the underlying interface supports interruption; it does that and returns 316 true regardless of whether there's an ongoing Solve() or not. The Solve() 317 call may still linger for a while depending on the conditions. If 318 interruption is not supported; returns false and does nothing. 319 MPSolver::SolverTypeSupportsInterruption can be used to check if 320 interruption is supported for a given solver type. 321 """ 322 return _pywraplp.Solver_InterruptSolve(self) 323 324 def FillSolutionResponseProto(self, response): 325 r""" Encodes the current solution in a solution response protocol buffer.""" 326 return _pywraplp.Solver_FillSolutionResponseProto(self, response) 327 328 @staticmethod 329 def SolveWithProto(model_request, response, interrupt=None): 330 r""" 331 Solves the model encoded by a MPModelRequest protocol buffer and fills the 332 solution encoded as a MPSolutionResponse. The solve is stopped prematurely 333 if interrupt is non-null at set to true during (or before) solving. 334 Interruption is only supported if SolverTypeSupportsInterruption() returns 335 true for the requested solver. Passing a non-null interruption with any 336 other solver type immediately returns an MPSOLVER_INCOMPATIBLE_OPTIONS 337 error. 338 339 Note(user): This attempts to first use `DirectlySolveProto()` (if 340 implemented). Consequently, this most likely does *not* override any of 341 the default parameters of the underlying solver. This behavior *differs* 342 from `MPSolver::Solve()` which by default sets the feasibility tolerance 343 and the gap limit (as of 2020/02/11, to 1e-7 and 0.0001, respectively). 344 """ 345 return _pywraplp.Solver_SolveWithProto(model_request, response, interrupt) 346 347 def ExportModelToProto(self, output_model): 348 r""" Exports model to protocol buffer.""" 349 return _pywraplp.Solver_ExportModelToProto(self, output_model) 350 351 def SetSolverSpecificParametersAsString(self, parameters): 352 r""" 353 Advanced usage: pass solver specific parameters in text format. 354 355 The format is solver-specific and is the same as the corresponding solver 356 configuration file format. Returns true if the operation was successful. 357 """ 358 return _pywraplp.Solver_SetSolverSpecificParametersAsString(self, parameters) 359 FREE = _pywraplp.Solver_FREE 360 AT_LOWER_BOUND = _pywraplp.Solver_AT_LOWER_BOUND 361 AT_UPPER_BOUND = _pywraplp.Solver_AT_UPPER_BOUND 362 FIXED_VALUE = _pywraplp.Solver_FIXED_VALUE 363 BASIC = _pywraplp.Solver_BASIC 364 365 @staticmethod 366 def infinity(): 367 r""" 368 Infinity. 369 370 You can use -MPSolver::infinity() for negative infinity. 371 """ 372 return _pywraplp.Solver_infinity() 373 374 def EnableOutput(self): 375 r""" Enables solver logging.""" 376 return _pywraplp.Solver_EnableOutput(self) 377 378 def SuppressOutput(self): 379 r""" Suppresses solver logging.""" 380 return _pywraplp.Solver_SuppressOutput(self) 381 382 def iterations(self): 383 r""" Returns the number of simplex iterations.""" 384 return _pywraplp.Solver_iterations(self) 385 386 def nodes(self): 387 r""" 388 Returns the number of branch-and-bound nodes evaluated during the solve. 389 390 Only available for discrete problems. 391 """ 392 return _pywraplp.Solver_nodes(self) 393 394 def SolverVersion(self): 395 r""" Returns a string describing the underlying solver and its version.""" 396 return _pywraplp.Solver_SolverVersion(self) 397 398 def ComputeExactConditionNumber(self): 399 r""" 400 Advanced usage: computes the exact condition number of the current scaled 401 basis: L1norm(B) * L1norm(inverse(B)), where B is the scaled basis. 402 403 This method requires that a basis exists: it should be called after Solve. 404 It is only available for continuous problems. It is implemented for GLPK 405 but not CLP because CLP does not provide the API for doing it. 406 407 The condition number measures how well the constraint matrix is conditioned 408 and can be used to predict whether numerical issues will arise during the 409 solve: the model is declared infeasible whereas it is feasible (or 410 vice-versa), the solution obtained is not optimal or violates some 411 constraints, the resolution is slow because of repeated singularities. 412 413 The rule of thumb to interpret the condition number kappa is: 414 - o kappa <= 1e7: virtually no chance of numerical issues 415 - o 1e7 < kappa <= 1e10: small chance of numerical issues 416 - o 1e10 < kappa <= 1e13: medium chance of numerical issues 417 - o kappa > 1e13: high chance of numerical issues 418 419 The computation of the condition number depends on the quality of the LU 420 decomposition, so it is not very accurate when the matrix is ill 421 conditioned. 422 """ 423 return _pywraplp.Solver_ComputeExactConditionNumber(self) 424 425 def NextSolution(self): 426 r""" 427 Some solvers (MIP only, not LP) can produce multiple solutions to the 428 problem. Returns true when another solution is available, and updates the 429 MPVariable* objects to make the new solution queryable. Call only after 430 calling solve. 431 432 The optimality properties of the additional solutions found, and whether or 433 not the solver computes them ahead of time or when NextSolution() is called 434 is solver specific. 435 436 As of 2020-02-10, only Gurobi and SCIP support NextSolution(), see 437 linear_solver_interfaces_test for an example of how to configure these 438 solvers for multiple solutions. Other solvers return false unconditionally. 439 """ 440 return _pywraplp.Solver_NextSolution(self) 441 442 def set_time_limit(self, time_limit_milliseconds): 443 return _pywraplp.Solver_set_time_limit(self, time_limit_milliseconds) 444 445 def wall_time(self): 446 return _pywraplp.Solver_wall_time(self) 447 448 def LoadModelFromProto(self, input_model): 449 return _pywraplp.Solver_LoadModelFromProto(self, input_model) 450 451 def LoadModelFromProtoKeepNames(self, input_model): 452 return _pywraplp.Solver_LoadModelFromProtoKeepNames(self, input_model) 453 454 def LoadModelFromProtoWithUniqueNamesOrDie(self, input_model): 455 return _pywraplp.Solver_LoadModelFromProtoWithUniqueNamesOrDie(self, input_model) 456 457 def LoadSolutionFromProto(self, *args): 458 return _pywraplp.Solver_LoadSolutionFromProto(self, *args) 459 460 def ExportModelAsLpFormat(self, obfuscated): 461 return _pywraplp.Solver_ExportModelAsLpFormat(self, obfuscated) 462 463 def ExportModelAsMpsFormat(self, fixed_format, obfuscated): 464 return _pywraplp.Solver_ExportModelAsMpsFormat(self, fixed_format, obfuscated) 465 466 def SetHint(self, variables, values): 467 r""" 468 Set a hint for solution. 469 470 If a feasible or almost-feasible solution to the problem is already known, 471 it may be helpful to pass it to the solver so that it can be used. A 472 solver that supports this feature will try to use this information to 473 create its initial feasible solution. 474 475 Note that it may not always be faster to give a hint like this to the 476 solver. There is also no guarantee that the solver will use this hint or 477 try to return a solution "close" to this assignment in case of multiple 478 optimal solutions. 479 """ 480 return _pywraplp.Solver_SetHint(self, variables, values) 481 482 def SetNumThreads(self, num_theads): 483 r""" Sets the number of threads to be used by the solver.""" 484 return _pywraplp.Solver_SetNumThreads(self, num_theads) 485 486 def Add(self, constraint, name=''): 487 if isinstance(constraint, bool): 488 if constraint: 489 return self.RowConstraint(0, 0, name) 490 else: 491 return self.RowConstraint(1, 1, name) 492 else: 493 return constraint.Extract(self, name) 494 495 def Sum(self, expr_array): 496 result = SumArray(expr_array) 497 return result 498 499 def RowConstraint(self, *args): 500 return self.Constraint(*args) 501 502 def Minimize(self, expr): 503 objective = self.Objective() 504 objective.Clear() 505 objective.SetMinimization() 506 if isinstance(expr, numbers.Number): 507 objective.SetOffset(expr) 508 else: 509 coeffs = expr.GetCoeffs() 510 objective.SetOffset(coeffs.pop(OFFSET_KEY, 0.0)) 511 for v, c, in list(coeffs.items()): 512 objective.SetCoefficient(v, float(c)) 513 514 def Maximize(self, expr): 515 objective = self.Objective() 516 objective.Clear() 517 objective.SetMaximization() 518 if isinstance(expr, numbers.Number): 519 objective.SetOffset(expr) 520 else: 521 coeffs = expr.GetCoeffs() 522 objective.SetOffset(coeffs.pop(OFFSET_KEY, 0.0)) 523 for v, c, in list(coeffs.items()): 524 objective.SetCoefficient(v, float(c)) 525 526 527 @staticmethod 528 def Infinity(): 529 return _pywraplp.Solver_Infinity() 530 531 def SetTimeLimit(self, x): 532 return _pywraplp.Solver_SetTimeLimit(self, x) 533 534 def WallTime(self): 535 return _pywraplp.Solver_WallTime(self) 536 537 def Iterations(self): 538 return _pywraplp.Solver_Iterations(self)
This mathematical programming (MP) solver class is the main class though which users build and solve problems.
98 def __init__(self, name, problem_type): 99 r""" Create a solver with the given name and underlying solver backend.""" 100 _pywraplp.Solver_swiginit(self, _pywraplp.new_Solver(name, problem_type))
Create a solver with the given name and underlying solver backend.
103 @staticmethod 104 def CreateSolver(solver_id): 105 r""" 106 Recommended factory method to create a MPSolver instance, especially in 107 non C++ languages. 108 109 It returns a newly created solver instance if successful, or a nullptr 110 otherwise. This can occur if the relevant interface is not linked in, or if 111 a needed license is not accessible for commercial solvers. 112 113 Ownership of the solver is passed on to the caller of this method. 114 It will accept both string names of the OptimizationProblemType enum, as 115 well as a short version (i.e. "SCIP_MIXED_INTEGER_PROGRAMMING" or "SCIP"). 116 117 solver_id is case insensitive, and the following names are supported: 118 - CLP_LINEAR_PROGRAMMING or CLP 119 - CBC_MIXED_INTEGER_PROGRAMMING or CBC 120 - GLOP_LINEAR_PROGRAMMING or GLOP 121 - BOP_INTEGER_PROGRAMMING or BOP 122 - SAT_INTEGER_PROGRAMMING or SAT or CP_SAT 123 - SCIP_MIXED_INTEGER_PROGRAMMING or SCIP 124 - GUROBI_LINEAR_PROGRAMMING or GUROBI_LP 125 - GUROBI_MIXED_INTEGER_PROGRAMMING or GUROBI or GUROBI_MIP 126 - CPLEX_LINEAR_PROGRAMMING or CPLEX_LP 127 - CPLEX_MIXED_INTEGER_PROGRAMMING or CPLEX or CPLEX_MIP 128 - XPRESS_LINEAR_PROGRAMMING or XPRESS_LP 129 - XPRESS_MIXED_INTEGER_PROGRAMMING or XPRESS or XPRESS_MIP 130 - GLPK_LINEAR_PROGRAMMING or GLPK_LP 131 - GLPK_MIXED_INTEGER_PROGRAMMING or GLPK or GLPK_MIP 132 """ 133 return _pywraplp.Solver_CreateSolver(solver_id)
Recommended factory method to create a MPSolver instance, especially in non C++ languages.
It returns a newly created solver instance if successful, or a nullptr otherwise. This can occur if the relevant interface is not linked in, or if a needed license is not accessible for commercial solvers.
Ownership of the solver is passed on to the caller of this method. It will accept both string names of the OptimizationProblemType enum, as well as a short version (i.e. "SCIP_MIXED_INTEGER_PROGRAMMING" or "SCIP").
solver_id is case insensitive, and the following names are supported:
- CLP_LINEAR_PROGRAMMING or CLP
- CBC_MIXED_INTEGER_PROGRAMMING or CBC
- GLOP_LINEAR_PROGRAMMING or GLOP
- BOP_INTEGER_PROGRAMMING or BOP
- SAT_INTEGER_PROGRAMMING or SAT or CP_SAT
- SCIP_MIXED_INTEGER_PROGRAMMING or SCIP
- GUROBI_LINEAR_PROGRAMMING or GUROBI_LP
- GUROBI_MIXED_INTEGER_PROGRAMMING or GUROBI or GUROBI_MIP
- CPLEX_LINEAR_PROGRAMMING or CPLEX_LP
- CPLEX_MIXED_INTEGER_PROGRAMMING or CPLEX or CPLEX_MIP
- XPRESS_LINEAR_PROGRAMMING or XPRESS_LP
- XPRESS_MIXED_INTEGER_PROGRAMMING or XPRESS or XPRESS_MIP
- GLPK_LINEAR_PROGRAMMING or GLPK_LP
- GLPK_MIXED_INTEGER_PROGRAMMING or GLPK or GLPK_MIP
135 @staticmethod 136 def SupportsProblemType(problem_type): 137 r""" 138 Whether the given problem type is supported (this will depend on the 139 targets that you linked). 140 """ 141 return _pywraplp.Solver_SupportsProblemType(problem_type)
Whether the given problem type is supported (this will depend on the targets that you linked).
143 def Clear(self): 144 r""" 145 Clears the objective (including the optimization direction), all variables 146 and constraints. All the other properties of the MPSolver (like the time 147 limit) are kept untouched. 148 """ 149 return _pywraplp.Solver_Clear(self)
Clears the objective (including the optimization direction), all variables and constraints. All the other properties of the MPSolver (like the time limit) are kept untouched.
151 def NumVariables(self): 152 r""" Returns the number of variables.""" 153 return _pywraplp.Solver_NumVariables(self)
Returns the number of variables.
155 def variables(self): 156 r""" 157 Returns the array of variables handled by the MPSolver. (They are listed in 158 the order in which they were created.) 159 """ 160 return _pywraplp.Solver_variables(self)
Returns the array of variables handled by the MPSolver. (They are listed in the order in which they were created.)
162 def variable(self, index): 163 r"""Returns the variable at position index.""" 164 return _pywraplp.Solver_variable(self, index)
Returns the variable at position index.
166 def LookupVariable(self, var_name): 167 r""" 168 Looks up a variable by name, and returns nullptr if it does not exist. The 169 first call has a O(n) complexity, as the variable name index is lazily 170 created upon first use. Will crash if variable names are not unique. 171 """ 172 return _pywraplp.Solver_LookupVariable(self, var_name)
Looks up a variable by name, and returns nullptr if it does not exist. The first call has a O(n) complexity, as the variable name index is lazily created upon first use. Will crash if variable names are not unique.
174 def Var(self, lb, ub, integer, name): 175 r""" 176 Creates a variable with the given bounds, integrality requirement and 177 name. Bounds can be finite or +/- MPSolver::infinity(). The MPSolver owns 178 the variable (i.e. the returned pointer is borrowed). Variable names are 179 optional. If you give an empty name, name() will auto-generate one for you 180 upon request. 181 """ 182 return _pywraplp.Solver_Var(self, lb, ub, integer, name)
Creates a variable with the given bounds, integrality requirement and name. Bounds can be finite or +/- MPSolver::infinity(). The MPSolver owns the variable (i.e. the returned pointer is borrowed). Variable names are optional. If you give an empty name, name() will auto-generate one for you upon request.
184 def NumVar(self, lb, ub, name): 185 r""" Creates a continuous variable.""" 186 return _pywraplp.Solver_NumVar(self, lb, ub, name)
Creates a continuous variable.
188 def IntVar(self, lb, ub, name): 189 r""" Creates an integer variable.""" 190 return _pywraplp.Solver_IntVar(self, lb, ub, name)
Creates an integer variable.
192 def BoolVar(self, name): 193 r""" Creates a boolean variable.""" 194 return _pywraplp.Solver_BoolVar(self, name)
Creates a boolean variable.
196 def NumConstraints(self): 197 r""" Returns the number of constraints.""" 198 return _pywraplp.Solver_NumConstraints(self)
Returns the number of constraints.
200 def constraints(self): 201 r""" 202 Returns the array of constraints handled by the MPSolver. 203 204 They are listed in the order in which they were created. 205 """ 206 return _pywraplp.Solver_constraints(self)
Returns the array of constraints handled by the MPSolver.
They are listed in the order in which they were created.
208 def constraint(self, index): 209 r""" Returns the constraint at the given index.""" 210 return _pywraplp.Solver_constraint(self, index)
Returns the constraint at the given index.
212 def LookupConstraint(self, constraint_name): 213 r""" 214 Looks up a constraint by name, and returns nullptr if it does not exist. 215 216 The first call has a O(n) complexity, as the constraint name index is 217 lazily created upon first use. Will crash if constraint names are not 218 unique. 219 """ 220 return _pywraplp.Solver_LookupConstraint(self, constraint_name)
Looks up a constraint by name, and returns nullptr if it does not exist.
The first call has a O(n) complexity, as the constraint name index is lazily created upon first use. Will crash if constraint names are not unique.
222 def Constraint(self, *args): 223 r""" 224 *Overload 1:* 225 226 Creates a linear constraint with given bounds. 227 228 Bounds can be finite or +/- MPSolver::infinity(). The MPSolver class 229 assumes ownership of the constraint. 230 231 :rtype: :py:class:`MPConstraint` 232 :return: a pointer to the newly created constraint. 233 234 | 235 236 *Overload 2:* 237 Creates a constraint with -infinity and +infinity bounds. 238 239 | 240 241 *Overload 3:* 242 Creates a named constraint with given bounds. 243 244 | 245 246 *Overload 4:* 247 Creates a named constraint with -infinity and +infinity bounds. 248 """ 249 return _pywraplp.Solver_Constraint(self, *args)
Overload 1:
Creates a linear constraint with given bounds.
Bounds can be finite or +/- MPSolver::infinity(). The MPSolver class assumes ownership of the constraint.
Returns
a pointer to the newly created constraint.
|
Overload 2: Creates a constraint with -infinity and +infinity bounds.
|
Overload 3: Creates a named constraint with given bounds.
|
Overload 4: Creates a named constraint with -infinity and +infinity bounds.
251 def Objective(self): 252 r""" Returns the mutable objective object.""" 253 return _pywraplp.Solver_Objective(self)
Returns the mutable objective object.
269 def Solve(self, *args): 270 r""" 271 *Overload 1:* 272 Solves the problem using the default parameter values. 273 274 | 275 276 *Overload 2:* 277 Solves the problem using the specified parameter values. 278 """ 279 return _pywraplp.Solver_Solve(self, *args)
Overload 1: Solves the problem using the default parameter values.
|
Overload 2: Solves the problem using the specified parameter values.
281 def ComputeConstraintActivities(self): 282 r""" 283 Advanced usage: compute the "activities" of all constraints, which are the 284 sums of their linear terms. The activities are returned in the same order 285 as constraints(), which is the order in which constraints were added; but 286 you can also use MPConstraint::index() to get a constraint's index. 287 """ 288 return _pywraplp.Solver_ComputeConstraintActivities(self)
Advanced usage: compute the "activities" of all constraints, which are the sums of their linear terms. The activities are returned in the same order as constraints(), which is the order in which constraints were added; but you can also use MPConstraint::index() to get a constraint's index.
290 def VerifySolution(self, tolerance, log_errors): 291 r""" 292 Advanced usage: Verifies the *correctness* of the solution. 293 294 It verifies that all variables must be within their domains, all 295 constraints must be satisfied, and the reported objective value must be 296 accurate. 297 298 Usage: 299 - This can only be called after Solve() was called. 300 - "tolerance" is interpreted as an absolute error threshold. 301 - For the objective value only, if the absolute error is too large, 302 the tolerance is interpreted as a relative error threshold instead. 303 - If "log_errors" is true, every single violation will be logged. 304 - If "tolerance" is negative, it will be set to infinity(). 305 306 Most users should just set the --verify_solution flag and not bother using 307 this method directly. 308 """ 309 return _pywraplp.Solver_VerifySolution(self, tolerance, log_errors)
Advanced usage: Verifies the correctness of the solution.
It verifies that all variables must be within their domains, all constraints must be satisfied, and the reported objective value must be accurate.
Usage:
- This can only be called after Solve() was called.
- "tolerance" is interpreted as an absolute error threshold.
- For the objective value only, if the absolute error is too large, the tolerance is interpreted as a relative error threshold instead.
- If "log_errors" is true, every single violation will be logged.
- If "tolerance" is negative, it will be set to infinity().
Most users should just set the --verify_solution flag and not bother using this method directly.
311 def InterruptSolve(self): 312 r""" 313 Interrupts the Solve() execution to terminate processing if possible. 314 315 If the underlying interface supports interruption; it does that and returns 316 true regardless of whether there's an ongoing Solve() or not. The Solve() 317 call may still linger for a while depending on the conditions. If 318 interruption is not supported; returns false and does nothing. 319 MPSolver::SolverTypeSupportsInterruption can be used to check if 320 interruption is supported for a given solver type. 321 """ 322 return _pywraplp.Solver_InterruptSolve(self)
Interrupts the Solve() execution to terminate processing if possible.
If the underlying interface supports interruption; it does that and returns true regardless of whether there's an ongoing Solve() or not. The Solve() call may still linger for a while depending on the conditions. If interruption is not supported; returns false and does nothing. MPSolver::SolverTypeSupportsInterruption can be used to check if interruption is supported for a given solver type.
324 def FillSolutionResponseProto(self, response): 325 r""" Encodes the current solution in a solution response protocol buffer.""" 326 return _pywraplp.Solver_FillSolutionResponseProto(self, response)
Encodes the current solution in a solution response protocol buffer.
328 @staticmethod 329 def SolveWithProto(model_request, response, interrupt=None): 330 r""" 331 Solves the model encoded by a MPModelRequest protocol buffer and fills the 332 solution encoded as a MPSolutionResponse. The solve is stopped prematurely 333 if interrupt is non-null at set to true during (or before) solving. 334 Interruption is only supported if SolverTypeSupportsInterruption() returns 335 true for the requested solver. Passing a non-null interruption with any 336 other solver type immediately returns an MPSOLVER_INCOMPATIBLE_OPTIONS 337 error. 338 339 Note(user): This attempts to first use `DirectlySolveProto()` (if 340 implemented). Consequently, this most likely does *not* override any of 341 the default parameters of the underlying solver. This behavior *differs* 342 from `MPSolver::Solve()` which by default sets the feasibility tolerance 343 and the gap limit (as of 2020/02/11, to 1e-7 and 0.0001, respectively). 344 """ 345 return _pywraplp.Solver_SolveWithProto(model_request, response, interrupt)
Solves the model encoded by a MPModelRequest protocol buffer and fills the solution encoded as a MPSolutionResponse. The solve is stopped prematurely if interrupt is non-null at set to true during (or before) solving. Interruption is only supported if SolverTypeSupportsInterruption() returns true for the requested solver. Passing a non-null interruption with any other solver type immediately returns an MPSOLVER_INCOMPATIBLE_OPTIONS error.
Note(user): This attempts to first use DirectlySolveProto()
(if
implemented). Consequently, this most likely does not override any of
the default parameters of the underlying solver. This behavior differs
from MPSolver::Solve()
which by default sets the feasibility tolerance
and the gap limit (as of 2020/02/11, to 1e-7 and 0.0001, respectively).
347 def ExportModelToProto(self, output_model): 348 r""" Exports model to protocol buffer.""" 349 return _pywraplp.Solver_ExportModelToProto(self, output_model)
Exports model to protocol buffer.
351 def SetSolverSpecificParametersAsString(self, parameters): 352 r""" 353 Advanced usage: pass solver specific parameters in text format. 354 355 The format is solver-specific and is the same as the corresponding solver 356 configuration file format. Returns true if the operation was successful. 357 """ 358 return _pywraplp.Solver_SetSolverSpecificParametersAsString(self, parameters)
Advanced usage: pass solver specific parameters in text format.
The format is solver-specific and is the same as the corresponding solver configuration file format. Returns true if the operation was successful.
365 @staticmethod 366 def infinity(): 367 r""" 368 Infinity. 369 370 You can use -MPSolver::infinity() for negative infinity. 371 """ 372 return _pywraplp.Solver_infinity()
Infinity.
You can use -MPSolver::infinity() for negative infinity.
374 def EnableOutput(self): 375 r""" Enables solver logging.""" 376 return _pywraplp.Solver_EnableOutput(self)
Enables solver logging.
378 def SuppressOutput(self): 379 r""" Suppresses solver logging.""" 380 return _pywraplp.Solver_SuppressOutput(self)
Suppresses solver logging.
382 def iterations(self): 383 r""" Returns the number of simplex iterations.""" 384 return _pywraplp.Solver_iterations(self)
Returns the number of simplex iterations.
386 def nodes(self): 387 r""" 388 Returns the number of branch-and-bound nodes evaluated during the solve. 389 390 Only available for discrete problems. 391 """ 392 return _pywraplp.Solver_nodes(self)
Returns the number of branch-and-bound nodes evaluated during the solve.
Only available for discrete problems.
394 def SolverVersion(self): 395 r""" Returns a string describing the underlying solver and its version.""" 396 return _pywraplp.Solver_SolverVersion(self)
Returns a string describing the underlying solver and its version.
398 def ComputeExactConditionNumber(self): 399 r""" 400 Advanced usage: computes the exact condition number of the current scaled 401 basis: L1norm(B) * L1norm(inverse(B)), where B is the scaled basis. 402 403 This method requires that a basis exists: it should be called after Solve. 404 It is only available for continuous problems. It is implemented for GLPK 405 but not CLP because CLP does not provide the API for doing it. 406 407 The condition number measures how well the constraint matrix is conditioned 408 and can be used to predict whether numerical issues will arise during the 409 solve: the model is declared infeasible whereas it is feasible (or 410 vice-versa), the solution obtained is not optimal or violates some 411 constraints, the resolution is slow because of repeated singularities. 412 413 The rule of thumb to interpret the condition number kappa is: 414 - o kappa <= 1e7: virtually no chance of numerical issues 415 - o 1e7 < kappa <= 1e10: small chance of numerical issues 416 - o 1e10 < kappa <= 1e13: medium chance of numerical issues 417 - o kappa > 1e13: high chance of numerical issues 418 419 The computation of the condition number depends on the quality of the LU 420 decomposition, so it is not very accurate when the matrix is ill 421 conditioned. 422 """ 423 return _pywraplp.Solver_ComputeExactConditionNumber(self)
Advanced usage: computes the exact condition number of the current scaled basis: L1norm(B) * L1norm(inverse(B)), where B is the scaled basis.
This method requires that a basis exists: it should be called after Solve. It is only available for continuous problems. It is implemented for GLPK but not CLP because CLP does not provide the API for doing it.
The condition number measures how well the constraint matrix is conditioned and can be used to predict whether numerical issues will arise during the solve: the model is declared infeasible whereas it is feasible (or vice-versa), the solution obtained is not optimal or violates some constraints, the resolution is slow because of repeated singularities.
The rule of thumb to interpret the condition number kappa is:
- o kappa <= 1e7: virtually no chance of numerical issues
- o 1e7 < kappa <= 1e10: small chance of numerical issues
- o 1e10 < kappa <= 1e13: medium chance of numerical issues
- o kappa > 1e13: high chance of numerical issues
The computation of the condition number depends on the quality of the LU decomposition, so it is not very accurate when the matrix is ill conditioned.
425 def NextSolution(self): 426 r""" 427 Some solvers (MIP only, not LP) can produce multiple solutions to the 428 problem. Returns true when another solution is available, and updates the 429 MPVariable* objects to make the new solution queryable. Call only after 430 calling solve. 431 432 The optimality properties of the additional solutions found, and whether or 433 not the solver computes them ahead of time or when NextSolution() is called 434 is solver specific. 435 436 As of 2020-02-10, only Gurobi and SCIP support NextSolution(), see 437 linear_solver_interfaces_test for an example of how to configure these 438 solvers for multiple solutions. Other solvers return false unconditionally. 439 """ 440 return _pywraplp.Solver_NextSolution(self)
Some solvers (MIP only, not LP) can produce multiple solutions to the problem. Returns true when another solution is available, and updates the MPVariable* objects to make the new solution queryable. Call only after calling solve.
The optimality properties of the additional solutions found, and whether or not the solver computes them ahead of time or when NextSolution() is called is solver specific.
As of 2020-02-10, only Gurobi and SCIP support NextSolution(), see linear_solver_interfaces_test for an example of how to configure these solvers for multiple solutions. Other solvers return false unconditionally.
466 def SetHint(self, variables, values): 467 r""" 468 Set a hint for solution. 469 470 If a feasible or almost-feasible solution to the problem is already known, 471 it may be helpful to pass it to the solver so that it can be used. A 472 solver that supports this feature will try to use this information to 473 create its initial feasible solution. 474 475 Note that it may not always be faster to give a hint like this to the 476 solver. There is also no guarantee that the solver will use this hint or 477 try to return a solution "close" to this assignment in case of multiple 478 optimal solutions. 479 """ 480 return _pywraplp.Solver_SetHint(self, variables, values)
Set a hint for solution.
If a feasible or almost-feasible solution to the problem is already known, it may be helpful to pass it to the solver so that it can be used. A solver that supports this feature will try to use this information to create its initial feasible solution.
Note that it may not always be faster to give a hint like this to the solver. There is also no guarantee that the solver will use this hint or try to return a solution "close" to this assignment in case of multiple optimal solutions.
482 def SetNumThreads(self, num_theads): 483 r""" Sets the number of threads to be used by the solver.""" 484 return _pywraplp.Solver_SetNumThreads(self, num_theads)
Sets the number of threads to be used by the solver.
502 def Minimize(self, expr): 503 objective = self.Objective() 504 objective.Clear() 505 objective.SetMinimization() 506 if isinstance(expr, numbers.Number): 507 objective.SetOffset(expr) 508 else: 509 coeffs = expr.GetCoeffs() 510 objective.SetOffset(coeffs.pop(OFFSET_KEY, 0.0)) 511 for v, c, in list(coeffs.items()): 512 objective.SetCoefficient(v, float(c))
514 def Maximize(self, expr): 515 objective = self.Objective() 516 objective.Clear() 517 objective.SetMaximization() 518 if isinstance(expr, numbers.Number): 519 objective.SetOffset(expr) 520 else: 521 coeffs = expr.GetCoeffs() 522 objective.SetOffset(coeffs.pop(OFFSET_KEY, 0.0)) 523 for v, c, in list(coeffs.items()): 524 objective.SetCoefficient(v, float(c))
545class Objective(object): 546 r""" A class to express a linear objective.""" 547 548 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 549 550 def __init__(self, *args, **kwargs): 551 raise AttributeError("No constructor defined") 552 __repr__ = _swig_repr 553 554 def Clear(self): 555 r""" 556 Clears the offset, all variables and coefficients, and the optimization 557 direction. 558 """ 559 return _pywraplp.Objective_Clear(self) 560 561 def SetCoefficient(self, var, coeff): 562 r""" 563 Sets the coefficient of the variable in the objective. 564 565 If the variable does not belong to the solver, the function just returns, 566 or crashes in non-opt mode. 567 """ 568 return _pywraplp.Objective_SetCoefficient(self, var, coeff) 569 570 def GetCoefficient(self, var): 571 r""" 572 Gets the coefficient of a given variable in the objective 573 574 It returns 0 if the variable does not appear in the objective). 575 """ 576 return _pywraplp.Objective_GetCoefficient(self, var) 577 578 def SetOffset(self, value): 579 r""" Sets the constant term in the objective.""" 580 return _pywraplp.Objective_SetOffset(self, value) 581 582 def offset(self): 583 r""" Gets the constant term in the objective.""" 584 return _pywraplp.Objective_offset(self) 585 586 def SetOptimizationDirection(self, maximize): 587 r""" Sets the optimization direction (maximize: true or minimize: false).""" 588 return _pywraplp.Objective_SetOptimizationDirection(self, maximize) 589 590 def SetMinimization(self): 591 r""" Sets the optimization direction to minimize.""" 592 return _pywraplp.Objective_SetMinimization(self) 593 594 def SetMaximization(self): 595 r""" Sets the optimization direction to maximize.""" 596 return _pywraplp.Objective_SetMaximization(self) 597 598 def maximization(self): 599 r""" Is the optimization direction set to maximize?""" 600 return _pywraplp.Objective_maximization(self) 601 602 def minimization(self): 603 r""" Is the optimization direction set to minimize?""" 604 return _pywraplp.Objective_minimization(self) 605 606 def Value(self): 607 r""" 608 Returns the objective value of the best solution found so far. 609 610 It is the optimal objective value if the problem has been solved to 611 optimality. 612 613 Note: the objective value may be slightly different than what you could 614 compute yourself using ``MPVariable::solution_value();`` please use the 615 --verify_solution flag to gain confidence about the numerical stability of 616 your solution. 617 """ 618 return _pywraplp.Objective_Value(self) 619 620 def BestBound(self): 621 r""" 622 Returns the best objective bound. 623 624 In case of minimization, it is a lower bound on the objective value of the 625 optimal integer solution. Only available for discrete problems. 626 """ 627 return _pywraplp.Objective_BestBound(self) 628 629 def Offset(self): 630 return _pywraplp.Objective_Offset(self) 631 __swig_destroy__ = _pywraplp.delete_Objective
A class to express a linear objective.
554 def Clear(self): 555 r""" 556 Clears the offset, all variables and coefficients, and the optimization 557 direction. 558 """ 559 return _pywraplp.Objective_Clear(self)
Clears the offset, all variables and coefficients, and the optimization direction.
561 def SetCoefficient(self, var, coeff): 562 r""" 563 Sets the coefficient of the variable in the objective. 564 565 If the variable does not belong to the solver, the function just returns, 566 or crashes in non-opt mode. 567 """ 568 return _pywraplp.Objective_SetCoefficient(self, var, coeff)
Sets the coefficient of the variable in the objective.
If the variable does not belong to the solver, the function just returns, or crashes in non-opt mode.
570 def GetCoefficient(self, var): 571 r""" 572 Gets the coefficient of a given variable in the objective 573 574 It returns 0 if the variable does not appear in the objective). 575 """ 576 return _pywraplp.Objective_GetCoefficient(self, var)
Gets the coefficient of a given variable in the objective
It returns 0 if the variable does not appear in the objective).
578 def SetOffset(self, value): 579 r""" Sets the constant term in the objective.""" 580 return _pywraplp.Objective_SetOffset(self, value)
Sets the constant term in the objective.
582 def offset(self): 583 r""" Gets the constant term in the objective.""" 584 return _pywraplp.Objective_offset(self)
Gets the constant term in the objective.
586 def SetOptimizationDirection(self, maximize): 587 r""" Sets the optimization direction (maximize: true or minimize: false).""" 588 return _pywraplp.Objective_SetOptimizationDirection(self, maximize)
Sets the optimization direction (maximize: true or minimize: false).
590 def SetMinimization(self): 591 r""" Sets the optimization direction to minimize.""" 592 return _pywraplp.Objective_SetMinimization(self)
Sets the optimization direction to minimize.
594 def SetMaximization(self): 595 r""" Sets the optimization direction to maximize.""" 596 return _pywraplp.Objective_SetMaximization(self)
Sets the optimization direction to maximize.
598 def maximization(self): 599 r""" Is the optimization direction set to maximize?""" 600 return _pywraplp.Objective_maximization(self)
Is the optimization direction set to maximize?
602 def minimization(self): 603 r""" Is the optimization direction set to minimize?""" 604 return _pywraplp.Objective_minimization(self)
Is the optimization direction set to minimize?
606 def Value(self): 607 r""" 608 Returns the objective value of the best solution found so far. 609 610 It is the optimal objective value if the problem has been solved to 611 optimality. 612 613 Note: the objective value may be slightly different than what you could 614 compute yourself using ``MPVariable::solution_value();`` please use the 615 --verify_solution flag to gain confidence about the numerical stability of 616 your solution. 617 """ 618 return _pywraplp.Objective_Value(self)
Returns the objective value of the best solution found so far.
It is the optimal objective value if the problem has been solved to optimality.
Note: the objective value may be slightly different than what you could
compute yourself using MPVariable::solution_value();
please use the
--verify_solution flag to gain confidence about the numerical stability of
your solution.
620 def BestBound(self): 621 r""" 622 Returns the best objective bound. 623 624 In case of minimization, it is a lower bound on the objective value of the 625 optimal integer solution. Only available for discrete problems. 626 """ 627 return _pywraplp.Objective_BestBound(self)
Returns the best objective bound.
In case of minimization, it is a lower bound on the objective value of the optimal integer solution. Only available for discrete problems.
635class Variable(object): 636 r""" The class for variables of a Mathematical Programming (MP) model.""" 637 638 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 639 640 def __init__(self, *args, **kwargs): 641 raise AttributeError("No constructor defined") 642 643 def name(self): 644 r""" Returns the name of the variable.""" 645 return _pywraplp.Variable_name(self) 646 647 def SetInteger(self, integer): 648 r""" Sets the integrality requirement of the variable.""" 649 return _pywraplp.Variable_SetInteger(self, integer) 650 651 def integer(self): 652 r""" Returns the integrality requirement of the variable.""" 653 return _pywraplp.Variable_integer(self) 654 655 def solution_value(self): 656 r""" 657 Returns the value of the variable in the current solution. 658 659 If the variable is integer, then the value will always be an integer (the 660 underlying solver handles floating-point values only, but this function 661 automatically rounds it to the nearest integer; see: man 3 round). 662 """ 663 return _pywraplp.Variable_solution_value(self) 664 665 def index(self): 666 r""" Returns the index of the variable in the MPSolver::variables_.""" 667 return _pywraplp.Variable_index(self) 668 669 def lb(self): 670 r""" Returns the lower bound.""" 671 return _pywraplp.Variable_lb(self) 672 673 def ub(self): 674 r""" Returns the upper bound.""" 675 return _pywraplp.Variable_ub(self) 676 677 def SetBounds(self, lb, ub): 678 r""" Sets both the lower and upper bounds.""" 679 return _pywraplp.Variable_SetBounds(self, lb, ub) 680 681 def reduced_cost(self): 682 r""" 683 Advanced usage: returns the reduced cost of the variable in the current 684 solution (only available for continuous problems). 685 """ 686 return _pywraplp.Variable_reduced_cost(self) 687 688 def basis_status(self): 689 r""" 690 Advanced usage: returns the basis status of the variable in the current 691 solution (only available for continuous problems). 692 693 See also: MPSolver::BasisStatus. 694 """ 695 return _pywraplp.Variable_basis_status(self) 696 697 def branching_priority(self): 698 r""" 699 Advanced usage: Certain MIP solvers (e.g. Gurobi or SCIP) allow you to set 700 a per-variable priority for determining which variable to branch on. 701 702 A value of 0 is treated as default, and is equivalent to not setting the 703 branching priority. The solver looks first to branch on fractional 704 variables in higher priority levels. As of 2019-05, only Gurobi and SCIP 705 support setting branching priority; all other solvers will simply ignore 706 this annotation. 707 """ 708 return _pywraplp.Variable_branching_priority(self) 709 710 def SetBranchingPriority(self, priority): 711 return _pywraplp.Variable_SetBranchingPriority(self, priority) 712 713 def __str__(self): 714 return _pywraplp.Variable___str__(self) 715 716 def __repr__(self): 717 return _pywraplp.Variable___repr__(self) 718 719 def __getattr__(self, name): 720 return getattr(VariableExpr(self), name) 721 722 723 def SolutionValue(self): 724 return _pywraplp.Variable_SolutionValue(self) 725 726 def Integer(self): 727 return _pywraplp.Variable_Integer(self) 728 729 def Lb(self): 730 return _pywraplp.Variable_Lb(self) 731 732 def Ub(self): 733 return _pywraplp.Variable_Ub(self) 734 735 def SetLb(self, x): 736 return _pywraplp.Variable_SetLb(self, x) 737 738 def SetUb(self, x): 739 return _pywraplp.Variable_SetUb(self, x) 740 741 def ReducedCost(self): 742 return _pywraplp.Variable_ReducedCost(self) 743 __swig_destroy__ = _pywraplp.delete_Variable
The class for variables of a Mathematical Programming (MP) model.
643 def name(self): 644 r""" Returns the name of the variable.""" 645 return _pywraplp.Variable_name(self)
Returns the name of the variable.
647 def SetInteger(self, integer): 648 r""" Sets the integrality requirement of the variable.""" 649 return _pywraplp.Variable_SetInteger(self, integer)
Sets the integrality requirement of the variable.
651 def integer(self): 652 r""" Returns the integrality requirement of the variable.""" 653 return _pywraplp.Variable_integer(self)
Returns the integrality requirement of the variable.
655 def solution_value(self): 656 r""" 657 Returns the value of the variable in the current solution. 658 659 If the variable is integer, then the value will always be an integer (the 660 underlying solver handles floating-point values only, but this function 661 automatically rounds it to the nearest integer; see: man 3 round). 662 """ 663 return _pywraplp.Variable_solution_value(self)
Returns the value of the variable in the current solution.
If the variable is integer, then the value will always be an integer (the underlying solver handles floating-point values only, but this function automatically rounds it to the nearest integer; see: man 3 round).
665 def index(self): 666 r""" Returns the index of the variable in the MPSolver::variables_.""" 667 return _pywraplp.Variable_index(self)
Returns the index of the variable in the MPSolver::variables_.
677 def SetBounds(self, lb, ub): 678 r""" Sets both the lower and upper bounds.""" 679 return _pywraplp.Variable_SetBounds(self, lb, ub)
Sets both the lower and upper bounds.
681 def reduced_cost(self): 682 r""" 683 Advanced usage: returns the reduced cost of the variable in the current 684 solution (only available for continuous problems). 685 """ 686 return _pywraplp.Variable_reduced_cost(self)
Advanced usage: returns the reduced cost of the variable in the current solution (only available for continuous problems).
688 def basis_status(self): 689 r""" 690 Advanced usage: returns the basis status of the variable in the current 691 solution (only available for continuous problems). 692 693 See also: MPSolver::BasisStatus. 694 """ 695 return _pywraplp.Variable_basis_status(self)
Advanced usage: returns the basis status of the variable in the current solution (only available for continuous problems).
See also: MPSolver::BasisStatus.
697 def branching_priority(self): 698 r""" 699 Advanced usage: Certain MIP solvers (e.g. Gurobi or SCIP) allow you to set 700 a per-variable priority for determining which variable to branch on. 701 702 A value of 0 is treated as default, and is equivalent to not setting the 703 branching priority. The solver looks first to branch on fractional 704 variables in higher priority levels. As of 2019-05, only Gurobi and SCIP 705 support setting branching priority; all other solvers will simply ignore 706 this annotation. 707 """ 708 return _pywraplp.Variable_branching_priority(self)
Advanced usage: Certain MIP solvers (e.g. Gurobi or SCIP) allow you to set a per-variable priority for determining which variable to branch on.
A value of 0 is treated as default, and is equivalent to not setting the branching priority. The solver looks first to branch on fractional variables in higher priority levels. As of 2019-05, only Gurobi and SCIP support setting branching priority; all other solvers will simply ignore this annotation.
747class Constraint(object): 748 r""" 749 The class for constraints of a Mathematical Programming (MP) model. 750 751 A constraint is represented as a linear equation or inequality. 752 """ 753 754 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 755 756 def __init__(self, *args, **kwargs): 757 raise AttributeError("No constructor defined") 758 __repr__ = _swig_repr 759 760 def name(self): 761 r""" Returns the name of the constraint.""" 762 return _pywraplp.Constraint_name(self) 763 764 def Clear(self): 765 r""" Clears all variables and coefficients. Does not clear the bounds.""" 766 return _pywraplp.Constraint_Clear(self) 767 768 def SetCoefficient(self, var, coeff): 769 r""" 770 Sets the coefficient of the variable on the constraint. 771 772 If the variable does not belong to the solver, the function just returns, 773 or crashes in non-opt mode. 774 """ 775 return _pywraplp.Constraint_SetCoefficient(self, var, coeff) 776 777 def GetCoefficient(self, var): 778 r""" 779 Gets the coefficient of a given variable on the constraint (which is 0 if 780 the variable does not appear in the constraint). 781 """ 782 return _pywraplp.Constraint_GetCoefficient(self, var) 783 784 def lb(self): 785 r""" Returns the lower bound.""" 786 return _pywraplp.Constraint_lb(self) 787 788 def ub(self): 789 r""" Returns the upper bound.""" 790 return _pywraplp.Constraint_ub(self) 791 792 def SetBounds(self, lb, ub): 793 r""" Sets both the lower and upper bounds.""" 794 return _pywraplp.Constraint_SetBounds(self, lb, ub) 795 796 def set_is_lazy(self, laziness): 797 r""" 798 Advanced usage: sets the constraint "laziness". 799 800 **This is only supported for SCIP and has no effect on other 801 solvers.** 802 803 When **laziness** is true, the constraint is only considered by the Linear 804 Programming solver if its current solution violates the constraint. In this 805 case, the constraint is definitively added to the problem. This may be 806 useful in some MIP problems, and may have a dramatic impact on performance. 807 808 For more info see: http://tinyurl.com/lazy-constraints. 809 """ 810 return _pywraplp.Constraint_set_is_lazy(self, laziness) 811 812 def index(self): 813 r""" Returns the index of the constraint in the MPSolver::constraints_.""" 814 return _pywraplp.Constraint_index(self) 815 816 def dual_value(self): 817 r""" 818 Advanced usage: returns the dual value of the constraint in the current 819 solution (only available for continuous problems). 820 """ 821 return _pywraplp.Constraint_dual_value(self) 822 823 def basis_status(self): 824 r""" 825 Advanced usage: returns the basis status of the constraint. 826 827 It is only available for continuous problems). 828 829 Note that if a constraint "linear_expression in [lb, ub]" is transformed 830 into "linear_expression + slack = 0" with slack in [-ub, -lb], then this 831 status is the same as the status of the slack variable with AT_UPPER_BOUND 832 and AT_LOWER_BOUND swapped. 833 834 See also: MPSolver::BasisStatus. 835 """ 836 return _pywraplp.Constraint_basis_status(self) 837 838 def Lb(self): 839 return _pywraplp.Constraint_Lb(self) 840 841 def Ub(self): 842 return _pywraplp.Constraint_Ub(self) 843 844 def SetLb(self, x): 845 return _pywraplp.Constraint_SetLb(self, x) 846 847 def SetUb(self, x): 848 return _pywraplp.Constraint_SetUb(self, x) 849 850 def DualValue(self): 851 return _pywraplp.Constraint_DualValue(self) 852 __swig_destroy__ = _pywraplp.delete_Constraint
The class for constraints of a Mathematical Programming (MP) model.
A constraint is represented as a linear equation or inequality.
760 def name(self): 761 r""" Returns the name of the constraint.""" 762 return _pywraplp.Constraint_name(self)
Returns the name of the constraint.
764 def Clear(self): 765 r""" Clears all variables and coefficients. Does not clear the bounds.""" 766 return _pywraplp.Constraint_Clear(self)
Clears all variables and coefficients. Does not clear the bounds.
768 def SetCoefficient(self, var, coeff): 769 r""" 770 Sets the coefficient of the variable on the constraint. 771 772 If the variable does not belong to the solver, the function just returns, 773 or crashes in non-opt mode. 774 """ 775 return _pywraplp.Constraint_SetCoefficient(self, var, coeff)
Sets the coefficient of the variable on the constraint.
If the variable does not belong to the solver, the function just returns, or crashes in non-opt mode.
777 def GetCoefficient(self, var): 778 r""" 779 Gets the coefficient of a given variable on the constraint (which is 0 if 780 the variable does not appear in the constraint). 781 """ 782 return _pywraplp.Constraint_GetCoefficient(self, var)
Gets the coefficient of a given variable on the constraint (which is 0 if the variable does not appear in the constraint).
792 def SetBounds(self, lb, ub): 793 r""" Sets both the lower and upper bounds.""" 794 return _pywraplp.Constraint_SetBounds(self, lb, ub)
Sets both the lower and upper bounds.
796 def set_is_lazy(self, laziness): 797 r""" 798 Advanced usage: sets the constraint "laziness". 799 800 **This is only supported for SCIP and has no effect on other 801 solvers.** 802 803 When **laziness** is true, the constraint is only considered by the Linear 804 Programming solver if its current solution violates the constraint. In this 805 case, the constraint is definitively added to the problem. This may be 806 useful in some MIP problems, and may have a dramatic impact on performance. 807 808 For more info see: http://tinyurl.com/lazy-constraints. 809 """ 810 return _pywraplp.Constraint_set_is_lazy(self, laziness)
Advanced usage: sets the constraint "laziness".
This is only supported for SCIP and has no effect on other solvers.
When laziness is true, the constraint is only considered by the Linear Programming solver if its current solution violates the constraint. In this case, the constraint is definitively added to the problem. This may be useful in some MIP problems, and may have a dramatic impact on performance.
For more info see: http://tinyurl.com/lazy-constraints.
812 def index(self): 813 r""" Returns the index of the constraint in the MPSolver::constraints_.""" 814 return _pywraplp.Constraint_index(self)
Returns the index of the constraint in the MPSolver::constraints_.
816 def dual_value(self): 817 r""" 818 Advanced usage: returns the dual value of the constraint in the current 819 solution (only available for continuous problems). 820 """ 821 return _pywraplp.Constraint_dual_value(self)
Advanced usage: returns the dual value of the constraint in the current solution (only available for continuous problems).
823 def basis_status(self): 824 r""" 825 Advanced usage: returns the basis status of the constraint. 826 827 It is only available for continuous problems). 828 829 Note that if a constraint "linear_expression in [lb, ub]" is transformed 830 into "linear_expression + slack = 0" with slack in [-ub, -lb], then this 831 status is the same as the status of the slack variable with AT_UPPER_BOUND 832 and AT_LOWER_BOUND swapped. 833 834 See also: MPSolver::BasisStatus. 835 """ 836 return _pywraplp.Constraint_basis_status(self)
Advanced usage: returns the basis status of the constraint.
It is only available for continuous problems).
Note that if a constraint "linear_expression in [lb, ub]" is transformed into "linear_expression + slack = 0" with slack in [-ub, -lb], then this status is the same as the status of the slack variable with AT_UPPER_BOUND and AT_LOWER_BOUND swapped.
See also: MPSolver::BasisStatus.
856class MPSolverParameters(object): 857 r""" 858 This class stores parameter settings for LP and MIP solvers. Some parameters 859 are marked as advanced: do not change their values unless you know what you 860 are doing! 861 862 For developers: how to add a new parameter: 863 - Add the new Foo parameter in the DoubleParam or IntegerParam enum. 864 - If it is a categorical param, add a FooValues enum. 865 - Decide if the wrapper should define a default value for it: yes 866 if it controls the properties of the solution (example: 867 tolerances) or if it consistently improves performance, no 868 otherwise. If yes, define kDefaultFoo. 869 - Add a foo_value_ member and, if no default value is defined, a 870 foo_is_default_ member. 871 - Add code to handle Foo in Set...Param, Reset...Param, 872 Get...Param, Reset and the constructor. 873 - In class MPSolverInterface, add a virtual method SetFoo, add it 874 to SetCommonParameters or SetMIPParameters, and implement it for 875 each solver. Sometimes, parameters need to be implemented 876 differently, see for example the INCREMENTALITY implementation. 877 - Add a test in linear_solver_test.cc. 878 879 TODO(user): store the parameter values in a protocol buffer 880 instead. We need to figure out how to deal with the subtleties of 881 the default values. 882 """ 883 884 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 885 __repr__ = _swig_repr 886 RELATIVE_MIP_GAP = _pywraplp.MPSolverParameters_RELATIVE_MIP_GAP 887 r""" Limit for relative MIP gap.""" 888 PRIMAL_TOLERANCE = _pywraplp.MPSolverParameters_PRIMAL_TOLERANCE 889 r""" 890 Advanced usage: tolerance for primal feasibility of basic solutions. 891 892 This does not control the integer feasibility tolerance of integer 893 solutions for MIP or the tolerance used during presolve. 894 """ 895 DUAL_TOLERANCE = _pywraplp.MPSolverParameters_DUAL_TOLERANCE 896 r""" Advanced usage: tolerance for dual feasibility of basic solutions.""" 897 PRESOLVE = _pywraplp.MPSolverParameters_PRESOLVE 898 r""" Advanced usage: presolve mode.""" 899 LP_ALGORITHM = _pywraplp.MPSolverParameters_LP_ALGORITHM 900 r""" Algorithm to solve linear programs.""" 901 INCREMENTALITY = _pywraplp.MPSolverParameters_INCREMENTALITY 902 r""" Advanced usage: incrementality from one solve to the next.""" 903 SCALING = _pywraplp.MPSolverParameters_SCALING 904 r""" Advanced usage: enable or disable matrix scaling.""" 905 PRESOLVE_OFF = _pywraplp.MPSolverParameters_PRESOLVE_OFF 906 r""" Presolve is off.""" 907 PRESOLVE_ON = _pywraplp.MPSolverParameters_PRESOLVE_ON 908 r""" Presolve is on.""" 909 DUAL = _pywraplp.MPSolverParameters_DUAL 910 r""" Dual simplex.""" 911 PRIMAL = _pywraplp.MPSolverParameters_PRIMAL 912 r""" Primal simplex.""" 913 BARRIER = _pywraplp.MPSolverParameters_BARRIER 914 r""" Barrier algorithm.""" 915 INCREMENTALITY_OFF = _pywraplp.MPSolverParameters_INCREMENTALITY_OFF 916 r""" Start solve from scratch.""" 917 INCREMENTALITY_ON = _pywraplp.MPSolverParameters_INCREMENTALITY_ON 918 r""" 919 Reuse results from previous solve as much as the underlying solver 920 allows. 921 """ 922 SCALING_OFF = _pywraplp.MPSolverParameters_SCALING_OFF 923 r""" Scaling is off.""" 924 SCALING_ON = _pywraplp.MPSolverParameters_SCALING_ON 925 r""" Scaling is on.""" 926 927 def __init__(self): 928 r""" The constructor sets all parameters to their default value.""" 929 _pywraplp.MPSolverParameters_swiginit(self, _pywraplp.new_MPSolverParameters()) 930 931 def SetDoubleParam(self, param, value): 932 r""" Sets a double parameter to a specific value.""" 933 return _pywraplp.MPSolverParameters_SetDoubleParam(self, param, value) 934 935 def SetIntegerParam(self, param, value): 936 r""" Sets a integer parameter to a specific value.""" 937 return _pywraplp.MPSolverParameters_SetIntegerParam(self, param, value) 938 939 def GetDoubleParam(self, param): 940 r""" Returns the value of a double parameter.""" 941 return _pywraplp.MPSolverParameters_GetDoubleParam(self, param) 942 943 def GetIntegerParam(self, param): 944 r""" Returns the value of an integer parameter.""" 945 return _pywraplp.MPSolverParameters_GetIntegerParam(self, param) 946 __swig_destroy__ = _pywraplp.delete_MPSolverParameters
This class stores parameter settings for LP and MIP solvers. Some parameters are marked as advanced: do not change their values unless you know what you are doing!
For developers: how to add a new parameter:
- Add the new Foo parameter in the DoubleParam or IntegerParam enum.
- If it is a categorical param, add a FooValues enum.
- Decide if the wrapper should define a default value for it: yes if it controls the properties of the solution (example: tolerances) or if it consistently improves performance, no otherwise. If yes, define kDefaultFoo.
- Add a foo_value_ member and, if no default value is defined, a foo_is_default_ member.
- Add code to handle Foo in Set...Param, Reset...Param, Get...Param, Reset and the constructor.
- In class MPSolverInterface, add a virtual method SetFoo, add it to SetCommonParameters or SetMIPParameters, and implement it for each solver. Sometimes, parameters need to be implemented differently, see for example the INCREMENTALITY implementation.
- Add a test in linear_solver_test.cc.
TODO(user): store the parameter values in a protocol buffer instead. We need to figure out how to deal with the subtleties of the default values.
927 def __init__(self): 928 r""" The constructor sets all parameters to their default value.""" 929 _pywraplp.MPSolverParameters_swiginit(self, _pywraplp.new_MPSolverParameters())
The constructor sets all parameters to their default value.
Advanced usage: tolerance for primal feasibility of basic solutions.
This does not control the integer feasibility tolerance of integer solutions for MIP or the tolerance used during presolve.
931 def SetDoubleParam(self, param, value): 932 r""" Sets a double parameter to a specific value.""" 933 return _pywraplp.MPSolverParameters_SetDoubleParam(self, param, value)
Sets a double parameter to a specific value.
935 def SetIntegerParam(self, param, value): 936 r""" Sets a integer parameter to a specific value.""" 937 return _pywraplp.MPSolverParameters_SetIntegerParam(self, param, value)
Sets a integer parameter to a specific value.
939 def GetDoubleParam(self, param): 940 r""" Returns the value of a double parameter.""" 941 return _pywraplp.MPSolverParameters_GetDoubleParam(self, param)
Returns the value of a double parameter.
957class ModelExportOptions(object): 958 r""" Export options.""" 959 960 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 961 __repr__ = _swig_repr 962 963 def __init__(self): 964 _pywraplp.ModelExportOptions_swiginit(self, _pywraplp.new_ModelExportOptions()) 965 __swig_destroy__ = _pywraplp.delete_ModelExportOptions
Export options.