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