Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
pywraplp.py
Go to the documentation of this file.
1# This file was automatically generated by SWIG (https://www.swig.org).
2# Version 4.3.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
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
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
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
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
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 `interrupt` is non-const because the internal solver may set it to true
349 itself, in some cases.
350
351 Note(user): This attempts to first use `DirectlySolveProto()` (if
352 implemented). Consequently, this most likely does *not* override any of
353 the default parameters of the underlying solver. This behavior *differs*
354 from `MPSolver::Solve()` which by default sets the feasibility tolerance
355 and the gap limit (as of 2020/02/11, to 1e-7 and 0.0001, respectively).
356 """
357 return _pywraplp.Solver_SolveWithProto(model_request, response, interrupt)
358
359 def ExportModelToProto(self, output_model):
360 r"""Exports model to protocol buffer."""
361 return _pywraplp.Solver_ExportModelToProto(self, output_model)
362
364 r"""
365 Advanced usage: pass solver specific parameters in text format.
366
367 The format is solver-specific and is the same as the corresponding solver
368 configuration file format. Returns true if the operation was successful.
369 """
370 return _pywraplp.Solver_SetSolverSpecificParametersAsString(self, parameters)
371 FREE = _pywraplp.Solver_FREE
372 AT_LOWER_BOUND = _pywraplp.Solver_AT_LOWER_BOUND
373 AT_UPPER_BOUND = _pywraplp.Solver_AT_UPPER_BOUND
374 FIXED_VALUE = _pywraplp.Solver_FIXED_VALUE
375 BASIC = _pywraplp.Solver_BASIC
376
377 @staticmethod
378 def infinity():
379 r"""
380 Infinity.
381
382 You can use -MPSolver::infinity() for negative infinity.
383 """
384 return _pywraplp.Solver_infinity()
385
386 def EnableOutput(self):
387 r"""Enables solver logging."""
388 return _pywraplp.Solver_EnableOutput(self)
389
390 def SuppressOutput(self):
391 r"""Suppresses solver logging."""
392 return _pywraplp.Solver_SuppressOutput(self)
393
394 def iterations(self):
395 r"""Returns the number of simplex iterations."""
396 return _pywraplp.Solver_iterations(self)
397
398 def nodes(self):
399 r"""
400 Returns the number of branch-and-bound nodes evaluated during the solve.
401
402 Only available for discrete problems.
403 """
404 return _pywraplp.Solver_nodes(self)
405
406 def SolverVersion(self):
407 r"""Returns a string describing the underlying solver and its version."""
408 return _pywraplp.Solver_SolverVersion(self)
409
411 r"""
412 Advanced usage: computes the exact condition number of the current scaled
413 basis: L1norm(B) * L1norm(inverse(B)), where B is the scaled basis.
414
415 This method requires that a basis exists: it should be called after Solve.
416 It is only available for continuous problems. It is implemented for GLPK
417 but not CLP because CLP does not provide the API for doing it.
418
419 The condition number measures how well the constraint matrix is conditioned
420 and can be used to predict whether numerical issues will arise during the
421 solve: the model is declared infeasible whereas it is feasible (or
422 vice-versa), the solution obtained is not optimal or violates some
423 constraints, the resolution is slow because of repeated singularities.
424
425 The rule of thumb to interpret the condition number kappa is:
426 - o kappa <= 1e7: virtually no chance of numerical issues
427 - o 1e7 < kappa <= 1e10: small chance of numerical issues
428 - o 1e10 < kappa <= 1e13: medium chance of numerical issues
429 - o kappa > 1e13: high chance of numerical issues
430
431 The computation of the condition number depends on the quality of the LU
432 decomposition, so it is not very accurate when the matrix is ill
433 conditioned.
434 """
435 return _pywraplp.Solver_ComputeExactConditionNumber(self)
436
437 def NextSolution(self):
438 r"""
439 Some solvers (MIP only, not LP) can produce multiple solutions to the
440 problem. Returns true when another solution is available, and updates the
441 MPVariable* objects to make the new solution queryable. Call only after
442 calling solve.
443
444 The optimality properties of the additional solutions found, and whether or
445 not the solver computes them ahead of time or when NextSolution() is called
446 is solver specific.
447
448 As of 2020-02-10, only Gurobi and SCIP support NextSolution(), see
449 linear_solver_interfaces_test for an example of how to configure these
450 solvers for multiple solutions. Other solvers return false unconditionally.
451 """
452 return _pywraplp.Solver_NextSolution(self)
453
454 def set_time_limit(self, time_limit_milliseconds):
455 return _pywraplp.Solver_set_time_limit(self, time_limit_milliseconds)
456
457 def wall_time(self):
458 return _pywraplp.Solver_wall_time(self)
459
460 def LoadModelFromProto(self, input_model):
461 return _pywraplp.Solver_LoadModelFromProto(self, input_model)
462
463 def LoadModelFromProtoKeepNames(self, input_model):
464 return _pywraplp.Solver_LoadModelFromProtoKeepNames(self, input_model)
465
467 return _pywraplp.Solver_LoadModelFromProtoWithUniqueNamesOrDie(self, input_model)
468
469 def LoadSolutionFromProto(self, *args):
470 return _pywraplp.Solver_LoadSolutionFromProto(self, *args)
471
472 def ExportModelAsLpFormat(self, obfuscate):
473 return _pywraplp.Solver_ExportModelAsLpFormat(self, obfuscate)
474
475 def ExportModelAsMpsFormat(self, fixed_format, obfuscate):
476 return _pywraplp.Solver_ExportModelAsMpsFormat(self, fixed_format, obfuscate)
477
478 def WriteModelToMpsFile(self, filename, fixed_format, obfuscate):
479 return _pywraplp.Solver_WriteModelToMpsFile(self, filename, fixed_format, obfuscate)
480
481 def SetHint(self, variables, values):
482 r"""
483 Set a hint for solution.
484
485 If a feasible or almost-feasible solution to the problem is already known,
486 it may be helpful to pass it to the solver so that it can be used. A
487 solver that supports this feature will try to use this information to
488 create its initial feasible solution.
489
490 Note that it may not always be faster to give a hint like this to the
491 solver. There is also no guarantee that the solver will use this hint or
492 try to return a solution "close" to this assignment in case of multiple
493 optimal solutions.
494 """
495 return _pywraplp.Solver_SetHint(self, variables, values)
496
497 def SetNumThreads(self, num_theads):
498 r"""Sets the number of threads to be used by the solver."""
499 return _pywraplp.Solver_SetNumThreads(self, num_theads)
500
501 def Add(self, constraint, name=''):
502 if isinstance(constraint, bool):
503 if constraint:
504 return self.RowConstraint(0, 0, name)
505 else:
506 return self.RowConstraint(1, 1, name)
507 else:
508 return constraint.Extract(self, name)
509
510 def Sum(self, expr_array):
511 result = SumArray(expr_array)
512 return result
513
514 def RowConstraint(self, *args):
515 return self.Constraint(*args)
516
517 def Minimize(self, expr):
518 objective = self.Objective()
519 objective.Clear()
520 objective.SetMinimization()
521 if isinstance(expr, numbers.Number):
522 objective.SetOffset(expr)
523 else:
524 coeffs = expr.GetCoeffs()
525 objective.SetOffset(coeffs.pop(OFFSET_KEY, 0.0))
526 for v, c, in list(coeffs.items()):
527 objective.SetCoefficient(v, float(c))
528
529 def Maximize(self, expr):
530 objective = self.Objective()
531 objective.Clear()
532 objective.SetMaximization()
533 if isinstance(expr, numbers.Number):
534 objective.SetOffset(expr)
535 else:
536 coeffs = expr.GetCoeffs()
537 objective.SetOffset(coeffs.pop(OFFSET_KEY, 0.0))
538 for v, c, in list(coeffs.items()):
539 objective.SetCoefficient(v, float(c))
540
541
542 @staticmethod
543 def Infinity():
544 return _pywraplp.Solver_Infinity()
545
546 def SetTimeLimit(self, x):
547 return _pywraplp.Solver_SetTimeLimit(self, x)
548
549 def WallTime(self):
550 return _pywraplp.Solver_WallTime(self)
551
552 def Iterations(self):
553 return _pywraplp.Solver_Iterations(self)
554
555# Register Solver in _pywraplp:
556_pywraplp.Solver_swigregister(Solver)
557
558def __lshift__(*args):
559 return _pywraplp.__lshift__(*args)
560class Objective(object):
561 r"""A class to express a linear objective."""
562
563 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
564
565 def __init__(self, *args, **kwargs):
566 raise AttributeError("No constructor defined")
567 __repr__ = _swig_repr
568
569 def Clear(self):
570 r"""
571 Clears the offset, all variables and coefficients, and the optimization
572 direction.
573 """
574 return _pywraplp.Objective_Clear(self)
575
576 def SetCoefficient(self, var, coeff):
577 r"""
578 Sets the coefficient of the variable in the objective.
579
580 If the variable does not belong to the solver, the function just returns,
581 or crashes in non-opt mode.
582 """
583 return _pywraplp.Objective_SetCoefficient(self, var, coeff)
584
585 def GetCoefficient(self, var):
586 r"""
587 Gets the coefficient of a given variable in the objective
588
589 It returns 0 if the variable does not appear in the objective).
590 """
591 return _pywraplp.Objective_GetCoefficient(self, var)
592
593 def SetOffset(self, value):
594 r"""Sets the constant term in the objective."""
595 return _pywraplp.Objective_SetOffset(self, value)
596
597 def offset(self):
598 r"""Gets the constant term in the objective."""
599 return _pywraplp.Objective_offset(self)
600
601 def SetOptimizationDirection(self, maximize):
602 r"""Sets the optimization direction (maximize: true or minimize: false)."""
603 return _pywraplp.Objective_SetOptimizationDirection(self, maximize)
604
606 r"""Sets the optimization direction to minimize."""
607 return _pywraplp.Objective_SetMinimization(self)
608
610 r"""Sets the optimization direction to maximize."""
611 return _pywraplp.Objective_SetMaximization(self)
612
613 def maximization(self):
614 r"""Is the optimization direction set to maximize?"""
615 return _pywraplp.Objective_maximization(self)
616
617 def minimization(self):
618 r"""Is the optimization direction set to minimize?"""
619 return _pywraplp.Objective_minimization(self)
620
621 def Value(self):
622 r"""
623 Returns the objective value of the best solution found so far.
624
625 It is the optimal objective value if the problem has been solved to
626 optimality.
627
628 Note: the objective value may be slightly different than what you could
629 compute yourself using ``MPVariable::solution_value();`` please use the
630 --verify_solution flag to gain confidence about the numerical stability of
631 your solution.
632 """
633 return _pywraplp.Objective_Value(self)
634
635 def BestBound(self):
636 r"""
637 Returns the best objective bound.
638
639 In case of minimization, it is a lower bound on the objective value of the
640 optimal integer solution. Only available for discrete problems.
641 """
642 return _pywraplp.Objective_BestBound(self)
643
644 def Offset(self):
645 return _pywraplp.Objective_Offset(self)
646 __swig_destroy__ = _pywraplp.delete_Objective
647
648# Register Objective in _pywraplp:
649_pywraplp.Objective_swigregister(Objective)
650class Variable(object):
651 r"""The class for variables of a Mathematical Programming (MP) model."""
652
653 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
654
655 def __init__(self, *args, **kwargs):
656 raise AttributeError("No constructor defined")
657
658 def name(self):
659 r"""Returns the name of the variable."""
660 return _pywraplp.Variable_name(self)
661
662 def SetInteger(self, integer):
663 r"""Sets the integrality requirement of the variable."""
664 return _pywraplp.Variable_SetInteger(self, integer)
665
666 def integer(self):
667 r"""Returns the integrality requirement of the variable."""
668 return _pywraplp.Variable_integer(self)
669
670 def solution_value(self):
671 r"""
672 Returns the value of the variable in the current solution.
673
674 If the variable is integer, then the value will always be an integer (the
675 underlying solver handles floating-point values only, but this function
676 automatically rounds it to the nearest integer; see: man 3 round).
677 """
678 return _pywraplp.Variable_solution_value(self)
679
680 def index(self):
681 r"""Returns the index of the variable in the MPSolver::variables_."""
682 return _pywraplp.Variable_index(self)
683
684 def lb(self):
685 r"""Returns the lower bound."""
686 return _pywraplp.Variable_lb(self)
687
688 def ub(self):
689 r"""Returns the upper bound."""
690 return _pywraplp.Variable_ub(self)
691
692 def SetBounds(self, lb, ub):
693 r"""Sets both the lower and upper bounds."""
694 return _pywraplp.Variable_SetBounds(self, lb, ub)
695
696 def reduced_cost(self):
697 r"""
698 Advanced usage: returns the reduced cost of the variable in the current
699 solution (only available for continuous problems).
700 """
701 return _pywraplp.Variable_reduced_cost(self)
702
703 def basis_status(self):
704 r"""
705 Advanced usage: returns the basis status of the variable in the current
706 solution (only available for continuous problems).
707
708 See also: MPSolver::BasisStatus.
709 """
710 return _pywraplp.Variable_basis_status(self)
711
713 r"""
714 Advanced usage: Certain MIP solvers (e.g. Gurobi or SCIP) allow you to set
715 a per-variable priority for determining which variable to branch on.
716
717 A value of 0 is treated as default, and is equivalent to not setting the
718 branching priority. The solver looks first to branch on fractional
719 variables in higher priority levels. As of 2019-05, only Gurobi and SCIP
720 support setting branching priority; all other solvers will simply ignore
721 this annotation.
722 """
723 return _pywraplp.Variable_branching_priority(self)
724
725 def SetBranchingPriority(self, priority):
726 return _pywraplp.Variable_SetBranchingPriority(self, priority)
727
728 def __str__(self):
729 return _pywraplp.Variable___str__(self)
730
731 def __repr__(self):
732 return _pywraplp.Variable___repr__(self)
733
734 def __getattr__(self, name):
735 return getattr(VariableExpr(self), name)
736
737
738 def SolutionValue(self):
739 return _pywraplp.Variable_SolutionValue(self)
740
741 def Integer(self):
742 return _pywraplp.Variable_Integer(self)
743
744 def Lb(self):
745 return _pywraplp.Variable_Lb(self)
746
747 def Ub(self):
748 return _pywraplp.Variable_Ub(self)
749
750 def SetLb(self, x):
751 return _pywraplp.Variable_SetLb(self, x)
752
753 def SetUb(self, x):
754 return _pywraplp.Variable_SetUb(self, x)
755
756 def ReducedCost(self):
757 return _pywraplp.Variable_ReducedCost(self)
758 __swig_destroy__ = _pywraplp.delete_Variable
759
760# Register Variable in _pywraplp:
761_pywraplp.Variable_swigregister(Variable)
762class Constraint(object):
763 r"""
764 The class for constraints of a Mathematical Programming (MP) model.
765
766 A constraint is represented as a linear equation or inequality.
767 """
768
769 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
770
771 def __init__(self, *args, **kwargs):
772 raise AttributeError("No constructor defined")
773 __repr__ = _swig_repr
774
775 def name(self):
776 r"""Returns the name of the constraint."""
777 return _pywraplp.Constraint_name(self)
778
779 def Clear(self):
780 r"""Clears all variables and coefficients. Does not clear the bounds."""
781 return _pywraplp.Constraint_Clear(self)
782
783 def SetCoefficient(self, var, coeff):
784 r"""
785 Sets the coefficient of the variable on the constraint.
786
787 If the variable does not belong to the solver, the function just returns,
788 or crashes in non-opt mode.
789 """
790 return _pywraplp.Constraint_SetCoefficient(self, var, coeff)
791
792 def GetCoefficient(self, var):
793 r"""
794 Gets the coefficient of a given variable on the constraint (which is 0 if
795 the variable does not appear in the constraint).
796 """
797 return _pywraplp.Constraint_GetCoefficient(self, var)
798
799 def lb(self):
800 r"""Returns the lower bound."""
801 return _pywraplp.Constraint_lb(self)
802
803 def ub(self):
804 r"""Returns the upper bound."""
805 return _pywraplp.Constraint_ub(self)
806
807 def SetBounds(self, lb, ub):
808 r"""Sets both the lower and upper bounds."""
809 return _pywraplp.Constraint_SetBounds(self, lb, ub)
810
811 def set_is_lazy(self, laziness):
812 r"""
813 Advanced usage: sets the constraint "laziness".
814
815 **This is only supported for SCIP and has no effect on other
816 solvers.**
817
818 When **laziness** is true, the constraint is only considered by the Linear
819 Programming solver if its current solution violates the constraint. In this
820 case, the constraint is definitively added to the problem. This may be
821 useful in some MIP problems, and may have a dramatic impact on performance.
822
823 For more info see: http://tinyurl.com/lazy-constraints.
824 """
825 return _pywraplp.Constraint_set_is_lazy(self, laziness)
826
827 def index(self):
828 r"""Returns the index of the constraint in the MPSolver::constraints_."""
829 return _pywraplp.Constraint_index(self)
830
831 def dual_value(self):
832 r"""
833 Advanced usage: returns the dual value of the constraint in the current
834 solution (only available for continuous problems).
835 """
836 return _pywraplp.Constraint_dual_value(self)
837
838 def basis_status(self):
839 r"""
840 Advanced usage: returns the basis status of the constraint.
841
842 It is only available for continuous problems).
843
844 Note that if a constraint "linear_expression in [lb, ub]" is transformed
845 into "linear_expression + slack = 0" with slack in [-ub, -lb], then this
846 status is the same as the status of the slack variable with AT_UPPER_BOUND
847 and AT_LOWER_BOUND swapped.
848
849 See also: MPSolver::BasisStatus.
850 """
851 return _pywraplp.Constraint_basis_status(self)
852
853 def Lb(self):
854 return _pywraplp.Constraint_Lb(self)
855
856 def Ub(self):
857 return _pywraplp.Constraint_Ub(self)
858
859 def SetLb(self, x):
860 return _pywraplp.Constraint_SetLb(self, x)
861
862 def SetUb(self, x):
863 return _pywraplp.Constraint_SetUb(self, x)
864
865 def DualValue(self):
866 return _pywraplp.Constraint_DualValue(self)
867 __swig_destroy__ = _pywraplp.delete_Constraint
868
869# Register Constraint in _pywraplp:
870_pywraplp.Constraint_swigregister(Constraint)
871class MPSolverParameters(object):
872 r"""
873 This class stores parameter settings for LP and MIP solvers. Some parameters
874 are marked as advanced: do not change their values unless you know what you
875 are doing!
876
877 For developers: how to add a new parameter:
878 - Add the new Foo parameter in the DoubleParam or IntegerParam enum.
879 - If it is a categorical param, add a FooValues enum.
880 - Decide if the wrapper should define a default value for it: yes
881 if it controls the properties of the solution (example:
882 tolerances) or if it consistently improves performance, no
883 otherwise. If yes, define kDefaultFoo.
884 - Add a foo_value_ member and, if no default value is defined, a
885 foo_is_default_ member.
886 - Add code to handle Foo in Set...Param, Reset...Param,
887 Get...Param, Reset and the constructor.
888 - In class MPSolverInterface, add a virtual method SetFoo, add it
889 to SetCommonParameters or SetMIPParameters, and implement it for
890 each solver. Sometimes, parameters need to be implemented
891 differently, see for example the INCREMENTALITY implementation.
892 - Add a test in linear_solver_test.cc.
893
894 TODO(user): store the parameter values in a protocol buffer
895 instead. We need to figure out how to deal with the subtleties of
896 the default values.
897 """
898
899 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
900 __repr__ = _swig_repr
901 RELATIVE_MIP_GAP = _pywraplp.MPSolverParameters_RELATIVE_MIP_GAP
902 r"""Limit for relative MIP gap."""
903 PRIMAL_TOLERANCE = _pywraplp.MPSolverParameters_PRIMAL_TOLERANCE
904 r"""
905 Advanced usage: tolerance for primal feasibility of basic solutions.
906
907 This does not control the integer feasibility tolerance of integer
908 solutions for MIP or the tolerance used during presolve.
909 """
910 DUAL_TOLERANCE = _pywraplp.MPSolverParameters_DUAL_TOLERANCE
911 r"""Advanced usage: tolerance for dual feasibility of basic solutions."""
912 PRESOLVE = _pywraplp.MPSolverParameters_PRESOLVE
913 r"""Advanced usage: presolve mode."""
914 LP_ALGORITHM = _pywraplp.MPSolverParameters_LP_ALGORITHM
915 r"""Algorithm to solve linear programs."""
916 INCREMENTALITY = _pywraplp.MPSolverParameters_INCREMENTALITY
917 r"""Advanced usage: incrementality from one solve to the next."""
918 SCALING = _pywraplp.MPSolverParameters_SCALING
919 r"""Advanced usage: enable or disable matrix scaling."""
920 PRESOLVE_OFF = _pywraplp.MPSolverParameters_PRESOLVE_OFF
921 r"""Presolve is off."""
922 PRESOLVE_ON = _pywraplp.MPSolverParameters_PRESOLVE_ON
923 r"""Presolve is on."""
924 DUAL = _pywraplp.MPSolverParameters_DUAL
925 r"""Dual simplex."""
926 PRIMAL = _pywraplp.MPSolverParameters_PRIMAL
927 r"""Primal simplex."""
928 BARRIER = _pywraplp.MPSolverParameters_BARRIER
929 r"""Barrier algorithm."""
930 INCREMENTALITY_OFF = _pywraplp.MPSolverParameters_INCREMENTALITY_OFF
931 r"""Start solve from scratch."""
932 INCREMENTALITY_ON = _pywraplp.MPSolverParameters_INCREMENTALITY_ON
933 r"""
934 Reuse results from previous solve as much as the underlying solver
935 allows.
936 """
937 SCALING_OFF = _pywraplp.MPSolverParameters_SCALING_OFF
938 r"""Scaling is off."""
939 SCALING_ON = _pywraplp.MPSolverParameters_SCALING_ON
940 r"""Scaling is on."""
941
942 def __init__(self):
943 r"""The constructor sets all parameters to their default value."""
944 _pywraplp.MPSolverParameters_swiginit(self, _pywraplp.new_MPSolverParameters())
945
946 def SetDoubleParam(self, param, value):
947 r"""Sets a double parameter to a specific value."""
948 return _pywraplp.MPSolverParameters_SetDoubleParam(self, param, value)
949
950 def SetIntegerParam(self, param, value):
951 r"""Sets a integer parameter to a specific value."""
952 return _pywraplp.MPSolverParameters_SetIntegerParam(self, param, value)
953
954 def GetDoubleParam(self, param):
955 r"""Returns the value of a double parameter."""
956 return _pywraplp.MPSolverParameters_GetDoubleParam(self, param)
957
958 def GetIntegerParam(self, param):
959 r"""Returns the value of an integer parameter."""
960 return _pywraplp.MPSolverParameters_GetIntegerParam(self, param)
961 __swig_destroy__ = _pywraplp.delete_MPSolverParameters
962
963# Register MPSolverParameters in _pywraplp:
964_pywraplp.MPSolverParameters_swigregister(MPSolverParameters)
965cvar = _pywraplp.cvar
966MPSolverParameters.kDefaultRelativeMipGap = _pywraplp.cvar.MPSolverParameters_kDefaultRelativeMipGap
967MPSolverParameters.kDefaultPrimalTolerance = _pywraplp.cvar.MPSolverParameters_kDefaultPrimalTolerance
968MPSolverParameters.kDefaultDualTolerance = _pywraplp.cvar.MPSolverParameters_kDefaultDualTolerance
969MPSolverParameters.kDefaultPresolve = _pywraplp.cvar.MPSolverParameters_kDefaultPresolve
970MPSolverParameters.kDefaultIncrementality = _pywraplp.cvar.MPSolverParameters_kDefaultIncrementality
971
972class ModelExportOptions(object):
973 r"""Export options."""
974
975 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
976 __repr__ = _swig_repr
977
978 def __init__(self):
979 _pywraplp.ModelExportOptions_swiginit(self, _pywraplp.new_ModelExportOptions())
980 __swig_destroy__ = _pywraplp.delete_ModelExportOptions
981
982# Register ModelExportOptions in _pywraplp:
983_pywraplp.ModelExportOptions_swigregister(ModelExportOptions)
984
986 return _pywraplp.ExportModelAsLpFormat(*args)
987
989 return _pywraplp.ExportModelAsMpsFormat(*args)
990
991def FindErrorInModelProto(input_model):
992 return _pywraplp.FindErrorInModelProto(input_model)
993
995 setattr(Variable, opname,
996 lambda self, *args: getattr(VariableExpr(self), opname)(*args))
997for opname in LinearExpr.OVERRIDDEN_OPERATOR_METHODS:
999
1000
SetHint(self, variables, values)
Definition pywraplp.py:481
WriteModelToMpsFile(self, filename, fixed_format, obfuscate)
Definition pywraplp.py:478
Add(self, constraint, name='')
Definition pywraplp.py:501
LookupConstraint(self, constraint_name)
Definition pywraplp.py:214
ExportModelAsMpsFormat(self, fixed_format, obfuscate)
Definition pywraplp.py:475
Var(self, lb, ub, integer, name)
Definition pywraplp.py:176
FillSolutionResponseProto(self, response)
Definition pywraplp.py:333
__init__(self, name, problem_type)
Definition pywraplp.py:97
LoadModelFromProtoWithUniqueNamesOrDie(self, input_model)
Definition pywraplp.py:466
ExportModelToProto(self, output_model)
Definition pywraplp.py:359
SetSolverSpecificParametersAsString(self, parameters)
Definition pywraplp.py:363
LoadModelFromProto(self, input_model)
Definition pywraplp.py:460
LoadModelFromProtoKeepNames(self, input_model)
Definition pywraplp.py:463
VerifySolution(self, tolerance, log_errors)
Definition pywraplp.py:299
set_time_limit(self, time_limit_milliseconds)
Definition pywraplp.py:454
SolveWithProto(model_request, response, interrupt=None)
Definition pywraplp.py:338
__init__(self, *args, **kwargs)
Definition pywraplp.py:655
FindErrorInModelProto(input_model)
Definition pywraplp.py:991
_swig_setattr_nondynamic_instance_variable(set)
Definition pywraplp.py:27