7from sys
import version_info
as _swig_python_version_info
9if __package__
or "." in __name__:
10 from .
import _pywrapcp
15 import builtins
as __builtin__
21 strthis =
"proxy of " + self.this.__repr__()
22 except __builtin__.Exception:
24 return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
28 def set_instance_attr(self, name, value):
30 set(self, name, value)
31 elif name ==
"thisown":
33 elif hasattr(self, name)
and isinstance(getattr(type(self), name), property):
34 set(self, name, value)
36 raise AttributeError(
"You cannot add instance attributes to %s" % self)
37 return set_instance_attr
41 def set_class_attr(cls, name, value):
42 if hasattr(cls, name)
and not isinstance(getattr(cls, name), property):
45 raise AttributeError(
"You cannot add class attributes to %s" % cls)
50 """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
52 return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
57 """Meta class to enforce nondynamic attributes (no new attributes) for a class"""
65 This struct holds all parameters for the default search.
66 DefaultPhaseParameters is only used by Solver::MakeDefaultPhase methods.
67 Note this is for advanced users only.
70 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
72 CHOOSE_MAX_SUM_IMPACT = _pywrapcp.DefaultPhaseParameters_CHOOSE_MAX_SUM_IMPACT
73 CHOOSE_MAX_AVERAGE_IMPACT = _pywrapcp.DefaultPhaseParameters_CHOOSE_MAX_AVERAGE_IMPACT
74 CHOOSE_MAX_VALUE_IMPACT = _pywrapcp.DefaultPhaseParameters_CHOOSE_MAX_VALUE_IMPACT
75 SELECT_MIN_IMPACT = _pywrapcp.DefaultPhaseParameters_SELECT_MIN_IMPACT
76 SELECT_MAX_IMPACT = _pywrapcp.DefaultPhaseParameters_SELECT_MAX_IMPACT
77 NONE = _pywrapcp.DefaultPhaseParameters_NONE
78 NORMAL = _pywrapcp.DefaultPhaseParameters_NORMAL
79 VERBOSE = _pywrapcp.DefaultPhaseParameters_VERBOSE
80 var_selection_schema = property(_pywrapcp.DefaultPhaseParameters_var_selection_schema_get, _pywrapcp.DefaultPhaseParameters_var_selection_schema_set, doc=
r"""
81 This parameter describes how the next variable to instantiate
84 value_selection_schema = property(_pywrapcp.DefaultPhaseParameters_value_selection_schema_get, _pywrapcp.DefaultPhaseParameters_value_selection_schema_set, doc=
r"""This parameter describes which value to select for a given var.""")
85 initialization_splits = property(_pywrapcp.DefaultPhaseParameters_initialization_splits_get, _pywrapcp.DefaultPhaseParameters_initialization_splits_set, doc=
r"""
86 Maximum number of intervals that the initialization of impacts will scan
89 run_all_heuristics = property(_pywrapcp.DefaultPhaseParameters_run_all_heuristics_get, _pywrapcp.DefaultPhaseParameters_run_all_heuristics_set, doc=
r"""
90 The default phase will run heuristics periodically. This parameter
91 indicates if we should run all heuristics, or a randomly selected
94 heuristic_period = property(_pywrapcp.DefaultPhaseParameters_heuristic_period_get, _pywrapcp.DefaultPhaseParameters_heuristic_period_set, doc=
r"""
95 The distance in nodes between each run of the heuristics. A
96 negative or null value will mean that we will not run heuristics
99 heuristic_num_failures_limit = property(_pywrapcp.DefaultPhaseParameters_heuristic_num_failures_limit_get, _pywrapcp.DefaultPhaseParameters_heuristic_num_failures_limit_set, doc=
r"""The failure limit for each heuristic that we run.""")
100 persistent_impact = property(_pywrapcp.DefaultPhaseParameters_persistent_impact_get, _pywrapcp.DefaultPhaseParameters_persistent_impact_set, doc=
r"""
101 Whether to keep the impact from the first search for other searches,
102 or to recompute the impact for each new search.
104 random_seed = property(_pywrapcp.DefaultPhaseParameters_random_seed_get, _pywrapcp.DefaultPhaseParameters_random_seed_set, doc=
r"""Seed used to initialize the random part in some heuristics.""")
105 display_level = property(_pywrapcp.DefaultPhaseParameters_display_level_get, _pywrapcp.DefaultPhaseParameters_display_level_set, doc=
r"""
106 This represents the amount of information displayed by the default search.
107 NONE means no display, VERBOSE means extra information.
109 decision_builder = property(_pywrapcp.DefaultPhaseParameters_decision_builder_get, _pywrapcp.DefaultPhaseParameters_decision_builder_set, doc=
r"""When defined, this overrides the default impact based decision builder.""")
112 _pywrapcp.DefaultPhaseParameters_swiginit(self, _pywrapcp.new_DefaultPhaseParameters())
113 __swig_destroy__ = _pywrapcp.delete_DefaultPhaseParameters
116_pywrapcp.DefaultPhaseParameters_swigregister(DefaultPhaseParameters)
121 A solver represents the main computation engine. It implements the entire
122 range of Constraint Programming protocols:
127 Usually, Constraint Programming code consists of
128 - the creation of the Solver,
129 - the creation of the decision variables of the model,
130 - the creation of the constraints of the model and their addition to the
131 solver() through the AddConstraint() method,
132 - the creation of the main DecisionBuilder class,
133 - the launch of the solve() method with the decision builder.
135 For the time being, Solver is neither MT_SAFE nor MT_HOT.
138 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
139 __repr__ = _swig_repr
140 INT_VAR_DEFAULT = _pywrapcp.Solver_INT_VAR_DEFAULT
141 r"""The default behavior is CHOOSE_FIRST_UNBOUND."""
142 INT_VAR_SIMPLE = _pywrapcp.Solver_INT_VAR_SIMPLE
143 r"""The simple selection is CHOOSE_FIRST_UNBOUND."""
144 CHOOSE_FIRST_UNBOUND = _pywrapcp.Solver_CHOOSE_FIRST_UNBOUND
146 Select the first unbound variable.
147 Variables are considered in the order of the vector of IntVars used
148 to create the selector.
150 CHOOSE_RANDOM = _pywrapcp.Solver_CHOOSE_RANDOM
151 r"""Randomly select one of the remaining unbound variables."""
152 CHOOSE_MIN_SIZE_LOWEST_MIN = _pywrapcp.Solver_CHOOSE_MIN_SIZE_LOWEST_MIN
154 Among unbound variables, select the variable with the smallest size,
155 i.e., the smallest number of possible values.
156 In case of a tie, the selected variables is the one with the lowest min
158 In case of a tie, the first one is selected, first being defined by the
159 order in the vector of IntVars used to create the selector.
161 CHOOSE_MIN_SIZE_HIGHEST_MIN = _pywrapcp.Solver_CHOOSE_MIN_SIZE_HIGHEST_MIN
163 Among unbound variables, select the variable with the smallest size,
164 i.e., the smallest number of possible values.
165 In case of a tie, the selected variable is the one with the highest min
167 In case of a tie, the first one is selected, first being defined by the
168 order in the vector of IntVars used to create the selector.
170 CHOOSE_MIN_SIZE_LOWEST_MAX = _pywrapcp.Solver_CHOOSE_MIN_SIZE_LOWEST_MAX
172 Among unbound variables, select the variable with the smallest size,
173 i.e., the smallest number of possible values.
174 In case of a tie, the selected variables is the one with the lowest max
176 In case of a tie, the first one is selected, first being defined by the
177 order in the vector of IntVars used to create the selector.
179 CHOOSE_MIN_SIZE_HIGHEST_MAX = _pywrapcp.Solver_CHOOSE_MIN_SIZE_HIGHEST_MAX
181 Among unbound variables, select the variable with the smallest size,
182 i.e., the smallest number of possible values.
183 In case of a tie, the selected variable is the one with the highest max
185 In case of a tie, the first one is selected, first being defined by the
186 order in the vector of IntVars used to create the selector.
188 CHOOSE_LOWEST_MIN = _pywrapcp.Solver_CHOOSE_LOWEST_MIN
190 Among unbound variables, select the variable with the smallest minimal
192 In case of a tie, the first one is selected, "first" defined by the
193 order in the vector of IntVars used to create the selector.
195 CHOOSE_HIGHEST_MAX = _pywrapcp.Solver_CHOOSE_HIGHEST_MAX
197 Among unbound variables, select the variable with the highest maximal
199 In case of a tie, the first one is selected, first being defined by the
200 order in the vector of IntVars used to create the selector.
202 CHOOSE_MIN_SIZE = _pywrapcp.Solver_CHOOSE_MIN_SIZE
204 Among unbound variables, select the variable with the smallest size.
205 In case of a tie, the first one is selected, first being defined by the
206 order in the vector of IntVars used to create the selector.
208 CHOOSE_MAX_SIZE = _pywrapcp.Solver_CHOOSE_MAX_SIZE
210 Among unbound variables, select the variable with the highest size.
211 In case of a tie, the first one is selected, first being defined by the
212 order in the vector of IntVars used to create the selector.
214 CHOOSE_MAX_REGRET_ON_MIN = _pywrapcp.Solver_CHOOSE_MAX_REGRET_ON_MIN
216 Among unbound variables, select the variable with the largest
217 gap between the first and the second values of the domain.
219 CHOOSE_PATH = _pywrapcp.Solver_CHOOSE_PATH
221 Selects the next unbound variable on a path, the path being defined by
222 the variables: var[i] corresponds to the index of the next of i.
224 INT_VALUE_DEFAULT = _pywrapcp.Solver_INT_VALUE_DEFAULT
225 r"""The default behavior is ASSIGN_MIN_VALUE."""
226 INT_VALUE_SIMPLE = _pywrapcp.Solver_INT_VALUE_SIMPLE
227 r"""The simple selection is ASSIGN_MIN_VALUE."""
228 ASSIGN_MIN_VALUE = _pywrapcp.Solver_ASSIGN_MIN_VALUE
229 r"""Selects the min value of the selected variable."""
230 ASSIGN_MAX_VALUE = _pywrapcp.Solver_ASSIGN_MAX_VALUE
231 r"""Selects the max value of the selected variable."""
232 ASSIGN_RANDOM_VALUE = _pywrapcp.Solver_ASSIGN_RANDOM_VALUE
233 r"""Selects randomly one of the possible values of the selected variable."""
234 ASSIGN_CENTER_VALUE = _pywrapcp.Solver_ASSIGN_CENTER_VALUE
236 Selects the first possible value which is the closest to the center
237 of the domain of the selected variable.
238 The center is defined as (min + max) / 2.
240 SPLIT_LOWER_HALF = _pywrapcp.Solver_SPLIT_LOWER_HALF
242 Split the domain in two around the center, and choose the lower
245 SPLIT_UPPER_HALF = _pywrapcp.Solver_SPLIT_UPPER_HALF
247 Split the domain in two around the center, and choose the lower
250 SEQUENCE_DEFAULT = _pywrapcp.Solver_SEQUENCE_DEFAULT
251 SEQUENCE_SIMPLE = _pywrapcp.Solver_SEQUENCE_SIMPLE
252 CHOOSE_MIN_SLACK_RANK_FORWARD = _pywrapcp.Solver_CHOOSE_MIN_SLACK_RANK_FORWARD
253 CHOOSE_RANDOM_RANK_FORWARD = _pywrapcp.Solver_CHOOSE_RANDOM_RANK_FORWARD
254 INTERVAL_DEFAULT = _pywrapcp.Solver_INTERVAL_DEFAULT
255 r"""The default is INTERVAL_SET_TIMES_FORWARD."""
256 INTERVAL_SIMPLE = _pywrapcp.Solver_INTERVAL_SIMPLE
257 r"""The simple is INTERVAL_SET_TIMES_FORWARD."""
258 INTERVAL_SET_TIMES_FORWARD = _pywrapcp.Solver_INTERVAL_SET_TIMES_FORWARD
260 Selects the variable with the lowest starting time of all variables,
261 and fixes its starting time to this lowest value.
263 INTERVAL_SET_TIMES_BACKWARD = _pywrapcp.Solver_INTERVAL_SET_TIMES_BACKWARD
265 Selects the variable with the highest ending time of all variables,
266 and fixes the ending time to this highest values.
268 TWOOPT = _pywrapcp.Solver_TWOOPT
270 Operator which reverses a sub-chain of a path. It is called TwoOpt
271 because it breaks two arcs on the path; resulting paths are called
273 Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5
274 (where (1, 5) are first and last nodes of the path and can therefore not
276 1 -> [3 -> 2] -> 4 -> 5
277 1 -> [4 -> 3 -> 2] -> 5
278 1 -> 2 -> [4 -> 3] -> 5
280 OROPT = _pywrapcp.Solver_OROPT
282 Relocate: OROPT and RELOCATE.
283 Operator which moves a sub-chain of a path to another position; the
284 specified chain length is the fixed length of the chains being moved.
285 When this length is 1, the operator simply moves a node to another
287 Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5, for a chain
288 length of 2 (where (1, 5) are first and last nodes of the path and can
289 therefore not be moved):
290 1 -> 4 -> [2 -> 3] -> 5
291 1 -> [3 -> 4] -> 2 -> 5
293 Using Relocate with chain lengths of 1, 2 and 3 together is equivalent
294 to the OrOpt operator on a path. The OrOpt operator is a limited
295 version of 3Opt (breaks 3 arcs on a path).
297 RELOCATE = _pywrapcp.Solver_RELOCATE
298 r"""Relocate neighborhood with length of 1 (see OROPT comment)."""
299 EXCHANGE = _pywrapcp.Solver_EXCHANGE
301 Operator which exchanges the positions of two nodes.
302 Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5
303 (where (1, 5) are first and last nodes of the path and can therefore not
305 1 -> [3] -> [2] -> 4 -> 5
306 1 -> [4] -> 3 -> [2] -> 5
307 1 -> 2 -> [4] -> [3] -> 5
309 CROSS = _pywrapcp.Solver_CROSS
311 Operator which cross exchanges the starting chains of 2 paths, including
312 exchanging the whole paths.
313 First and last nodes are not moved.
314 Possible neighbors for the paths 1 -> 2 -> 3 -> 4 -> 5 and 6 -> 7 -> 8
315 (where (1, 5) and (6, 8) are first and last nodes of the paths and can
316 therefore not be moved):
317 1 -> [7] -> 3 -> 4 -> 5 6 -> [2] -> 8
318 1 -> [7] -> 4 -> 5 6 -> [2 -> 3] -> 8
319 1 -> [7] -> 5 6 -> [2 -> 3 -> 4] -> 8
321 MAKEACTIVE = _pywrapcp.Solver_MAKEACTIVE
323 Operator which inserts an inactive node into a path.
324 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive
325 (where 1 and 4 are first and last nodes of the path) are:
326 1 -> [5] -> 2 -> 3 -> 4
327 1 -> 2 -> [5] -> 3 -> 4
328 1 -> 2 -> 3 -> [5] -> 4
330 MAKEINACTIVE = _pywrapcp.Solver_MAKEINACTIVE
332 Operator which makes path nodes inactive.
333 Possible neighbors for the path 1 -> 2 -> 3 -> 4 (where 1 and 4 are
334 first and last nodes of the path) are:
335 1 -> 3 -> 4 with 2 inactive
336 1 -> 2 -> 4 with 3 inactive
338 MAKECHAININACTIVE = _pywrapcp.Solver_MAKECHAININACTIVE
340 Operator which makes a "chain" of path nodes inactive.
341 Possible neighbors for the path 1 -> 2 -> 3 -> 4 (where 1 and 4 are
342 first and last nodes of the path) are:
343 1 -> 3 -> 4 with 2 inactive
344 1 -> 2 -> 4 with 3 inactive
345 1 -> 4 with 2 and 3 inactive
347 SWAPACTIVE = _pywrapcp.Solver_SWAPACTIVE
349 Operator which replaces an active node by an inactive one.
350 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive
351 (where 1 and 4 are first and last nodes of the path) are:
352 1 -> [5] -> 3 -> 4 with 2 inactive
353 1 -> 2 -> [5] -> 4 with 3 inactive
355 EXTENDEDSWAPACTIVE = _pywrapcp.Solver_EXTENDEDSWAPACTIVE
357 Operator which makes an inactive node active and an active one inactive.
358 It is similar to SwapActiveOperator except that it tries to insert the
359 inactive node in all possible positions instead of just the position of
360 the node made inactive.
361 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive
362 (where 1 and 4 are first and last nodes of the path) are:
363 1 -> [5] -> 3 -> 4 with 2 inactive
364 1 -> 3 -> [5] -> 4 with 2 inactive
365 1 -> [5] -> 2 -> 4 with 3 inactive
366 1 -> 2 -> [5] -> 4 with 3 inactive
368 PATHLNS = _pywrapcp.Solver_PATHLNS
370 Operator which relaxes two sub-chains of three consecutive arcs each.
371 Each sub-chain is defined by a start node and the next three arcs. Those
372 six arcs are relaxed to build a new neighbor.
373 PATHLNS explores all possible pairs of starting nodes and so defines
374 n^2 neighbors, n being the number of nodes.
375 Note that the two sub-chains can be part of the same path; they even may
378 FULLPATHLNS = _pywrapcp.Solver_FULLPATHLNS
380 Operator which relaxes one entire path and all inactive nodes, thus
381 defining num_paths neighbors.
383 UNACTIVELNS = _pywrapcp.Solver_UNACTIVELNS
385 Operator which relaxes all inactive nodes and one sub-chain of six
386 consecutive arcs. That way the path can be improved by inserting
387 inactive nodes or swapping arcs.
389 INCREMENT = _pywrapcp.Solver_INCREMENT
391 Operator which defines one neighbor per variable. Each neighbor tries to
392 increment by one the value of the corresponding variable. When a new
393 solution is found the neighborhood is rebuilt from scratch, i.e., tries
394 to increment values in the variable order.
395 Consider for instance variables x and y. x is incremented one by one to
396 its max, and when it is not possible to increment x anymore, y is
397 incremented once. If this is a solution, then next neighbor tries to
400 DECREMENT = _pywrapcp.Solver_DECREMENT
402 Operator which defines a neighborhood to decrement values.
403 The behavior is the same as INCREMENT, except values are decremented
404 instead of incremented.
406 SIMPLELNS = _pywrapcp.Solver_SIMPLELNS
408 Operator which defines one neighbor per variable. Each neighbor relaxes
410 When a new solution is found the neighborhood is rebuilt from scratch.
411 Consider for instance variables x and y. First x is relaxed and the
412 solver is looking for the best possible solution (with only x relaxed).
413 Then y is relaxed, and the solver is looking for a new solution.
414 If a new solution is found, then the next variable to be relaxed is x.
416 GE = _pywrapcp.Solver_GE
417 r"""Move is accepted when the current objective value >= objective.Min."""
418 LE = _pywrapcp.Solver_LE
419 r"""Move is accepted when the current objective value <= objective.Max."""
420 EQ = _pywrapcp.Solver_EQ
422 Move is accepted when the current objective value is in the interval
423 objective.Min .. objective.Max.
425 DELAYED_PRIORITY = _pywrapcp.Solver_DELAYED_PRIORITY
427 DELAYED_PRIORITY is the lowest priority: Demons will be processed after
428 VAR_PRIORITY and NORMAL_PRIORITY demons.
430 VAR_PRIORITY = _pywrapcp.Solver_VAR_PRIORITY
431 r"""VAR_PRIORITY is between DELAYED_PRIORITY and NORMAL_PRIORITY."""
432 NORMAL_PRIORITY = _pywrapcp.Solver_NORMAL_PRIORITY
433 r"""NORMAL_PRIORITY is the highest priority: Demons will be processed first."""
437 _pywrapcp.Solver_swiginit(self, _pywrapcp.new_Solver(*args))
443 __swig_destroy__ = _pywrapcp.delete_Solver
446 r"""Stored Parameters."""
447 return _pywrapcp.Solver_Parameters(self)
451 r"""Create a ConstraintSolverParameters proto with all the default values."""
452 return _pywrapcp.Solver_DefaultSolverParameters()
456 Adds the constraint 'c' to the model.
458 After calling this method, and until there is a backtrack that undoes the
459 addition, any assignment of variables to values must satisfy the given
460 constraint in order to be considered feasible. There are two fairly
463 - the most common use case is modeling: the given constraint is really
464 part of the problem that the user is trying to solve. In this use case,
465 AddConstraint is called outside of search (i.e., with state() ==
466 OUTSIDE_SEARCH). Most users should only use AddConstraint in this
467 way. In this case, the constraint will belong to the model forever: it
468 cannot be removed by backtracking.
470 - a rarer use case is that 'c' is not a real constraint of the model. It
471 may be a constraint generated by a branching decision (a constraint whose
472 goal is to restrict the search space), a symmetry breaking constraint (a
473 constraint that does restrict the search space, but in a way that cannot
474 have an impact on the quality of the solutions in the subtree), or an
475 inferred constraint that, while having no semantic value to the model (it
476 does not restrict the set of solutions), is worth having because we
477 believe it may strengthen the propagation. In these cases, it happens
478 that the constraint is added during the search (i.e., with state() ==
479 IN_SEARCH or state() == IN_ROOT_NODE). When a constraint is
480 added during a search, it applies only to the subtree of the search tree
481 rooted at the current node, and will be automatically removed by
484 This method does not take ownership of the constraint. If the constraint
485 has been created by any factory method (Solver::MakeXXX), it will
486 automatically be deleted. However, power users who implement their own
487 constraints should do: solver.AddConstraint(solver.RevAlloc(new
490 return _pywrapcp.Solver_AddConstraint(self, c)
494 Solves the problem using the given DecisionBuilder and returns true if a
495 solution was found and accepted.
497 These methods are the ones most users should use to search for a solution.
498 Note that the definition of 'solution' is subtle. A solution here is
499 defined as a leaf of the search tree with respect to the given decision
500 builder for which there is no failure. What this means is that, contrary
501 to intuition, a solution may not have all variables of the model bound.
502 It is the responsibility of the decision builder to keep returning
503 decisions until all variables are indeed bound. The most extreme
504 counterexample is calling Solve with a trivial decision builder whose
505 Next() method always returns nullptr. In this case, Solve immediately
506 returns 'true', since not assigning any variable to any value is a
507 solution, unless the root node propagation discovers that the model is
510 This function must be called either from outside of search,
511 or from within the Next() method of a decision builder.
513 Solve will terminate whenever any of the following event arise:
514 A search monitor asks the solver to terminate the search by calling
515 solver()->FinishCurrentSearch().
516 A solution is found that is accepted by all search monitors, and none of
517 the search monitors decides to search for another one.
519 Upon search termination, there will be a series of backtracks all the way
520 to the top level. This means that a user cannot expect to inspect the
521 solution by querying variables after a call to Solve(): all the
522 information will be lost. In order to do something with the solution, the
525 Use a search monitor that can process such a leaf. See, in particular,
526 the SolutionCollector class.
527 Do not use Solve. Instead, use the more fine-grained approach using
528 methods NewSearch(...), NextSolution(), and EndSearch().
530 :type db: :py:class:`DecisionBuilder`
531 :param db: The decision builder that will generate the search tree.
532 :type monitors: std::vector< operations_research::SearchMonitor * >
533 :param monitors: A vector of search monitors that will be notified of
534 various events during the search. In their reaction to these events, such
535 monitors may influence the search.
537 return _pywrapcp.Solver_Solve(self, *args)
542 The code for a top level search should look like
543 solver->NewSearch(db);
544 while (solver->NextSolution()) {
545 .. use the current solution
547 solver()->EndSearch();
549 return _pywrapcp.Solver_NewSearch(self, *args)
552 return _pywrapcp.Solver_NextSolution(self)
555 return _pywrapcp.Solver_RestartSearch(self)
558 return _pywrapcp.Solver_EndSearch(self)
562 SolveAndCommit using a decision builder and up to three
563 search monitors, usually one for the objective, one for the limits
564 and one to collect solutions.
566 The difference between a SolveAndCommit() and a Solve() method
567 call is the fact that SolveAndCommit will not backtrack all
568 modifications at the end of the search. This method is only
569 usable during the Next() method of a decision builder.
571 return _pywrapcp.Solver_SolveAndCommit(self, *args)
574 r"""Checks whether the given assignment satisfies all relevant constraints."""
575 return _pywrapcp.Solver_CheckAssignment(self, solution)
579 Checks whether adding this constraint will lead to an immediate
580 failure. It will return false if the model is already inconsistent, or if
581 adding the constraint makes it inconsistent.
583 return _pywrapcp.Solver_CheckConstraint(self, ct)
586 r"""Abandon the current branch in the search tree. A backtrack will follow."""
587 return _pywrapcp.Solver_Fail(self)
591 r"""Current memory usage in bytes"""
592 return _pywrapcp.Solver_MemoryUsage()
596 DEPRECATED: Use Now() instead.
597 Time elapsed, in ms since the creation of the solver.
599 return _pywrapcp.Solver_WallTime(self)
602 r"""The number of branches explored since the creation of the solver."""
603 return _pywrapcp.Solver_Branches(self)
606 r"""The number of solutions found since the start of the search."""
607 return _pywrapcp.Solver_Solutions(self)
610 r"""The number of failures encountered since the creation of the solver."""
611 return _pywrapcp.Solver_Failures(self)
614 r"""The number of accepted neighbors."""
615 return _pywrapcp.Solver_AcceptedNeighbors(self)
619 The stamp indicates how many moves in the search tree we have performed.
620 It is useful to detect if we need to update same lazy structures.
622 return _pywrapcp.Solver_Stamp(self)
625 r"""The fail_stamp() is incremented after each backtrack."""
626 return _pywrapcp.Solver_FailStamp(self)
631 MakeIntVar will create the best range based int var for the bounds given.
636 MakeIntVar will create a variable with the given sparse domain.
641 MakeIntVar will create a variable with the given sparse domain.
646 MakeIntVar will create the best range based int var for the bounds given.
651 MakeIntVar will create a variable with the given sparse domain.
656 MakeIntVar will create a variable with the given sparse domain.
658 return _pywrapcp.Solver_IntVar(self, *args)
663 MakeBoolVar will create a variable with a {0, 1} domain.
668 MakeBoolVar will create a variable with a {0, 1} domain.
670 return _pywrapcp.Solver_BoolVar(self, *args)
675 IntConst will create a constant expression.
680 IntConst will create a constant expression.
682 return _pywrapcp.Solver_IntConst(self, *args)
685 r"""sum of all vars."""
686 return _pywrapcp.Solver_Sum(self, vars)
698 return _pywrapcp.Solver_ScalProd(self, *args)
702 Function based element. The constraint takes ownership of the
703 callback. The callback must be monotonic. It must be able to
704 cope with any possible value in the domain of 'index'
705 (potentially negative ones too). Furtermore, monotonicity is not
706 checked. Thus giving a non-monotonic function, or specifying an
707 incorrect increasing parameter will result in undefined behavior.
709 return _pywrapcp.Solver_MonotonicElement(self, values, increasing, index)
724 Function-based element. The constraint takes ownership of the
725 callback. The callback must be able to cope with any possible
726 value in the domain of 'index' (potentially negative ones too).
731 2D version of function-based element expression, values(expr1, expr2).
738 return _pywrapcp.Solver_Element(self, *args)
742 Returns the expression expr such that vars[expr] == value.
743 It assumes that vars are all different.
745 return _pywrapcp.Solver_IndexExpression(self, vars, value)
755 std::min (left, right)
760 std::min(expr, value)
765 std::min(expr, value)
767 return _pywrapcp.Solver_Min(self, *args)
777 std::max(left, right)
782 std::max(expr, value)
787 std::max(expr, value)
789 return _pywrapcp.Solver_Max(self, *args)
792 r"""Convex piecewise function."""
793 return _pywrapcp.Solver_ConvexPiecewiseExpr(self, expr, early_cost, early_date, late_date, late_cost)
797 Semi continuous Expression (x <= 0 -> f(x) = 0; x > 0 -> f(x) = ax + b)
800 return _pywrapcp.Solver_SemiContinuousExpr(self, expr, fixed_charge, step)
803 r"""Conditional Expr condition ? expr : unperformed_value"""
804 return _pywrapcp.Solver_ConditionalExpression(self, condition, expr, unperformed_value)
807 r"""This constraint always succeeds."""
808 return _pywrapcp.Solver_TrueConstraint(self)
811 r"""This constraint always fails."""
812 return _pywrapcp.Solver_FalseConstraint(self, *args)
815 r"""boolvar == (var == value)"""
816 return _pywrapcp.Solver_IsEqualCstCt(self, var, value, boolvar)
819 r"""status var of (var == value)"""
820 return _pywrapcp.Solver_IsEqualCstVar(self, var, value)
823 r"""b == (v1 == v2)"""
824 return _pywrapcp.Solver_IsEqualCt(self, v1, v2, b)
827 r"""status var of (v1 == v2)"""
828 return _pywrapcp.Solver_IsEqualVar(self, v1, v2)
831 r"""boolvar == (var != value)"""
832 return _pywrapcp.Solver_IsDifferentCstCt(self, var, value, boolvar)
835 r"""status var of (var != value)"""
836 return _pywrapcp.Solver_IsDifferentCstVar(self, var, value)
839 r"""status var of (v1 != v2)"""
840 return _pywrapcp.Solver_IsDifferentVar(self, v1, v2)
843 r"""b == (v1 != v2)"""
844 return _pywrapcp.Solver_IsDifferentCt(self, v1, v2, b)
847 r"""boolvar == (var <= value)"""
848 return _pywrapcp.Solver_IsLessOrEqualCstCt(self, var, value, boolvar)
851 r"""status var of (var <= value)"""
852 return _pywrapcp.Solver_IsLessOrEqualCstVar(self, var, value)
855 r"""status var of (left <= right)"""
856 return _pywrapcp.Solver_IsLessOrEqualVar(self, left, right)
859 r"""b == (left <= right)"""
860 return _pywrapcp.Solver_IsLessOrEqualCt(self, left, right, b)
863 r"""boolvar == (var >= value)"""
864 return _pywrapcp.Solver_IsGreaterOrEqualCstCt(self, var, value, boolvar)
867 r"""status var of (var >= value)"""
868 return _pywrapcp.Solver_IsGreaterOrEqualCstVar(self, var, value)
871 r"""status var of (left >= right)"""
872 return _pywrapcp.Solver_IsGreaterOrEqualVar(self, left, right)
875 r"""b == (left >= right)"""
876 return _pywrapcp.Solver_IsGreaterOrEqualCt(self, left, right, b)
880 return _pywrapcp.Solver_IsGreaterCstCt(self, v, c, b)
883 r"""status var of (var > value)"""
884 return _pywrapcp.Solver_IsGreaterCstVar(self, var, value)
887 r"""status var of (left > right)"""
888 return _pywrapcp.Solver_IsGreaterVar(self, left, right)
891 r"""b == (left > right)"""
892 return _pywrapcp.Solver_IsGreaterCt(self, left, right, b)
896 return _pywrapcp.Solver_IsLessCstCt(self, v, c, b)
899 r"""status var of (var < value)"""
900 return _pywrapcp.Solver_IsLessCstVar(self, var, value)
903 r"""status var of (left < right)"""
904 return _pywrapcp.Solver_IsLessVar(self, left, right)
907 r"""b == (left < right)"""
908 return _pywrapcp.Solver_IsLessCt(self, left, right, b)
911 r"""Variation on arrays."""
912 return _pywrapcp.Solver_SumLessOrEqual(self, vars, cst)
915 return _pywrapcp.Solver_SumGreaterOrEqual(self, vars, cst)
918 return _pywrapcp.Solver_SumEquality(self, *args)
921 return _pywrapcp.Solver_ScalProdEquality(self, *args)
924 return _pywrapcp.Solver_ScalProdGreaterOrEqual(self, *args)
927 return _pywrapcp.Solver_ScalProdLessOrEqual(self, *args)
930 return _pywrapcp.Solver_MinEquality(self, vars, min_var)
933 return _pywrapcp.Solver_MaxEquality(self, vars, max_var)
936 return _pywrapcp.Solver_ElementEquality(self, *args)
939 r"""Creates the constraint abs(var) == abs_var."""
940 return _pywrapcp.Solver_AbsEquality(self, var, abs_var)
944 This constraint is a special case of the element constraint with
945 an array of integer variables, where the variables are all
946 different and the index variable is constrained such that
947 vars[index] == target.
949 return _pywrapcp.Solver_IndexOfConstraint(self, vars, index, target)
953 This method is a specialized case of the MakeConstraintDemon
954 method to call the InitiatePropagate of the constraint 'ct'.
956 return _pywrapcp.Solver_ConstraintInitialPropagateCallback(self, ct)
960 This method is a specialized case of the MakeConstraintDemon
961 method to call the InitiatePropagate of the constraint 'ct' with
964 return _pywrapcp.Solver_DelayedConstraintInitialPropagateCallback(self, ct)
967 r"""Creates a demon from a closure."""
968 return _pywrapcp.Solver_ClosureDemon(self, closure)
971 r"""(l <= expr <= u)"""
972 return _pywrapcp.Solver_BetweenCt(self, expr, l, u)
975 r"""b == (l <= expr <= u)"""
976 return _pywrapcp.Solver_IsBetweenCt(self, expr, l, u, b)
979 return _pywrapcp.Solver_IsBetweenVar(self, v, l, u)
983 expr in set. Propagation is lazy, i.e. this constraint does not
984 creates holes in the domain of the variable.
986 return _pywrapcp.Solver_MemberCt(self, *args)
996 expr should not be in the list of forbidden intervals [start[i]..end[i]].
1001 expr should not be in the list of forbidden intervals [start[i]..end[i]].
1003 return _pywrapcp.Solver_NotMemberCt(self, *args)
1006 r"""boolvar == (expr in set)"""
1007 return _pywrapcp.Solver_IsMemberCt(self, *args)
1010 return _pywrapcp.Solver_IsMemberVar(self, *args)
1015 |{i | vars[i] == value}| == max_count
1020 |{i | vars[i] == value}| == max_count
1022 return _pywrapcp.Solver_Count(self, *args)
1027 Aggregated version of count: |{i | v[i] == values[j]}| == cards[j]
1032 Aggregated version of count: |{i | v[i] == values[j]}| == cards[j]
1037 Aggregated version of count: |{i | v[i] == j}| == cards[j]
1042 Aggregated version of count with bounded cardinalities:
1043 forall j in 0 .. card_size - 1: card_min <= |{i | v[i] == j}| <= card_max
1048 Aggregated version of count with bounded cardinalities:
1049 forall j in 0 .. card_size - 1:
1050 card_min[j] <= |{i | v[i] == j}| <= card_max[j]
1055 Aggregated version of count with bounded cardinalities:
1056 forall j in 0 .. card_size - 1:
1057 card_min[j] <= |{i | v[i] == j}| <= card_max[j]
1062 Aggregated version of count with bounded cardinalities:
1063 forall j in 0 .. card_size - 1:
1064 card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j]
1069 Aggregated version of count with bounded cardinalities:
1070 forall j in 0 .. card_size - 1:
1071 card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j]
1073 return _pywrapcp.Solver_Distribute(self, *args)
1077 Deviation constraint:
1078 sum_i |n * vars[i] - total_sum| <= deviation_var and
1079 sum_i vars[i] == total_sum
1082 return _pywrapcp.Solver_Deviation(self, vars, deviation_var, total_sum)
1087 All variables are pairwise different. This corresponds to the
1088 stronger version of the propagation algorithm.
1093 All variables are pairwise different. If 'stronger_propagation'
1094 is true, stronger, and potentially slower propagation will
1095 occur. This API will be deprecated in the future.
1097 return _pywrapcp.Solver_AllDifferent(self, *args)
1101 All variables are pairwise different, unless they are assigned to
1104 return _pywrapcp.Solver_AllDifferentExcept(self, vars, escape_value)
1108 Creates a constraint binding the arrays of variables "vars" and
1109 "sorted_vars": sorted_vars[0] must be equal to the minimum of all
1110 variables in vars, and so on: the value of sorted_vars[i] must be
1111 equal to the i-th value of variables invars.
1113 This constraint propagates in both directions: from "vars" to
1114 "sorted_vars" and vice-versa.
1116 Behind the scenes, this constraint maintains that:
1117 - sorted is always increasing.
1118 - whatever the values of vars, there exists a permutation that
1119 injects its values into the sorted variables.
1121 For more info, please have a look at:
1122 https://mpi-inf.mpg.de/~mehlhorn/ftp/Mehlhorn-Thiel.pdf
1124 return _pywrapcp.Solver_SortingConstraint(self, vars, sorted)
1128 Creates a constraint that enforces that left is lexicographically less
1131 return _pywrapcp.Solver_LexicalLess(self, left, right)
1135 Creates a constraint that enforces that left is lexicographically less
1136 than or equal to right.
1138 return _pywrapcp.Solver_LexicalLessOrEqual(self, left, right)
1142 Creates a constraint that enforces that 'left' and 'right' both
1143 represent permutations of [0..left.size()-1], and that 'right' is
1144 the inverse permutation of 'left', i.e. for all i in
1145 [0..left.size()-1], right[left[i]] = i.
1147 return _pywrapcp.Solver_InversePermutationConstraint(self, left, right)
1151 Creates a constraint that states that all variables in the first
1152 vector are different from all variables in the second
1153 group. Thus the set of values in the first vector does not
1154 intersect with the set of values in the second vector.
1156 return _pywrapcp.Solver_NullIntersect(self, first_vars, second_vars)
1160 Creates a constraint that states that all variables in the first
1161 vector are different from all variables from the second group,
1162 unless they are assigned to the escape value. Thus the set of
1163 values in the first vector minus the escape value does not
1164 intersect with the set of values in the second vector.
1166 return _pywrapcp.Solver_NullIntersectExcept(self, first_vars, second_vars, escape_value)
1169 r"""Force the "nexts" variable to create a complete Hamiltonian path."""
1170 return _pywrapcp.Solver_Circuit(self, nexts)
1174 Force the "nexts" variable to create a complete Hamiltonian path
1175 for those that do not loop upon themselves.
1177 return _pywrapcp.Solver_SubCircuit(self, nexts)
1181 Delayed version of the same constraint: propagation on the nexts variables
1182 is delayed until all constraints have propagated.
1184 return _pywrapcp.Solver_DelayedPathCumul(self, nexts, active, cumuls, transits)
1189 Creates a constraint which accumulates values along a path such that:
1190 cumuls[next[i]] = cumuls[i] + transits[i].
1191 Active variables indicate if the corresponding next variable is active;
1192 this could be useful to model unperformed nodes in a routing problem.
1197 Creates a constraint which accumulates values along a path such that:
1198 cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]).
1199 Active variables indicate if the corresponding next variable is active;
1200 this could be useful to model unperformed nodes in a routing problem.
1201 Ownership of transit_evaluator is taken and it must be a repeatable
1207 Creates a constraint which accumulates values along a path such that:
1208 cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]) + slacks[i].
1209 Active variables indicate if the corresponding next variable is active;
1210 this could be useful to model unperformed nodes in a routing problem.
1211 Ownership of transit_evaluator is taken and it must be a repeatable
1214 return _pywrapcp.Solver_PathCumul(self, *args)
1219 This method creates a constraint where the graph of the relation
1220 between the variables is given in extension. There are 'arity'
1221 variables involved in the relation and the graph is given by a
1227 Compatibility layer for Python API.
1229 return _pywrapcp.Solver_AllowedAssignments(self, *args)
1234 This constraint create a finite automaton that will check the
1235 sequence of variables vars. It uses a transition table called
1236 'transition_table'. Each transition is a triple
1237 (current_state, variable_value, new_state).
1238 The initial state is given, and the set of accepted states is decribed
1239 by 'final_states'. These states are hidden inside the constraint.
1240 Only the transitions (i.e. the variables) are visible.
1245 This constraint create a finite automaton that will check the
1246 sequence of variables vars. It uses a transition table called
1247 'transition_table'. Each transition is a triple
1248 (current_state, variable_value, new_state).
1249 The initial state is given, and the set of accepted states is decribed
1250 by 'final_states'. These states are hidden inside the constraint.
1251 Only the transitions (i.e. the variables) are visible.
1253 return _pywrapcp.Solver_TransitionConstraint(self, *args)
1257 This constraint states that all the boxes must not overlap.
1258 The coordinates of box i are:
1259 (x_vars[i], y_vars[i]),
1260 (x_vars[i], y_vars[i] + y_size[i]),
1261 (x_vars[i] + x_size[i], y_vars[i]),
1262 (x_vars[i] + x_size[i], y_vars[i] + y_size[i]).
1263 The sizes must be non-negative. Boxes with a zero dimension can be
1264 pushed like any box.
1266 return _pywrapcp.Solver_NonOverlappingBoxesConstraint(self, *args)
1268 def Pack(self, vars, number_of_bins):
1270 This constraint packs all variables onto 'number_of_bins'
1271 variables. For any given variable, a value of 'number_of_bins'
1272 indicates that the variable is not assigned to any bin.
1273 Dimensions, i.e., cumulative constraints on this packing, can be
1274 added directly from the pack class.
1276 return _pywrapcp.Solver_Pack(self, vars, number_of_bins)
1281 Creates an interval var with a fixed duration. The duration must
1282 be greater than 0. If optional is true, then the interval can be
1283 performed or unperformed. If optional is false, then the interval
1284 is always performed.
1289 Creates a performed interval var with a fixed duration. The duration must
1295 Creates an interval var with a fixed duration, and performed_variable.
1296 The duration must be greater than 0.
1298 return _pywrapcp.Solver_FixedDurationIntervalVar(self, *args)
1301 r"""Creates a fixed and performed interval."""
1302 return _pywrapcp.Solver_FixedInterval(self, start, duration, name)
1304 def IntervalVar(self, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name):
1306 Creates an interval var by specifying the bounds on start,
1309 return _pywrapcp.Solver_IntervalVar(self, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name)
1313 Creates an interval var that is the mirror image of the given one, that
1314 is, the interval var obtained by reversing the axis.
1316 return _pywrapcp.Solver_MirrorInterval(self, interval_var)
1320 Creates an interval var with a fixed duration whose start is
1321 synchronized with the start of another interval, with a given
1322 offset. The performed status is also in sync with the performed
1323 status of the given interval variable.
1325 return _pywrapcp.Solver_FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset)
1329 Creates an interval var with a fixed duration whose start is
1330 synchronized with the end of another interval, with a given
1331 offset. The performed status is also in sync with the performed
1332 status of the given interval variable.
1334 return _pywrapcp.Solver_FixedDurationStartSyncedOnEndIntervalVar(self, interval_var, duration, offset)
1338 Creates an interval var with a fixed duration whose end is
1339 synchronized with the start of another interval, with a given
1340 offset. The performed status is also in sync with the performed
1341 status of the given interval variable.
1343 return _pywrapcp.Solver_FixedDurationEndSyncedOnStartIntervalVar(self, interval_var, duration, offset)
1347 Creates an interval var with a fixed duration whose end is
1348 synchronized with the end of another interval, with a given
1349 offset. The performed status is also in sync with the performed
1350 status of the given interval variable.
1352 return _pywrapcp.Solver_FixedDurationEndSyncedOnEndIntervalVar(self, interval_var, duration, offset)
1356 Creates and returns an interval variable that wraps around the given one,
1357 relaxing the min start and end. Relaxing means making unbounded when
1358 optional. If the variable is non-optional, this method returns
1361 More precisely, such an interval variable behaves as follows:
1362 When the underlying must be performed, the returned interval variable
1363 behaves exactly as the underlying;
1364 When the underlying may or may not be performed, the returned interval
1365 variable behaves like the underlying, except that it is unbounded on
1367 When the underlying cannot be performed, the returned interval variable
1368 is of duration 0 and must be performed in an interval unbounded on
1371 This is very useful to implement propagators that may only modify
1372 the start max or end max.
1374 return _pywrapcp.Solver_IntervalRelaxedMin(self, interval_var)
1378 Creates and returns an interval variable that wraps around the given one,
1379 relaxing the max start and end. Relaxing means making unbounded when
1380 optional. If the variable is non optional, this method returns
1383 More precisely, such an interval variable behaves as follows:
1384 When the underlying must be performed, the returned interval variable
1385 behaves exactly as the underlying;
1386 When the underlying may or may not be performed, the returned interval
1387 variable behaves like the underlying, except that it is unbounded on
1389 When the underlying cannot be performed, the returned interval variable
1390 is of duration 0 and must be performed in an interval unbounded on
1393 This is very useful for implementing propagators that may only modify
1394 the start min or end min.
1396 return _pywrapcp.Solver_IntervalRelaxedMax(self, interval_var)
1401 This constraint implements a temporal disjunction between two
1402 interval vars t1 and t2. 'alt' indicates which alternative was
1403 chosen (alt == 0 is equivalent to t1 before t2).
1408 This constraint implements a temporal disjunction between two
1411 return _pywrapcp.Solver_TemporalDisjunction(self, *args)
1415 This constraint forces all interval vars into an non-overlapping
1416 sequence. Intervals with zero duration can be scheduled anywhere.
1418 return _pywrapcp.Solver_DisjunctiveConstraint(self, intervals, name)
1423 This constraint forces that, for any integer t, the sum of the demands
1424 corresponding to an interval containing t does not exceed the given
1427 Intervals and demands should be vectors of equal size.
1429 Demands should only contain non-negative values. Zero values are
1430 supported, and the corresponding intervals are filtered out, as they
1431 neither impact nor are impacted by this constraint.
1436 This constraint forces that, for any integer t, the sum of the demands
1437 corresponding to an interval containing t does not exceed the given
1440 Intervals and demands should be vectors of equal size.
1442 Demands should only contain non-negative values. Zero values are
1443 supported, and the corresponding intervals are filtered out, as they
1444 neither impact nor are impacted by this constraint.
1449 This constraint forces that, for any integer t, the sum of the demands
1450 corresponding to an interval containing t does not exceed the given
1453 Intervals and demands should be vectors of equal size.
1455 Demands should only contain non-negative values. Zero values are
1456 supported, and the corresponding intervals are filtered out, as they
1457 neither impact nor are impacted by this constraint.
1462 This constraint enforces that, for any integer t, the sum of the demands
1463 corresponding to an interval containing t does not exceed the given
1466 Intervals and demands should be vectors of equal size.
1468 Demands should only contain non-negative values. Zero values are
1469 supported, and the corresponding intervals are filtered out, as they
1470 neither impact nor are impacted by this constraint.
1475 This constraint enforces that, for any integer t, the sum of demands
1476 corresponding to an interval containing t does not exceed the given
1479 Intervals and demands should be vectors of equal size.
1481 Demands should be positive.
1486 This constraint enforces that, for any integer t, the sum of demands
1487 corresponding to an interval containing t does not exceed the given
1490 Intervals and demands should be vectors of equal size.
1492 Demands should be positive.
1494 return _pywrapcp.Solver_Cumulative(self, *args)
1498 This constraint states that the target_var is the convex hull of
1499 the intervals. If none of the interval variables is performed,
1500 then the target var is unperformed too. Also, if the target
1501 variable is unperformed, then all the intervals variables are
1504 return _pywrapcp.Solver_Cover(self, vars, target_var)
1509 This method creates an empty assignment.
1514 This method creates an assignment which is a copy of 'a'.
1516 return _pywrapcp.Solver_Assignment(self, *args)
1521 Collect the first solution of the search.
1526 Collect the first solution of the search. The variables will need to
1529 return _pywrapcp.Solver_FirstSolutionCollector(self, *args)
1534 Collect the last solution of the search.
1539 Collect the last solution of the search. The variables will need to
1542 return _pywrapcp.Solver_LastSolutionCollector(self, *args)
1547 Collect the solution corresponding to the optimal value of the objective
1548 of 'assignment'; if 'assignment' does not have an objective no solution is
1549 collected. This collector only collects one solution corresponding to the
1550 best objective value (the first one found).
1555 Collect the solution corresponding to the optimal value of the
1556 objective of the internal assignment; if this assignment does not have an
1557 objective no solution is collected. This collector only collects one
1558 solution corresponding to the best objective value (the first one found).
1559 The variables and objective(s) will need to be added later.
1561 return _pywrapcp.Solver_BestValueSolutionCollector(self, *args)
1566 Collect all solutions of the search.
1571 Collect all solutions of the search. The variables will need to
1574 return _pywrapcp.Solver_AllSolutionCollector(self, *args)
1577 r"""Creates a minimization objective."""
1578 return _pywrapcp.Solver_Minimize(self, v, step)
1581 r"""Creates a maximization objective."""
1582 return _pywrapcp.Solver_Maximize(self, v, step)
1585 r"""Creates a objective with a given sense (true = maximization)."""
1586 return _pywrapcp.Solver_Optimize(self, maximize, v, step)
1591 Creates a minimization weighted objective. The actual objective is
1592 scalar_prod(sub_objectives, weights).
1597 Creates a minimization weighted objective. The actual objective is
1598 scalar_prod(sub_objectives, weights).
1600 return _pywrapcp.Solver_WeightedMinimize(self, *args)
1605 Creates a maximization weigthed objective.
1610 Creates a maximization weigthed objective.
1612 return _pywrapcp.Solver_WeightedMaximize(self, *args)
1617 Creates a weighted objective with a given sense (true = maximization).
1622 Creates a weighted objective with a given sense (true = maximization).
1624 return _pywrapcp.Solver_WeightedOptimize(self, *args)
1626 def TabuSearch(self, maximize, objective, step, vars, keep_tenure, forbid_tenure, tabu_factor):
1628 MetaHeuristics which try to get the search out of local optima.
1629 Creates a Tabu Search monitor.
1630 In the context of local search the behavior is similar to MakeOptimize(),
1631 creating an objective in a given sense. The behavior differs once a local
1632 optimum is reached: thereafter solutions which degrade the value of the
1633 objective are allowed if they are not "tabu". A solution is "tabu" if it
1634 doesn't respect the following rules:
1635 - improving the best solution found so far
1636 - variables in the "keep" list must keep their value, variables in the
1637 "forbid" list must not take the value they have in the list.
1638 Variables with new values enter the tabu lists after each new solution
1639 found and leave the lists after a given number of iterations (called
1640 tenure). Only the variables passed to the method can enter the lists.
1641 The tabu criterion is softened by the tabu factor which gives the number
1642 of "tabu" violations which is tolerated; a factor of 1 means no violations
1643 allowed; a factor of 0 means all violations are allowed.
1645 return _pywrapcp.Solver_TabuSearch(self, maximize, objective, step, vars, keep_tenure, forbid_tenure, tabu_factor)
1648 r"""Creates a Simulated Annealing monitor."""
1649 return _pywrapcp.Solver_SimulatedAnnealing(self, maximize, v, step, initial_temperature)
1653 This search monitor will restart the search periodically.
1654 At the iteration n, it will restart after scale_factor * Luby(n) failures
1655 where Luby is the Luby Strategy (i.e. 1 1 2 1 1 2 4 1 1 2 1 1 2 4 8...).
1657 return _pywrapcp.Solver_LubyRestart(self, scale_factor)
1661 This search monitor will restart the search periodically after 'frequency'
1664 return _pywrapcp.Solver_ConstantRestart(self, frequency)
1667 r"""Creates a search limit that constrains the running time."""
1668 return _pywrapcp.Solver_TimeLimit(self, *args)
1672 Creates a search limit that constrains the number of branches
1673 explored in the search tree.
1675 return _pywrapcp.Solver_BranchesLimit(self, branches)
1679 Creates a search limit that constrains the number of failures
1680 that can happen when exploring the search tree.
1682 return _pywrapcp.Solver_FailuresLimit(self, failures)
1686 Creates a search limit that constrains the number of solutions found
1689 return _pywrapcp.Solver_SolutionsLimit(self, solutions)
1694 Limits the search with the 'time', 'branches', 'failures' and
1695 'solutions' limits. 'smart_time_check' reduces the calls to the wall
1700 Creates a search limit from its protobuf description
1705 Creates a search limit that is reached when either of the underlying limit
1706 is reached. That is, the returned limit is more stringent than both
1709 return _pywrapcp.Solver_Limit(self, *args)
1713 Callback-based search limit. Search stops when limiter returns true; if
1714 this happens at a leaf the corresponding solution will be rejected.
1716 return _pywrapcp.Solver_CustomLimit(self, limiter)
1721 The SearchMonitors below will display a periodic search log
1722 on LOG(INFO) every branch_period branches explored.
1727 At each solution, this monitor also display the var value.
1732 At each solution, this monitor will also display result of
1733 ``display_callback``.
1738 At each solution, this monitor will display the 'var' value and the
1739 result of ``display_callback``.
1744 At each solution, this monitor will display the 'vars' values and the
1745 result of ``display_callback``.
1750 OptimizeVar Search Logs
1751 At each solution, this monitor will also display the 'opt_var' value.
1756 Creates a search monitor that will also print the result of the
1759 return _pywrapcp.Solver_SearchLog(self, *args)
1763 Creates a search monitor that will trace precisely the behavior of the
1764 search. Use this only for low level debugging.
1766 return _pywrapcp.Solver_SearchTrace(self, prefix)
1769 r"""Prints the model."""
1770 return _pywrapcp.Solver_PrintModelVisitor(self)
1773 r"""Displays some nice statistics on the model."""
1774 return _pywrapcp.Solver_StatisticsModelVisitor(self)
1778 return _pywrapcp.Solver_AssignVariableValue(self, var, val)
1781 return _pywrapcp.Solver_VariableLessOrEqualValue(self, var, value)
1784 return _pywrapcp.Solver_VariableGreaterOrEqualValue(self, var, value)
1787 return _pywrapcp.Solver_SplitVariableDomain(self, var, val, start_with_lower_half)
1790 return _pywrapcp.Solver_AssignVariableValueOrFail(self, var, value)
1793 return _pywrapcp.Solver_AssignVariablesValues(self, vars, values)
1796 return _pywrapcp.Solver_FailDecision(self)
1799 return _pywrapcp.Solver_Decision(self, apply, refute)
1802 return _pywrapcp.Solver_Compose(self, dbs)
1805 return _pywrapcp.Solver_Try(self, dbs)
1808 return _pywrapcp.Solver_DefaultPhase(self, *args)
1812 Returns a decision that tries to schedule a task at a given time.
1813 On the Apply branch, it will set that interval var as performed and set
1814 its start to 'est'. On the Refute branch, it will just update the
1815 'marker' to 'est' + 1. This decision is used in the
1816 INTERVAL_SET_TIMES_FORWARD strategy.
1818 return _pywrapcp.Solver_ScheduleOrPostpone(self, var, est, marker)
1822 Returns a decision that tries to schedule a task at a given time.
1823 On the Apply branch, it will set that interval var as performed and set
1824 its end to 'est'. On the Refute branch, it will just update the
1825 'marker' to 'est' - 1. This decision is used in the
1826 INTERVAL_SET_TIMES_BACKWARD strategy.
1828 return _pywrapcp.Solver_ScheduleOrExpedite(self, var, est, marker)
1832 Returns a decision that tries to rank first the ith interval var
1833 in the sequence variable.
1835 return _pywrapcp.Solver_RankFirstInterval(self, sequence, index)
1839 Returns a decision that tries to rank last the ith interval var
1840 in the sequence variable.
1842 return _pywrapcp.Solver_RankLastInterval(self, sequence, index)
1847 Phases on IntVar arrays.
1848 for all other functions that have several homonyms in this .h).
1855 return _pywrapcp.Solver_Phase(self, *args)
1859 Returns a decision builder for which the left-most leaf corresponds
1860 to assignment, the rest of the tree being explored using 'db'.
1862 return _pywrapcp.Solver_DecisionBuilderFromAssignment(self, assignment, db, vars)
1866 Returns a decision builder that will add the given constraint to
1869 return _pywrapcp.Solver_ConstraintAdder(self, ct)
1872 return _pywrapcp.Solver_SolveOnce(self, db, monitors)
1876 NestedOptimize will collapse a search tree described by a
1877 decision builder 'db' and a set of monitors and wrap it into a
1878 single point. If there are no solutions to this nested tree, then
1879 NestedOptimize will fail. If there are solutions, it will find
1880 the best as described by the mandatory objective in the solution
1881 as well as the optimization direction, instantiate all variables
1882 to this solution, and return nullptr.
1884 return _pywrapcp.Solver_NestedOptimize(self, *args)
1888 Returns a DecisionBuilder which restores an Assignment
1889 (calls void Assignment::Restore())
1891 return _pywrapcp.Solver_RestoreAssignment(self, assignment)
1895 Returns a DecisionBuilder which stores an Assignment
1896 (calls void Assignment::Store())
1898 return _pywrapcp.Solver_StoreAssignment(self, assignment)
1901 r"""Local Search Operators."""
1902 return _pywrapcp.Solver_Operator(self, *args)
1906 Creates a large neighborhood search operator which creates fragments (set
1907 of relaxed variables) with up to number_of_variables random variables
1908 (sampling with replacement is performed meaning that at most
1909 number_of_variables variables are selected). Warning: this operator will
1910 always return neighbors; using it without a search limit will result in a
1912 Optionally a random seed can be specified.
1914 return _pywrapcp.Solver_RandomLnsOperator(self, *args)
1919 Creates a local search operator that tries to move the assignment of some
1920 variables toward a target. The target is given as an Assignment. This
1921 operator generates neighbors in which the only difference compared to the
1922 current state is that one variable that belongs to the target assignment
1923 is set to its target value.
1928 Creates a local search operator that tries to move the assignment of some
1929 variables toward a target. The target is given either as two vectors: a
1930 vector of variables and a vector of associated target values. The two
1931 vectors should be of the same length. This operator generates neighbors in
1932 which the only difference compared to the current state is that one
1933 variable that belongs to the given vector is set to its target value.
1935 return _pywrapcp.Solver_MoveTowardTargetOperator(self, *args)
1939 Creates a local search operator which concatenates a vector of operators.
1940 Each operator from the vector is called sequentially. By default, when a
1941 neighbor is found the neighborhood exploration restarts from the last
1942 active operator (the one which produced the neighbor).
1943 This can be overridden by setting restart to true to force the exploration
1944 to start from the first operator in the vector.
1946 The default behavior can also be overridden using an evaluation callback
1947 to set the order in which the operators are explored (the callback is
1948 called in LocalSearchOperator::Start()). The first argument of the
1949 callback is the index of the operator which produced the last move, the
1950 second argument is the index of the operator to be evaluated. Ownership of
1951 the callback is taken by ConcatenateOperators.
1955 const int kPriorities = {10, 100, 10, 0};
1956 int64_t Evaluate(int active_operator, int current_operator) {
1957 return kPriorities[current_operator];
1960 LocalSearchOperator* concat =
1961 solver.ConcatenateOperators(operators,
1962 NewPermanentCallback(&Evaluate));
1964 The elements of the vector operators will be sorted by increasing priority
1965 and explored in that order (tie-breaks are handled by keeping the relative
1966 operator order in the vector). This would result in the following order:
1967 operators[3], operators[0], operators[2], operators[1].
1969 return _pywrapcp.Solver_ConcatenateOperators(self, *args)
1974 Randomized version of local search concatenator; calls a random operator
1975 at each call to MakeNextNeighbor().
1980 Randomized version of local search concatenator; calls a random operator
1981 at each call to MakeNextNeighbor(). The provided seed is used to
1982 initialize the random number generator.
1984 return _pywrapcp.Solver_RandomConcatenateOperators(self, *args)
1988 Creates a local search operator that wraps another local search
1989 operator and limits the number of neighbors explored (i.e., calls
1990 to MakeNextNeighbor from the current solution (between two calls
1991 to Start()). When this limit is reached, MakeNextNeighbor()
1992 returns false. The counter is cleared when Start() is called.
1994 return _pywrapcp.Solver_NeighborhoodLimit(self, op, limit)
1999 Local Search decision builders factories.
2000 Local search is used to improve a given solution. This initial solution
2001 can be specified either by an Assignment or by a DecisionBulder, and the
2002 corresponding variables, the initial solution being the first solution
2003 found by the DecisionBuilder.
2004 The LocalSearchPhaseParameters parameter holds the actual definition of
2005 the local search phase:
2006 - a local search operator used to explore the neighborhood of the current
2008 - a decision builder to instantiate unbound variables once a neighbor has
2009 been defined; in the case of LNS-based operators instantiates fragment
2010 variables; search monitors can be added to this sub-search by wrapping
2011 the decision builder with MakeSolveOnce.
2012 - a search limit specifying how long local search looks for neighbors
2013 before accepting one; the last neighbor is always taken and in the case
2014 of a greedy search, this corresponds to the best local neighbor;
2015 first-accept (which is the default behavior) can be modeled using a
2016 solution found limit of 1,
2017 - a vector of local search filters used to speed up the search by pruning
2018 unfeasible neighbors.
2019 Metaheuristics can be added by defining specialized search monitors;
2020 currently down/up-hill climbing is available through OptimizeVar, as well
2021 as Guided Local Search, Tabu Search and Simulated Annealing.
2026 Variant with a sub_decison_builder specific to the first solution.
2028 return _pywrapcp.Solver_LocalSearchPhase(self, *args)
2031 r"""Local Search Phase Parameters"""
2032 return _pywrapcp.Solver_LocalSearchPhaseParameters(self, *args)
2036 Returns a percentage representing the propress of the search before
2037 reaching the limits of the top-level search (can be called from a nested
2040 return _pywrapcp.Solver_TopProgressPercent(self)
2044 Gets the search depth of the current active search. Returns -1 if
2045 there is no active search opened.
2047 return _pywrapcp.Solver_SearchDepth(self)
2051 Gets the search left depth of the current active search. Returns -1 if
2052 there is no active search opened.
2054 return _pywrapcp.Solver_SearchLeftDepth(self)
2058 Gets the number of nested searches. It returns 0 outside search,
2059 1 during the top level search, 2 or more in case of nested searches.
2061 return _pywrapcp.Solver_SolveDepth(self)
2064 r"""Returns a random value between 0 and 'size' - 1;"""
2065 return _pywrapcp.Solver_Rand64(self, size)
2068 r"""Returns a random value between 0 and 'size' - 1;"""
2069 return _pywrapcp.Solver_Rand32(self, size)
2072 r"""Reseed the solver random generator."""
2073 return _pywrapcp.Solver_ReSeed(self, seed)
2076 r"""Returns local search profiling information in a human readable format."""
2077 return _pywrapcp.Solver_LocalSearchProfile(self)
2081 Counts the number of constraints that have been added
2082 to the solver before the search.
2084 return _pywrapcp.Solver_Constraints(self)
2087 r"""Accepts the given model visitor."""
2088 return _pywrapcp.Solver_Accept(self, visitor)
2091 r"""Tells the solver to kill or restart the current search."""
2092 return _pywrapcp.Solver_FinishCurrentSearch(self)
2095 return _pywrapcp.Solver_RestartCurrentSearch(self)
2099 These methods are only useful for the SWIG wrappers, which need a way
2100 to externally cause the Solver to fail.
2102 return _pywrapcp.Solver_ShouldFail(self)
2105 return _pywrapcp.Solver___str__(self)
2108 if isinstance(ct, PyConstraint):
2114 return _pywrapcp.Solver_TreeNoCycle(self, nexts, active, callback)
2117 return _pywrapcp.Solver_SearchLogWithCallback(self, period, callback)
2120 return _pywrapcp.Solver_ElementFunction(self, values, index)
2123 return _pywrapcp.Solver_VarEvalValStrPhase(self, vars, var_evaluator, val_str)
2126 return _pywrapcp.Solver_VarStrValEvalPhase(self, vars, var_str, val_eval)
2129 return _pywrapcp.Solver_VarEvalValEvalPhase(self, vars, var_eval, val_eval)
2132 return _pywrapcp.Solver_VarStrValEvalTieBreakPhase(self, vars, var_str, val_eval, tie_breaker)
2135 return _pywrapcp.Solver_VarEvalValEvalTieBreakPhase(self, vars, var_eval, val_eval, tie_breaker)
2138 return _pywrapcp.Solver_EvalEvalStrPhase(self, vars, evaluator, str)
2141 return _pywrapcp.Solver_EvalEvalStrTieBreakPhase(self, vars, evaluator, tie_breaker, str)
2144 return _pywrapcp.Solver_GuidedLocalSearch(self, maximize, objective, objective_function, step, vars, penalty_factor)
2147 return _pywrapcp.Solver_SumObjectiveFilter(self, vars, values, filter_enum)
2150_pywrapcp.Solver_swigregister(Solver)
2153 A BaseObject is the root of all reversibly allocated objects.
2154 A DebugString method and the associated << operator are implemented
2158 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2165 _pywrapcp.BaseObject_swiginit(self, _pywrapcp.new_BaseObject(_self, ))
2166 __swig_destroy__ = _pywrapcp.delete_BaseObject
2169 return _pywrapcp.BaseObject_DebugString(self)
2172 return _pywrapcp.BaseObject___str__(self)
2175 return _pywrapcp.BaseObject___repr__(self)
2178 _pywrapcp.disown_BaseObject(self)
2179 return weakref.proxy(self)
2182_pywrapcp.BaseObject_swigregister(BaseObject)
2186 The PropagationBaseObject is a subclass of BaseObject that is also
2187 friend to the Solver class. It allows accessing methods useful when
2188 writing new constraints or new expressions.
2191 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2192 __repr__ = _swig_repr
2195 if self.
__class__ == PropagationBaseObject:
2199 _pywrapcp.PropagationBaseObject_swiginit(self, _pywrapcp.new_PropagationBaseObject(_self, s))
2200 __swig_destroy__ = _pywrapcp.delete_PropagationBaseObject
2203 return _pywrapcp.PropagationBaseObject_DebugString(self)
2206 return _pywrapcp.PropagationBaseObject_solver(self)
2209 r"""Object naming."""
2210 return _pywrapcp.PropagationBaseObject_Name(self)
2213 _pywrapcp.disown_PropagationBaseObject(self)
2214 return weakref.proxy(self)
2217_pywrapcp.PropagationBaseObject_swigregister(PropagationBaseObject)
2220 A Decision represents a choice point in the search tree. The two main
2221 methods are Apply() to go left, or Refute() to go right.
2224 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2231 _pywrapcp.Decision_swiginit(self, _pywrapcp.new_Decision(_self, ))
2232 __swig_destroy__ = _pywrapcp.delete_Decision
2235 r"""Apply will be called first when the decision is executed."""
2236 return _pywrapcp.Decision_ApplyWrapper(self, s)
2239 r"""Refute will be called after a backtrack."""
2240 return _pywrapcp.Decision_RefuteWrapper(self, s)
2243 return _pywrapcp.Decision_DebugString(self)
2246 return _pywrapcp.Decision___repr__(self)
2249 return _pywrapcp.Decision___str__(self)
2252 _pywrapcp.disown_Decision(self)
2253 return weakref.proxy(self)
2256_pywrapcp.Decision_swigregister(Decision)
2259 A DecisionBuilder is responsible for creating the search tree. The
2260 important method is Next(), which returns the next decision to execute.
2263 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2270 _pywrapcp.DecisionBuilder_swiginit(self, _pywrapcp.new_DecisionBuilder(_self, ))
2271 __swig_destroy__ = _pywrapcp.delete_DecisionBuilder
2275 This is the main method of the decision builder class. It must
2276 return a decision (an instance of the class Decision). If it
2277 returns nullptr, this means that the decision builder has finished
2280 return _pywrapcp.DecisionBuilder_NextWrapper(self, s)
2283 return _pywrapcp.DecisionBuilder_DebugString(self)
2286 return _pywrapcp.DecisionBuilder___repr__(self)
2289 return _pywrapcp.DecisionBuilder___str__(self)
2292 _pywrapcp.disown_DecisionBuilder(self)
2293 return weakref.proxy(self)
2296_pywrapcp.DecisionBuilder_swigregister(DecisionBuilder)
2299 A Demon is the base element of a propagation queue. It is the main
2300 object responsible for implementing the actual propagation
2301 of the constraint and pruning the inconsistent values in the domains
2302 of the variables. The main concept is that demons are listeners that are
2303 attached to the variables and listen to their modifications.
2304 There are two methods:
2305 - Run() is the actual method called when the demon is processed.
2306 - priority() returns its priority. Standard priorities are slow, normal
2307 or fast. "immediate" is reserved for variables and is treated separately.
2310 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2311 __repr__ = _swig_repr
2315 This indicates the priority of a demon. Immediate demons are treated
2316 separately and corresponds to variables.
2322 _pywrapcp.Demon_swiginit(self, _pywrapcp.new_Demon(_self, ))
2323 __swig_destroy__ = _pywrapcp.delete_Demon
2326 r"""This is the main callback of the demon."""
2327 return _pywrapcp.Demon_RunWrapper(self, s)
2331 This method returns the priority of the demon. Usually a demon is
2332 fast, slow or normal. Immediate demons are reserved for internal
2333 use to maintain variables.
2335 return _pywrapcp.Demon_Priority(self)
2338 return _pywrapcp.Demon_DebugString(self)
2342 This method inhibits the demon in the search tree below the
2345 return _pywrapcp.Demon_Inhibit(self, s)
2348 r"""This method un-inhibits the demon that was previously inhibited."""
2349 return _pywrapcp.Demon_Desinhibit(self, s)
2352 _pywrapcp.disown_Demon(self)
2353 return weakref.proxy(self)
2356_pywrapcp.Demon_swigregister(Demon)
2359 A constraint is the main modeling object. It provides two methods:
2360 - Post() is responsible for creating the demons and attaching them to
2362 - InitialPropagate() is called once just after Post and performs
2363 the initial propagation. The subsequent propagations will be performed
2364 by the demons Posted during the post() method.
2367 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2374 _pywrapcp.Constraint_swiginit(self, _pywrapcp.new_Constraint(_self, solver))
2375 __swig_destroy__ = _pywrapcp.delete_Constraint
2379 This method is called when the constraint is processed by the
2380 solver. Its main usage is to attach demons to variables.
2382 return _pywrapcp.Constraint_Post(self)
2386 This method performs the initial propagation of the
2387 constraint. It is called just after the post.
2389 return _pywrapcp.Constraint_InitialPropagateWrapper(self)
2392 return _pywrapcp.Constraint_DebugString(self)
2396 Creates a Boolean variable representing the status of the constraint
2397 (false = constraint is violated, true = constraint is satisfied). It
2398 returns nullptr if the constraint does not support this API.
2400 return _pywrapcp.Constraint_Var(self)
2403 return _pywrapcp.Constraint___repr__(self)
2406 return _pywrapcp.Constraint___str__(self)
2409 return _pywrapcp.Constraint___add__(self, *args)
2412 return _pywrapcp.Constraint___radd__(self, v)
2415 return _pywrapcp.Constraint___sub__(self, *args)
2418 return _pywrapcp.Constraint___rsub__(self, v)
2421 return _pywrapcp.Constraint___mul__(self, *args)
2424 return _pywrapcp.Constraint___rmul__(self, v)
2427 return _pywrapcp.Constraint___floordiv__(self, v)
2430 return _pywrapcp.Constraint___neg__(self)
2433 return _pywrapcp.Constraint___abs__(self)
2436 return _pywrapcp.Constraint_Square(self)
2439 return _pywrapcp.Constraint___eq__(self, *args)
2442 return _pywrapcp.Constraint___ne__(self, *args)
2445 return _pywrapcp.Constraint___ge__(self, *args)
2448 return _pywrapcp.Constraint___gt__(self, *args)
2451 return _pywrapcp.Constraint___le__(self, *args)
2454 return _pywrapcp.Constraint___lt__(self, *args)
2457 return _pywrapcp.Constraint_MapTo(self, vars)
2460 return _pywrapcp.Constraint_IndexOf(self, *args)
2463 _pywrapcp.disown_Constraint(self)
2464 return weakref.proxy(self)
2467_pywrapcp.Constraint_swigregister(Constraint)
2469 r"""A search monitor is a simple set of callbacks to monitor all search events"""
2471 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2472 kNoProgress = _pywrapcp.SearchMonitor_kNoProgress
2479 _pywrapcp.SearchMonitor_swiginit(self, _pywrapcp.new_SearchMonitor(_self, s))
2480 __swig_destroy__ = _pywrapcp.delete_SearchMonitor
2483 r"""Beginning of the search."""
2484 return _pywrapcp.SearchMonitor_EnterSearch(self)
2487 r"""Restart the search."""
2488 return _pywrapcp.SearchMonitor_RestartSearch(self)
2491 r"""End of the search."""
2492 return _pywrapcp.SearchMonitor_ExitSearch(self)
2495 r"""Before calling DecisionBuilder::Next."""
2496 return _pywrapcp.SearchMonitor_BeginNextDecision(self, b)
2499 r"""After calling DecisionBuilder::Next, along with the returned decision."""
2500 return _pywrapcp.SearchMonitor_EndNextDecision(self, b, d)
2503 r"""Before applying the decision."""
2504 return _pywrapcp.SearchMonitor_ApplyDecision(self, d)
2507 r"""Before refuting the decision."""
2508 return _pywrapcp.SearchMonitor_RefuteDecision(self, d)
2512 Just after refuting or applying the decision, apply is true after Apply.
2513 This is called only if the Apply() or Refute() methods have not failed.
2515 return _pywrapcp.SearchMonitor_AfterDecision(self, d, apply)
2518 r"""Just when the failure occurs."""
2519 return _pywrapcp.SearchMonitor_BeginFail(self)
2522 r"""After completing the backtrack."""
2523 return _pywrapcp.SearchMonitor_EndFail(self)
2526 r"""Before the initial propagation."""
2527 return _pywrapcp.SearchMonitor_BeginInitialPropagation(self)
2530 r"""After the initial propagation."""
2531 return _pywrapcp.SearchMonitor_EndInitialPropagation(self)
2535 This method is called when a solution is found. It asserts whether the
2536 solution is valid. A value of false indicates that the solution
2537 should be discarded.
2539 return _pywrapcp.SearchMonitor_AcceptSolution(self)
2543 This method is called when a valid solution is found. If the
2544 return value is true, then search will resume after. If the result
2545 is false, then search will stop there.
2547 return _pywrapcp.SearchMonitor_AtSolution(self)
2550 r"""When the search tree is finished."""
2551 return _pywrapcp.SearchMonitor_NoMoreSolutions(self)
2555 When a local optimum is reached. If 'true' is returned, the last solution
2556 is discarded and the search proceeds with the next one.
2558 return _pywrapcp.SearchMonitor_LocalOptimum(self)
2562 return _pywrapcp.SearchMonitor_AcceptDelta(self, delta, deltadelta)
2565 r"""After accepting a neighbor during local search."""
2566 return _pywrapcp.SearchMonitor_AcceptNeighbor(self)
2570 Returns a percentage representing the propress of the search before
2573 return _pywrapcp.SearchMonitor_ProgressPercent(self)
2576 return _pywrapcp.SearchMonitor_solver(self)
2579 return _pywrapcp.SearchMonitor___repr__(self)
2582 return _pywrapcp.SearchMonitor___str__(self)
2585 _pywrapcp.disown_SearchMonitor(self)
2586 return weakref.proxy(self)
2589_pywrapcp.SearchMonitor_swigregister(SearchMonitor)
2592 The class IntExpr is the base of all integer expressions in
2593 constraint programming.
2594 It contains the basic protocol for an expression:
2595 - setting and modifying its bound
2596 - querying if it is bound
2597 - listening to events modifying its bounds
2598 - casting it into a variable (instance of IntVar)
2601 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2604 raise AttributeError(
"No constructor defined - class is abstract")
2607 return _pywrapcp.IntExpr_Min(self)
2610 return _pywrapcp.IntExpr_SetMin(self, m)
2613 return _pywrapcp.IntExpr_Max(self)
2616 return _pywrapcp.IntExpr_SetMax(self, m)
2619 r"""This method sets both the min and the max of the expression."""
2620 return _pywrapcp.IntExpr_SetRange(self, l, u)
2623 r"""This method sets the value of the expression."""
2624 return _pywrapcp.IntExpr_SetValue(self, v)
2627 r"""Returns true if the min and the max of the expression are equal."""
2628 return _pywrapcp.IntExpr_Bound(self)
2631 r"""Returns true if the expression is indeed a variable."""
2632 return _pywrapcp.IntExpr_IsVar(self)
2635 r"""Creates a variable from the expression."""
2636 return _pywrapcp.IntExpr_Var(self)
2640 Creates a variable from the expression and set the name of the
2641 resulting var. If the expression is already a variable, then it
2642 will set the name of the expression, possibly overwriting it.
2643 This is just a shortcut to Var() followed by set_name().
2645 return _pywrapcp.IntExpr_VarWithName(self, name)
2650 Attach a demon that will watch the min or the max of the expression.
2655 Attach a demon that will watch the min or the max of the expression.
2657 return _pywrapcp.IntExpr_WhenRange(self, *args)
2660 return _pywrapcp.IntExpr___repr__(self)
2663 return _pywrapcp.IntExpr___str__(self)
2666 return _pywrapcp.IntExpr___add__(self, *args)
2669 return _pywrapcp.IntExpr___radd__(self, v)
2672 return _pywrapcp.IntExpr___sub__(self, *args)
2675 return _pywrapcp.IntExpr___rsub__(self, v)
2678 return _pywrapcp.IntExpr___mul__(self, *args)
2681 return _pywrapcp.IntExpr___rmul__(self, v)
2684 return _pywrapcp.IntExpr___floordiv__(self, *args)
2687 return _pywrapcp.IntExpr___mod__(self, *args)
2690 return _pywrapcp.IntExpr___neg__(self)
2693 return _pywrapcp.IntExpr___abs__(self)
2696 return _pywrapcp.IntExpr_Square(self)
2699 return _pywrapcp.IntExpr___eq__(self, *args)
2702 return _pywrapcp.IntExpr___ne__(self, *args)
2705 return _pywrapcp.IntExpr___ge__(self, *args)
2708 return _pywrapcp.IntExpr___gt__(self, *args)
2711 return _pywrapcp.IntExpr___le__(self, *args)
2714 return _pywrapcp.IntExpr___lt__(self, *args)
2717 return _pywrapcp.IntExpr_MapTo(self, vars)
2720 return _pywrapcp.IntExpr_IndexOf(self, *args)
2723 return _pywrapcp.IntExpr_IsMember(self, values)
2726 return _pywrapcp.IntExpr_Member(self, values)
2729 return _pywrapcp.IntExpr_NotMember(self, starts, ends)
2732_pywrapcp.IntExpr_swigregister(IntExpr)
2735 The class Iterator has two direct subclasses. HoleIterators
2736 iterates over all holes, that is value removed between the
2737 current min and max of the variable since the last time the
2738 variable was processed in the queue. DomainIterators iterates
2739 over all elements of the variable domain. Both iterators are not
2740 robust to domain changes. Hole iterators can also report values outside
2741 the current min and max of the variable.
2742 HoleIterators should only be called from a demon attached to the
2743 variable that has created this iterator.
2744 IntVar* current_var;
2745 std::unique_ptr<IntVarIterator> it(current_var->MakeHoleIterator(false));
2746 for (const int64_t hole : InitAndGetValues(it)) {
2751 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2754 raise AttributeError(
"No constructor defined - class is abstract")
2755 __repr__ = _swig_repr
2758 r"""This method must be called before each loop."""
2759 return _pywrapcp.IntVarIterator_Init(self)
2762 r"""This method indicates if we can call Value() or not."""
2763 return _pywrapcp.IntVarIterator_Ok(self)
2766 r"""This method returns the current value of the iterator."""
2767 return _pywrapcp.IntVarIterator_Value(self)
2770 r"""This method moves the iterator to the next value."""
2771 return _pywrapcp.IntVarIterator_Next(self)
2774 r"""Pretty Print."""
2775 return _pywrapcp.IntVarIterator_DebugString(self)
2783 result = self.
Value()
2787 raise StopIteration()
2794_pywrapcp.IntVarIterator_swigregister(IntVarIterator)
2797 The class IntVar is a subset of IntExpr. In addition to the
2798 IntExpr protocol, it offers persistence, removing values from the domains,
2799 and a finer model for events.
2802 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2805 raise AttributeError(
"No constructor defined - class is abstract")
2808 return _pywrapcp.IntVar_IsVar(self)
2811 return _pywrapcp.IntVar_Var(self)
2815 This method returns the value of the variable. This method checks
2816 before that the variable is bound.
2818 return _pywrapcp.IntVar_Value(self)
2821 r"""This method removes the value 'v' from the domain of the variable."""
2822 return _pywrapcp.IntVar_RemoveValue(self, v)
2826 This method removes the interval 'l' .. 'u' from the domain of
2827 the variable. It assumes that 'l' <= 'u'.
2829 return _pywrapcp.IntVar_RemoveInterval(self, l, u)
2832 r"""This method remove the values from the domain of the variable."""
2833 return _pywrapcp.IntVar_RemoveValues(self, values)
2836 r"""This method intersects the current domain with the values in the array."""
2837 return _pywrapcp.IntVar_SetValues(self, values)
2842 This method attaches a demon that will be awakened when the
2848 This method attaches a closure that will be awakened when the
2851 return _pywrapcp.IntVar_WhenBound(self, *args)
2856 This method attaches a demon that will watch any domain
2857 modification of the domain of the variable.
2862 This method attaches a closure that will watch any domain
2863 modification of the domain of the variable.
2865 return _pywrapcp.IntVar_WhenDomain(self, *args)
2868 r"""This method returns the number of values in the domain of the variable."""
2869 return _pywrapcp.IntVar_Size(self)
2873 This method returns whether the value 'v' is in the domain of the
2876 return _pywrapcp.IntVar_Contains(self, v)
2880 Creates a hole iterator. When 'reversible' is false, the returned
2881 object is created on the normal C++ heap and the solver does NOT
2882 take ownership of the object.
2884 return _pywrapcp.IntVar_HoleIteratorAux(self, reversible)
2888 Creates a domain iterator. When 'reversible' is false, the
2889 returned object is created on the normal C++ heap and the solver
2890 does NOT take ownership of the object.
2892 return _pywrapcp.IntVar_DomainIteratorAux(self, reversible)
2895 r"""Returns the previous min."""
2896 return _pywrapcp.IntVar_OldMin(self)
2899 r"""Returns the previous max."""
2900 return _pywrapcp.IntVar_OldMax(self)
2903 return _pywrapcp.IntVar___repr__(self)
2906 return _pywrapcp.IntVar___str__(self)
2916_pywrapcp.IntVar_swigregister(IntVar)
2919 This class is the root class of all solution collectors.
2920 It implements a basic query API to be used independently
2921 of the collector used.
2924 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
2927 raise AttributeError(
"No constructor defined")
2928 __repr__ = _swig_repr
2931 return _pywrapcp.SolutionCollector_DebugString(self)
2935 return _pywrapcp.SolutionCollector_Add(self, *args)
2938 return _pywrapcp.SolutionCollector_AddObjective(self, objective)
2941 r"""Beginning of the search."""
2942 return _pywrapcp.SolutionCollector_EnterSearch(self)
2945 r"""Returns how many solutions were stored during the search."""
2946 return _pywrapcp.SolutionCollector_SolutionCount(self)
2949 r"""Returns the nth solution."""
2950 return _pywrapcp.SolutionCollector_Solution(self, n)
2953 r"""Returns the wall time in ms for the nth solution."""
2954 return _pywrapcp.SolutionCollector_WallTime(self, n)
2957 r"""Returns the number of branches when the nth solution was found."""
2958 return _pywrapcp.SolutionCollector_Branches(self, n)
2962 Returns the number of failures encountered at the time of the nth
2965 return _pywrapcp.SolutionCollector_Failures(self, n)
2968 r"""Returns the objective value of the nth solution."""
2969 return _pywrapcp.SolutionCollector_ObjectiveValue(self, n)
2972 r"""This is a shortcut to get the Value of 'var' in the nth solution."""
2973 return _pywrapcp.SolutionCollector_Value(self, n, var)
2976 r"""This is a shortcut to get the StartValue of 'var' in the nth solution."""
2977 return _pywrapcp.SolutionCollector_StartValue(self, n, var)
2980 r"""This is a shortcut to get the EndValue of 'var' in the nth solution."""
2981 return _pywrapcp.SolutionCollector_EndValue(self, n, var)
2984 r"""This is a shortcut to get the DurationValue of 'var' in the nth solution."""
2985 return _pywrapcp.SolutionCollector_DurationValue(self, n, var)
2988 r"""This is a shortcut to get the PerformedValue of 'var' in the nth solution."""
2989 return _pywrapcp.SolutionCollector_PerformedValue(self, n, var)
2993 This is a shortcut to get the ForwardSequence of 'var' in the
2994 nth solution. The forward sequence is the list of ranked interval
2995 variables starting from the start of the sequence.
2997 return _pywrapcp.SolutionCollector_ForwardSequence(self, n, var)
3001 This is a shortcut to get the BackwardSequence of 'var' in the
3002 nth solution. The backward sequence is the list of ranked interval
3003 variables starting from the end of the sequence.
3005 return _pywrapcp.SolutionCollector_BackwardSequence(self, n, var)
3009 This is a shortcut to get the list of unperformed of 'var' in the
3012 return _pywrapcp.SolutionCollector_Unperformed(self, n, var)
3015_pywrapcp.SolutionCollector_swigregister(SolutionCollector)
3018 This class encapsulates an objective. It requires the direction
3019 (minimize or maximize), the variable to optimize, and the
3023 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3026 raise AttributeError(
"No constructor defined")
3027 __repr__ = _swig_repr
3030 r"""Returns the best value found during search."""
3031 return _pywrapcp.OptimizeVar_Best(self)
3034 r"""Internal methods."""
3035 return _pywrapcp.OptimizeVar_BeginNextDecision(self, db)
3038 return _pywrapcp.OptimizeVar_RefuteDecision(self, d)
3041 return _pywrapcp.OptimizeVar_AtSolution(self)
3044 return _pywrapcp.OptimizeVar_AcceptSolution(self)
3047 return _pywrapcp.OptimizeVar_DebugString(self)
3048 __swig_destroy__ = _pywrapcp.delete_OptimizeVar
3051_pywrapcp.OptimizeVar_swigregister(OptimizeVar)
3053 r"""Base class of all search limits."""
3055 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3058 raise AttributeError(
"No constructor defined - class is abstract")
3059 __repr__ = _swig_repr
3060 __swig_destroy__ = _pywrapcp.delete_SearchLimit
3063 r"""Returns true if the limit has been crossed."""
3064 return _pywrapcp.SearchLimit_Crossed(self)
3068 This method is called to check the status of the limit. A return
3069 value of true indicates that we have indeed crossed the limit. In
3070 that case, this method will not be called again and the remaining
3071 search will be discarded.
3073 return _pywrapcp.SearchLimit_Check(self)
3076 r"""This method is called when the search limit is initialized."""
3077 return _pywrapcp.SearchLimit_Init(self)
3080 r"""Internal methods."""
3081 return _pywrapcp.SearchLimit_EnterSearch(self)
3084 return _pywrapcp.SearchLimit_BeginNextDecision(self, b)
3087 return _pywrapcp.SearchLimit_RefuteDecision(self, d)
3090 return _pywrapcp.SearchLimit_DebugString(self)
3093_pywrapcp.SearchLimit_swigregister(SearchLimit)
3096 Interval variables are often used in scheduling. The main characteristics
3097 of an IntervalVar are the start position, duration, and end
3098 date. All these characteristics can be queried and set, and demons can
3099 be posted on their modifications.
3101 An important aspect is optionality: an IntervalVar can be performed or not.
3102 If unperformed, then it simply does not exist, and its characteristics
3103 cannot be accessed any more. An interval var is automatically marked
3104 as unperformed when it is not consistent anymore (start greater
3105 than end, duration < 0...)
3108 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3111 raise AttributeError(
"No constructor defined - class is abstract")
3115 These methods query, set, and watch the start position of the
3118 return _pywrapcp.IntervalVar_StartMin(self)
3121 return _pywrapcp.IntervalVar_StartMax(self)
3124 return _pywrapcp.IntervalVar_SetStartMin(self, m)
3127 return _pywrapcp.IntervalVar_SetStartMax(self, m)
3130 return _pywrapcp.IntervalVar_SetStartRange(self, mi, ma)
3133 return _pywrapcp.IntervalVar_OldStartMin(self)
3136 return _pywrapcp.IntervalVar_OldStartMax(self)
3139 return _pywrapcp.IntervalVar_WhenStartRange(self, *args)
3142 return _pywrapcp.IntervalVar_WhenStartBound(self, *args)
3145 r"""These methods query, set, and watch the duration of the interval var."""
3146 return _pywrapcp.IntervalVar_DurationMin(self)
3149 return _pywrapcp.IntervalVar_DurationMax(self)
3152 return _pywrapcp.IntervalVar_SetDurationMin(self, m)
3155 return _pywrapcp.IntervalVar_SetDurationMax(self, m)
3158 return _pywrapcp.IntervalVar_SetDurationRange(self, mi, ma)
3161 return _pywrapcp.IntervalVar_OldDurationMin(self)
3164 return _pywrapcp.IntervalVar_OldDurationMax(self)
3167 return _pywrapcp.IntervalVar_WhenDurationRange(self, *args)
3170 return _pywrapcp.IntervalVar_WhenDurationBound(self, *args)
3173 r"""These methods query, set, and watch the end position of the interval var."""
3174 return _pywrapcp.IntervalVar_EndMin(self)
3177 return _pywrapcp.IntervalVar_EndMax(self)
3180 return _pywrapcp.IntervalVar_SetEndMin(self, m)
3183 return _pywrapcp.IntervalVar_SetEndMax(self, m)
3186 return _pywrapcp.IntervalVar_SetEndRange(self, mi, ma)
3189 return _pywrapcp.IntervalVar_OldEndMin(self)
3192 return _pywrapcp.IntervalVar_OldEndMax(self)
3195 return _pywrapcp.IntervalVar_WhenEndRange(self, *args)
3198 return _pywrapcp.IntervalVar_WhenEndBound(self, *args)
3202 These methods query, set, and watch the performed status of the
3205 return _pywrapcp.IntervalVar_MustBePerformed(self)
3208 return _pywrapcp.IntervalVar_MayBePerformed(self)
3211 return _pywrapcp.IntervalVar_CannotBePerformed(self)
3214 return _pywrapcp.IntervalVar_IsPerformedBound(self)
3217 return _pywrapcp.IntervalVar_SetPerformed(self, val)
3220 return _pywrapcp.IntervalVar_WasPerformedBound(self)
3223 return _pywrapcp.IntervalVar_WhenPerformedBound(self, *args)
3228 Attaches a demon awakened when anything about this interval changes.
3233 Attaches a closure awakened when anything about this interval changes.
3235 return _pywrapcp.IntervalVar_WhenAnything(self, *args)
3239 These methods create expressions encapsulating the start, end
3240 and duration of the interval var. Please note that these must not
3241 be used if the interval var is unperformed.
3243 return _pywrapcp.IntervalVar_StartExpr(self)
3246 return _pywrapcp.IntervalVar_DurationExpr(self)
3249 return _pywrapcp.IntervalVar_EndExpr(self)
3252 return _pywrapcp.IntervalVar_PerformedExpr(self)
3256 These methods create expressions encapsulating the start, end
3257 and duration of the interval var. If the interval var is
3258 unperformed, they will return the unperformed_value.
3260 return _pywrapcp.IntervalVar_SafeStartExpr(self, unperformed_value)
3263 return _pywrapcp.IntervalVar_SafeDurationExpr(self, unperformed_value)
3266 return _pywrapcp.IntervalVar_SafeEndExpr(self, unperformed_value)
3269 return _pywrapcp.IntervalVar_EndsAfterEnd(self, other)
3272 return _pywrapcp.IntervalVar_EndsAfterEndWithDelay(self, other, delay)
3275 return _pywrapcp.IntervalVar_EndsAfterStart(self, other)
3278 return _pywrapcp.IntervalVar_EndsAfterStartWithDelay(self, other, delay)
3281 return _pywrapcp.IntervalVar_EndsAtEnd(self, other)
3284 return _pywrapcp.IntervalVar_EndsAtEndWithDelay(self, other, delay)
3287 return _pywrapcp.IntervalVar_EndsAtStart(self, other)
3290 return _pywrapcp.IntervalVar_EndsAtStartWithDelay(self, other, delay)
3293 return _pywrapcp.IntervalVar_StartsAfterEnd(self, other)
3296 return _pywrapcp.IntervalVar_StartsAfterEndWithDelay(self, other, delay)
3299 return _pywrapcp.IntervalVar_StartsAfterStart(self, other)
3302 return _pywrapcp.IntervalVar_StartsAfterStartWithDelay(self, other, delay)
3305 return _pywrapcp.IntervalVar_StartsAtEnd(self, other)
3308 return _pywrapcp.IntervalVar_StartsAtEndWithDelay(self, other, delay)
3311 return _pywrapcp.IntervalVar_StartsAtStart(self, other)
3314 return _pywrapcp.IntervalVar_StartsAtStartWithDelay(self, other, delay)
3317 return _pywrapcp.IntervalVar_StaysInSync(self, other)
3320 return _pywrapcp.IntervalVar_StaysInSyncWithDelay(self, other, delay)
3323 return _pywrapcp.IntervalVar_EndsAfter(self, date)
3326 return _pywrapcp.IntervalVar_EndsAt(self, date)
3329 return _pywrapcp.IntervalVar_EndsBefore(self, date)
3332 return _pywrapcp.IntervalVar_StartsAfter(self, date)
3335 return _pywrapcp.IntervalVar_StartsAt(self, date)
3338 return _pywrapcp.IntervalVar_StartsBefore(self, date)
3341 return _pywrapcp.IntervalVar_CrossesDate(self, date)
3344 return _pywrapcp.IntervalVar_AvoidsDate(self, date)
3347 return _pywrapcp.IntervalVar___repr__(self)
3350 return _pywrapcp.IntervalVar___str__(self)
3353_pywrapcp.IntervalVar_swigregister(IntervalVar)
3356 A sequence variable is a variable whose domain is a set of possible
3357 orderings of the interval variables. It allows ordering of tasks. It
3358 has two sets of methods: ComputePossibleFirstsAndLasts(), which
3359 returns the list of interval variables that can be ranked first or
3360 last; and RankFirst/RankNotFirst/RankLast/RankNotLast, which can be
3361 used to create the search decision.
3364 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3367 raise AttributeError(
"No constructor defined")
3370 return _pywrapcp.SequenceVar_DebugString(self)
3374 Ranks the index_th interval var first of all unranked interval
3375 vars. After that, it will no longer be considered ranked.
3377 return _pywrapcp.SequenceVar_RankFirst(self, index)
3381 Indicates that the index_th interval var will not be ranked first
3382 of all currently unranked interval vars.
3384 return _pywrapcp.SequenceVar_RankNotFirst(self, index)
3388 Ranks the index_th interval var first of all unranked interval
3389 vars. After that, it will no longer be considered ranked.
3391 return _pywrapcp.SequenceVar_RankLast(self, index)
3395 Indicates that the index_th interval var will not be ranked first
3396 of all currently unranked interval vars.
3398 return _pywrapcp.SequenceVar_RankNotLast(self, index)
3401 r"""Returns the index_th interval of the sequence."""
3402 return _pywrapcp.SequenceVar_Interval(self, index)
3405 r"""Returns the next of the index_th interval of the sequence."""
3406 return _pywrapcp.SequenceVar_Next(self, index)
3409 r"""Returns the number of interval vars in the sequence."""
3410 return _pywrapcp.SequenceVar_Size(self)
3413 return _pywrapcp.SequenceVar___repr__(self)
3416 return _pywrapcp.SequenceVar___str__(self)
3419_pywrapcp.SequenceVar_swigregister(SequenceVar)
3421 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3424 raise AttributeError(
"No constructor defined")
3425 __repr__ = _swig_repr
3428 return _pywrapcp.AssignmentElement_Activate(self)
3431 return _pywrapcp.AssignmentElement_Deactivate(self)
3434 return _pywrapcp.AssignmentElement_Activated(self)
3435 __swig_destroy__ = _pywrapcp.delete_AssignmentElement
3438_pywrapcp.AssignmentElement_swigregister(AssignmentElement)
3440 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3443 raise AttributeError(
"No constructor defined")
3444 __repr__ = _swig_repr
3447 return _pywrapcp.IntVarElement_Var(self)
3450 return _pywrapcp.IntVarElement_Min(self)
3453 return _pywrapcp.IntVarElement_SetMin(self, m)
3456 return _pywrapcp.IntVarElement_Max(self)
3459 return _pywrapcp.IntVarElement_SetMax(self, m)
3462 return _pywrapcp.IntVarElement_Value(self)
3465 return _pywrapcp.IntVarElement_Bound(self)
3468 return _pywrapcp.IntVarElement_SetRange(self, l, u)
3471 return _pywrapcp.IntVarElement_SetValue(self, v)
3474 return _pywrapcp.IntVarElement___eq__(self, element)
3477 return _pywrapcp.IntVarElement___ne__(self, element)
3478 __swig_destroy__ = _pywrapcp.delete_IntVarElement
3481_pywrapcp.IntVarElement_swigregister(IntVarElement)
3483 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3486 raise AttributeError(
"No constructor defined")
3487 __repr__ = _swig_repr
3490 return _pywrapcp.IntervalVarElement_Var(self)
3493 return _pywrapcp.IntervalVarElement_StartMin(self)
3496 return _pywrapcp.IntervalVarElement_StartMax(self)
3499 return _pywrapcp.IntervalVarElement_StartValue(self)
3502 return _pywrapcp.IntervalVarElement_DurationMin(self)
3505 return _pywrapcp.IntervalVarElement_DurationMax(self)
3508 return _pywrapcp.IntervalVarElement_DurationValue(self)
3511 return _pywrapcp.IntervalVarElement_EndMin(self)
3514 return _pywrapcp.IntervalVarElement_EndMax(self)
3517 return _pywrapcp.IntervalVarElement_EndValue(self)
3520 return _pywrapcp.IntervalVarElement_PerformedMin(self)
3523 return _pywrapcp.IntervalVarElement_PerformedMax(self)
3526 return _pywrapcp.IntervalVarElement_PerformedValue(self)
3529 return _pywrapcp.IntervalVarElement_SetStartMin(self, m)
3532 return _pywrapcp.IntervalVarElement_SetStartMax(self, m)
3535 return _pywrapcp.IntervalVarElement_SetStartRange(self, mi, ma)
3538 return _pywrapcp.IntervalVarElement_SetStartValue(self, v)
3541 return _pywrapcp.IntervalVarElement_SetDurationMin(self, m)
3544 return _pywrapcp.IntervalVarElement_SetDurationMax(self, m)
3547 return _pywrapcp.IntervalVarElement_SetDurationRange(self, mi, ma)
3550 return _pywrapcp.IntervalVarElement_SetDurationValue(self, v)
3553 return _pywrapcp.IntervalVarElement_SetEndMin(self, m)
3556 return _pywrapcp.IntervalVarElement_SetEndMax(self, m)
3559 return _pywrapcp.IntervalVarElement_SetEndRange(self, mi, ma)
3562 return _pywrapcp.IntervalVarElement_SetEndValue(self, v)
3565 return _pywrapcp.IntervalVarElement_SetPerformedMin(self, m)
3568 return _pywrapcp.IntervalVarElement_SetPerformedMax(self, m)
3571 return _pywrapcp.IntervalVarElement_SetPerformedRange(self, mi, ma)
3574 return _pywrapcp.IntervalVarElement_SetPerformedValue(self, v)
3577 return _pywrapcp.IntervalVarElement___eq__(self, element)
3580 return _pywrapcp.IntervalVarElement___ne__(self, element)
3581 __swig_destroy__ = _pywrapcp.delete_IntervalVarElement
3584_pywrapcp.IntervalVarElement_swigregister(IntervalVarElement)
3587 The SequenceVarElement stores a partial representation of ranked
3588 interval variables in the underlying sequence variable.
3589 This representation consists of three vectors:
3590 - the forward sequence. That is the list of interval variables
3591 ranked first in the sequence. The first element of the backward
3592 sequence is the first interval in the sequence variable.
3593 - the backward sequence. That is the list of interval variables
3594 ranked last in the sequence. The first element of the backward
3595 sequence is the last interval in the sequence variable.
3596 - The list of unperformed interval variables.
3597 Furthermore, if all performed variables are ranked, then by
3598 convention, the forward_sequence will contain all such variables
3599 and the backward_sequence will be empty.
3602 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3605 raise AttributeError(
"No constructor defined")
3606 __repr__ = _swig_repr
3609 return _pywrapcp.SequenceVarElement_Var(self)
3612 return _pywrapcp.SequenceVarElement_ForwardSequence(self)
3615 return _pywrapcp.SequenceVarElement_BackwardSequence(self)
3618 return _pywrapcp.SequenceVarElement_Unperformed(self)
3620 def SetSequence(self, forward_sequence, backward_sequence, unperformed):
3621 return _pywrapcp.SequenceVarElement_SetSequence(self, forward_sequence, backward_sequence, unperformed)
3624 return _pywrapcp.SequenceVarElement_SetForwardSequence(self, forward_sequence)
3627 return _pywrapcp.SequenceVarElement_SetBackwardSequence(self, backward_sequence)
3630 return _pywrapcp.SequenceVarElement_SetUnperformed(self, unperformed)
3633 return _pywrapcp.SequenceVarElement___eq__(self, element)
3636 return _pywrapcp.SequenceVarElement___ne__(self, element)
3637 __swig_destroy__ = _pywrapcp.delete_SequenceVarElement
3640_pywrapcp.SequenceVarElement_swigregister(SequenceVarElement)
3643 An Assignment is a variable -> domains mapping, used
3644 to report solutions to the user.
3647 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3650 raise AttributeError(
"No constructor defined")
3651 __repr__ = _swig_repr
3654 return _pywrapcp.Assignment_Clear(self)
3657 return _pywrapcp.Assignment_Empty(self)
3660 return _pywrapcp.Assignment_Size(self)
3663 return _pywrapcp.Assignment_NumIntVars(self)
3666 return _pywrapcp.Assignment_NumIntervalVars(self)
3669 return _pywrapcp.Assignment_NumSequenceVars(self)
3672 return _pywrapcp.Assignment_Store(self)
3675 return _pywrapcp.Assignment_Restore(self)
3679 Loads an assignment from a file; does not add variables to the
3680 assignment (only the variables contained in the assignment are modified).
3682 return _pywrapcp.Assignment_Load(self, *args)
3685 r"""Saves the assignment to a file."""
3686 return _pywrapcp.Assignment_Save(self, *args)
3689 return _pywrapcp.Assignment_AddObjective(self, v)
3692 return _pywrapcp.Assignment_Objective(self)
3695 return _pywrapcp.Assignment_HasObjective(self)
3698 return _pywrapcp.Assignment_ObjectiveMin(self)
3701 return _pywrapcp.Assignment_ObjectiveMax(self)
3704 return _pywrapcp.Assignment_ObjectiveValue(self)
3707 return _pywrapcp.Assignment_ObjectiveBound(self)
3710 return _pywrapcp.Assignment_SetObjectiveMin(self, m)
3713 return _pywrapcp.Assignment_SetObjectiveMax(self, m)
3716 return _pywrapcp.Assignment_SetObjectiveValue(self, value)
3719 return _pywrapcp.Assignment_SetObjectiveRange(self, l, u)
3722 return _pywrapcp.Assignment_Min(self, var)
3725 return _pywrapcp.Assignment_Max(self, var)
3728 return _pywrapcp.Assignment_Value(self, var)
3731 return _pywrapcp.Assignment_Bound(self, var)
3734 return _pywrapcp.Assignment_SetMin(self, var, m)
3737 return _pywrapcp.Assignment_SetMax(self, var, m)
3740 return _pywrapcp.Assignment_SetRange(self, var, l, u)
3743 return _pywrapcp.Assignment_SetValue(self, var, value)
3746 return _pywrapcp.Assignment_StartMin(self, var)
3749 return _pywrapcp.Assignment_StartMax(self, var)
3752 return _pywrapcp.Assignment_StartValue(self, var)
3755 return _pywrapcp.Assignment_DurationMin(self, var)
3758 return _pywrapcp.Assignment_DurationMax(self, var)
3761 return _pywrapcp.Assignment_DurationValue(self, var)
3764 return _pywrapcp.Assignment_EndMin(self, var)
3767 return _pywrapcp.Assignment_EndMax(self, var)
3770 return _pywrapcp.Assignment_EndValue(self, var)
3773 return _pywrapcp.Assignment_PerformedMin(self, var)
3776 return _pywrapcp.Assignment_PerformedMax(self, var)
3779 return _pywrapcp.Assignment_PerformedValue(self, var)
3782 return _pywrapcp.Assignment_SetStartMin(self, var, m)
3785 return _pywrapcp.Assignment_SetStartMax(self, var, m)
3788 return _pywrapcp.Assignment_SetStartRange(self, var, mi, ma)
3791 return _pywrapcp.Assignment_SetStartValue(self, var, value)
3794 return _pywrapcp.Assignment_SetDurationMin(self, var, m)
3797 return _pywrapcp.Assignment_SetDurationMax(self, var, m)
3800 return _pywrapcp.Assignment_SetDurationRange(self, var, mi, ma)
3803 return _pywrapcp.Assignment_SetDurationValue(self, var, value)
3806 return _pywrapcp.Assignment_SetEndMin(self, var, m)
3809 return _pywrapcp.Assignment_SetEndMax(self, var, m)
3812 return _pywrapcp.Assignment_SetEndRange(self, var, mi, ma)
3815 return _pywrapcp.Assignment_SetEndValue(self, var, value)
3818 return _pywrapcp.Assignment_SetPerformedMin(self, var, m)
3821 return _pywrapcp.Assignment_SetPerformedMax(self, var, m)
3824 return _pywrapcp.Assignment_SetPerformedRange(self, var, mi, ma)
3827 return _pywrapcp.Assignment_SetPerformedValue(self, var, value)
3830 return _pywrapcp.Assignment_Add(self, *args)
3833 return _pywrapcp.Assignment_ForwardSequence(self, var)
3836 return _pywrapcp.Assignment_BackwardSequence(self, var)
3839 return _pywrapcp.Assignment_Unperformed(self, var)
3841 def SetSequence(self, var, forward_sequence, backward_sequence, unperformed):
3842 return _pywrapcp.Assignment_SetSequence(self, var, forward_sequence, backward_sequence, unperformed)
3845 return _pywrapcp.Assignment_SetForwardSequence(self, var, forward_sequence)
3848 return _pywrapcp.Assignment_SetBackwardSequence(self, var, backward_sequence)
3851 return _pywrapcp.Assignment_SetUnperformed(self, var, unperformed)
3854 return _pywrapcp.Assignment_Activate(self, *args)
3857 return _pywrapcp.Assignment_Deactivate(self, *args)
3860 return _pywrapcp.Assignment_Activated(self, *args)
3863 return _pywrapcp.Assignment_DebugString(self)
3866 return _pywrapcp.Assignment_IntVarContainer(self)
3869 return _pywrapcp.Assignment_MutableIntVarContainer(self)
3872 return _pywrapcp.Assignment_IntervalVarContainer(self)
3875 return _pywrapcp.Assignment_MutableIntervalVarContainer(self)
3878 return _pywrapcp.Assignment_SequenceVarContainer(self)
3881 return _pywrapcp.Assignment_MutableSequenceVarContainer(self)
3884 return _pywrapcp.Assignment___eq__(self, assignment)
3887 return _pywrapcp.Assignment___ne__(self, assignment)
3890_pywrapcp.Assignment_swigregister(Assignment)
3893 return _pywrapcp.__lshift__(*args)
3895 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3898 raise AttributeError(
"No constructor defined")
3899 __repr__ = _swig_repr
3904 Dimensions are additional constraints than can restrict what is
3905 possible with the pack constraint. It can be used to set capacity
3906 limits, to count objects per bin, to compute unassigned
3908 This dimension imposes that for all bins b, the weighted sum
3909 (weights[i]) of all objects i assigned to 'b' is less or equal
3915 This dimension imposes that for all bins b, the weighted sum
3916 (weights->Run(i)) of all objects i assigned to 'b' is less or
3917 equal to 'bounds[b]'. Ownership of the callback is transferred to
3918 the pack constraint.
3923 This dimension imposes that for all bins b, the weighted sum
3924 (weights->Run(i, b) of all objects i assigned to 'b' is less or
3925 equal to 'bounds[b]'. Ownership of the callback is transferred to
3926 the pack constraint.
3928 return _pywrapcp.Pack_AddWeightedSumLessOrEqualConstantDimension(self, *args)
3933 This dimension imposes that for all bins b, the weighted sum
3934 (weights[i]) of all objects i assigned to 'b' is equal to loads[b].
3939 This dimension imposes that for all bins b, the weighted sum
3940 (weights->Run(i, b)) of all objects i assigned to 'b' is equal to
3943 return _pywrapcp.Pack_AddWeightedSumEqualVarDimension(self, *args)
3947 This dimension imposes:
3949 sum (i in items: usage[i] * is_assigned(i, b)) <= capacity[b]
3950 where is_assigned(i, b) is true if and only if item i is assigned
3953 This can be used to model shapes of items by linking variables of
3954 the same item on parallel dimensions with an allowed assignment
3957 return _pywrapcp.Pack_AddSumVariableWeightsLessOrEqualConstantDimension(self, usage, capacity)
3961 This dimension enforces that cost_var == sum of weights[i] for
3962 all objects 'i' assigned to a bin.
3964 return _pywrapcp.Pack_AddWeightedSumOfAssignedDimension(self, weights, cost_var)
3968 This dimension links 'count_var' to the actual number of bins used in the
3971 return _pywrapcp.Pack_AddCountUsedBinDimension(self, count_var)
3975 This dimension links 'count_var' to the actual number of items
3976 assigned to a bin in the pack.
3978 return _pywrapcp.Pack_AddCountAssignedItemsDimension(self, count_var)
3981 return _pywrapcp.Pack_Post(self)
3984 return _pywrapcp.Pack_InitialPropagateWrapper(self)
3987 return _pywrapcp.Pack_DebugString(self)
3990_pywrapcp.Pack_swigregister(Pack)
3992 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
3995 raise AttributeError(
"No constructor defined - class is abstract")
3996 __repr__ = _swig_repr
3999 r"""Creates a sequence variable from the constraint."""
4000 return _pywrapcp.DisjunctiveConstraint_SequenceVar(self)
4004 Add a transition time between intervals. It forces the distance between
4005 the end of interval a and start of interval b that follows it to be at
4006 least transition_time(a, b). This function must always return
4007 a positive or null value.
4009 return _pywrapcp.DisjunctiveConstraint_SetTransitionTime(self, transition_time)
4012 return _pywrapcp.DisjunctiveConstraint_TransitionTime(self, before_index, after_index)
4015_pywrapcp.DisjunctiveConstraint_swigregister(DisjunctiveConstraint)
4018 This class adds reversibility to a POD type.
4019 It contains the stamp optimization. i.e. the SaveValue call is done
4020 only once per node of the search tree. Please note that actual
4021 stamps always starts at 1, thus an initial value of 0 will always
4022 trigger the first SaveValue.
4025 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4026 __repr__ = _swig_repr
4029 _pywrapcp.RevInteger_swiginit(self, _pywrapcp.new_RevInteger(val))
4032 return _pywrapcp.RevInteger_Value(self)
4035 return _pywrapcp.RevInteger_SetValue(self, s, val)
4036 __swig_destroy__ = _pywrapcp.delete_RevInteger
4039_pywrapcp.RevInteger_swigregister(RevInteger)
4041 r"""Subclass of Rev<T> which adds numerical operations."""
4043 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4044 __repr__ = _swig_repr
4047 _pywrapcp.NumericalRevInteger_swiginit(self, _pywrapcp.new_NumericalRevInteger(val))
4050 return _pywrapcp.NumericalRevInteger_Add(self, s, to_add)
4053 return _pywrapcp.NumericalRevInteger_Incr(self, s)
4056 return _pywrapcp.NumericalRevInteger_Decr(self, s)
4057 __swig_destroy__ = _pywrapcp.delete_NumericalRevInteger
4060_pywrapcp.NumericalRevInteger_swigregister(NumericalRevInteger)
4063 This class adds reversibility to a POD type.
4064 It contains the stamp optimization. i.e. the SaveValue call is done
4065 only once per node of the search tree. Please note that actual
4066 stamps always starts at 1, thus an initial value of 0 will always
4067 trigger the first SaveValue.
4070 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4071 __repr__ = _swig_repr
4074 _pywrapcp.RevBool_swiginit(self, _pywrapcp.new_RevBool(val))
4077 return _pywrapcp.RevBool_Value(self)
4080 return _pywrapcp.RevBool_SetValue(self, s, val)
4081 __swig_destroy__ = _pywrapcp.delete_RevBool
4084_pywrapcp.RevBool_swigregister(RevBool)
4086 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4089 raise AttributeError(
"No constructor defined")
4090 __repr__ = _swig_repr
4093 return _pywrapcp.IntVarContainer_Contains(self, var)
4096 return _pywrapcp.IntVarContainer_Element(self, index)
4099 return _pywrapcp.IntVarContainer_Size(self)
4102 return _pywrapcp.IntVarContainer_Store(self)
4105 return _pywrapcp.IntVarContainer_Restore(self)
4109 Returns true if this and 'container' both represent the same V* -> E map.
4110 Runs in linear time; requires that the == operator on the type E is well
4113 return _pywrapcp.IntVarContainer___eq__(self, container)
4116 return _pywrapcp.IntVarContainer___ne__(self, container)
4117 __swig_destroy__ = _pywrapcp.delete_IntVarContainer
4120_pywrapcp.IntVarContainer_swigregister(IntVarContainer)
4122 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4125 raise AttributeError(
"No constructor defined")
4126 __repr__ = _swig_repr
4129 return _pywrapcp.IntervalVarContainer_Contains(self, var)
4132 return _pywrapcp.IntervalVarContainer_Element(self, index)
4135 return _pywrapcp.IntervalVarContainer_Size(self)
4138 return _pywrapcp.IntervalVarContainer_Store(self)
4141 return _pywrapcp.IntervalVarContainer_Restore(self)
4145 Returns true if this and 'container' both represent the same V* -> E map.
4146 Runs in linear time; requires that the == operator on the type E is well
4149 return _pywrapcp.IntervalVarContainer___eq__(self, container)
4152 return _pywrapcp.IntervalVarContainer___ne__(self, container)
4153 __swig_destroy__ = _pywrapcp.delete_IntervalVarContainer
4156_pywrapcp.IntervalVarContainer_swigregister(IntervalVarContainer)
4158 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4161 raise AttributeError(
"No constructor defined")
4162 __repr__ = _swig_repr
4165 return _pywrapcp.SequenceVarContainer_Contains(self, var)
4168 return _pywrapcp.SequenceVarContainer_Element(self, index)
4171 return _pywrapcp.SequenceVarContainer_Size(self)
4174 return _pywrapcp.SequenceVarContainer_Store(self)
4177 return _pywrapcp.SequenceVarContainer_Restore(self)
4181 Returns true if this and 'container' both represent the same V* -> E map.
4182 Runs in linear time; requires that the == operator on the type E is well
4185 return _pywrapcp.SequenceVarContainer___eq__(self, container)
4188 return _pywrapcp.SequenceVarContainer___ne__(self, container)
4189 __swig_destroy__ = _pywrapcp.delete_SequenceVarContainer
4192_pywrapcp.SequenceVarContainer_swigregister(SequenceVarContainer)
4195 The base class for all local search operators.
4197 A local search operator is an object that defines the neighborhood of a
4198 solution. In other words, a neighborhood is the set of solutions which can
4199 be reached from a given solution using an operator.
4201 The behavior of the LocalSearchOperator class is similar to iterators.
4202 The operator is synchronized with an assignment (gives the
4203 current values of the variables); this is done in the Start() method.
4205 Then one can iterate over the neighbors using the MakeNextNeighbor method.
4206 This method returns an assignment which represents the incremental changes
4207 to the current solution. It also returns a second assignment representing
4208 the changes to the last solution defined by the neighborhood operator; this
4209 assignment is empty if the neighborhood operator cannot track this
4213 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4216 raise AttributeError(
"No constructor defined - class is abstract")
4217 __repr__ = _swig_repr
4220 return _pywrapcp.LocalSearchOperator_NextNeighbor(self, delta, deltadelta)
4223 return _pywrapcp.LocalSearchOperator_Start(self, assignment)
4226 _pywrapcp.disown_LocalSearchOperator(self)
4227 return weakref.proxy(self)
4230_pywrapcp.LocalSearchOperator_swigregister(LocalSearchOperator)
4233 Specialization of LocalSearchOperator built from an array of IntVars
4234 which specifies the scope of the operator.
4235 This class also takes care of storing current variable values in Start(),
4236 keeps track of changes done by the operator and builds the delta.
4237 The Deactivate() method can be used to perform Large Neighborhood Search.
4240 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4241 __repr__ = _swig_repr
4244 if self.
__class__ == IntVarLocalSearchOperator:
4248 _pywrapcp.IntVarLocalSearchOperator_swiginit(self, _pywrapcp.new_IntVarLocalSearchOperator(_self, vars, keep_inverse_values))
4249 __swig_destroy__ = _pywrapcp.delete_IntVarLocalSearchOperator
4253 This method should not be overridden. Override OnStart() instead which is
4254 called before exiting this method.
4256 return _pywrapcp.IntVarLocalSearchOperator_Start(self, assignment)
4259 return _pywrapcp.IntVarLocalSearchOperator_IsIncremental(self)
4262 return _pywrapcp.IntVarLocalSearchOperator_Size(self)
4266 Returns the value in the current assignment of the variable of given
4269 return _pywrapcp.IntVarLocalSearchOperator_Value(self, index)
4272 r"""Returns the variable of given index."""
4273 return _pywrapcp.IntVarLocalSearchOperator_Var(self, index)
4276 return _pywrapcp.IntVarLocalSearchOperator_OldValue(self, index)
4279 return _pywrapcp.IntVarLocalSearchOperator_PrevValue(self, index)
4282 return _pywrapcp.IntVarLocalSearchOperator_SetValue(self, index, value)
4285 return _pywrapcp.IntVarLocalSearchOperator_Activated(self, index)
4288 return _pywrapcp.IntVarLocalSearchOperator_Activate(self, index)
4291 return _pywrapcp.IntVarLocalSearchOperator_Deactivate(self, index)
4294 return _pywrapcp.IntVarLocalSearchOperator_AddVars(self, vars)
4298 Called by Start() after synchronizing the operator with the current
4299 assignment. Should be overridden instead of Start() to avoid calling
4300 IntVarLocalSearchOperator::Start explicitly.
4302 return _pywrapcp.IntVarLocalSearchOperator_OnStart(self)
4306 OnStart() should really be protected, but then SWIG doesn't see it. So we
4307 make it public, but only subclasses should access to it (to override it).
4308 Redefines MakeNextNeighbor to export a simpler interface. The calls to
4309 ApplyChanges() and RevertChanges() are factored in this method, hiding
4310 both delta and deltadelta from subclasses which only need to override
4312 Therefore this method should not be overridden. Override MakeOneNeighbor()
4315 return _pywrapcp.IntVarLocalSearchOperator_NextNeighbor(self, delta, deltadelta)
4319 Creates a new neighbor. It returns false when the neighborhood is
4320 completely explored.
4321 MakeNextNeighbor() in a subclass of IntVarLocalSearchOperator.
4323 return _pywrapcp.IntVarLocalSearchOperator_OneNeighbor(self)
4326 _pywrapcp.disown_IntVarLocalSearchOperator(self)
4327 return weakref.proxy(self)
4330_pywrapcp.IntVarLocalSearchOperator_swigregister(IntVarLocalSearchOperator)
4333 This is the base class for building an Lns operator. An Lns fragment is a
4334 collection of variables which will be relaxed. Fragments are built with
4335 NextFragment(), which returns false if there are no more fragments to build.
4336 Optionally one can override InitFragments, which is called from
4337 LocalSearchOperator::Start to initialize fragment data.
4339 Here's a sample relaxing one variable at a time:
4341 class OneVarLns : public BaseLns {
4343 OneVarLns(const std::vector<IntVar*>& vars) : BaseLns(vars), index_(0) {}
4344 virtual ~OneVarLns() {}
4345 virtual void InitFragments() { index_ = 0; }
4346 virtual bool NextFragment() {
4347 const int size = Size();
4348 if (index_ < size) {
4349 AppendToFragment(index_);
4362 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4363 __repr__ = _swig_repr
4370 _pywrapcp.BaseLns_swiginit(self, _pywrapcp.new_BaseLns(_self, vars))
4371 __swig_destroy__ = _pywrapcp.delete_BaseLns
4374 return _pywrapcp.BaseLns_InitFragments(self)
4377 return _pywrapcp.BaseLns_NextFragment(self)
4380 return _pywrapcp.BaseLns_AppendToFragment(self, index)
4383 return _pywrapcp.BaseLns_FragmentSize(self)
4386 return _pywrapcp.BaseLns___getitem__(self, index)
4389 return _pywrapcp.BaseLns___len__(self)
4392 _pywrapcp.disown_BaseLns(self)
4393 return weakref.proxy(self)
4396_pywrapcp.BaseLns_swigregister(BaseLns)
4399 Defines operators which change the value of variables;
4400 each neighbor corresponds to *one* modified variable.
4401 Sub-classes have to define ModifyValue which determines what the new
4402 variable value is going to be (given the current value and the variable).
4405 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4406 __repr__ = _swig_repr
4413 _pywrapcp.ChangeValue_swiginit(self, _pywrapcp.new_ChangeValue(_self, vars))
4414 __swig_destroy__ = _pywrapcp.delete_ChangeValue
4417 return _pywrapcp.ChangeValue_ModifyValue(self, index, value)
4420 r"""This method should not be overridden. Override ModifyValue() instead."""
4421 return _pywrapcp.ChangeValue_OneNeighbor(self)
4424 _pywrapcp.disown_ChangeValue(self)
4425 return weakref.proxy(self)
4428_pywrapcp.ChangeValue_swigregister(ChangeValue)
4431 Local Search Filters are used for fast neighbor pruning.
4432 Filtering a move is done in several phases:
4433 - in the Relax phase, filters determine which parts of their internals
4434 will be changed by the candidate, and modify intermediary State
4435 - in the Accept phase, filters check that the candidate is feasible,
4436 - if the Accept phase succeeds, the solver may decide to trigger a
4437 Synchronize phase that makes filters change their internal representation
4438 to the last candidate,
4439 - otherwise (Accept fails or the solver does not want to synchronize),
4440 a Revert phase makes filters erase any intermediary State generated by the
4441 Relax and Accept phases.
4442 A given filter has phases called with the following pattern:
4443 (Relax.Accept.Synchronize | Relax.Accept.Revert | Relax.Revert)*.
4444 Filters's Revert() is always called in the reverse order their Accept() was
4445 called, to allow late filters to use state done/undone by early filters'
4449 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4452 raise AttributeError(
"No constructor defined - class is abstract")
4453 __repr__ = _swig_repr
4455 def Accept(self, delta, deltadelta, objective_min, objective_max):
4457 Accepts a "delta" given the assignment with which the filter has been
4458 synchronized; the delta holds the variables which have been modified and
4460 If the filter represents a part of the global objective, its contribution
4461 must be between objective_min and objective_max.
4462 Sample: supposing one wants to maintain a[0,1] + b[0,1] <= 1,
4463 for the assignment (a,1), (b,0), the delta (b,1) will be rejected
4464 but the delta (a,0) will be accepted.
4465 TODO(user): Remove arguments when there are no more need for those.
4467 return _pywrapcp.LocalSearchFilter_Accept(self, delta, deltadelta, objective_min, objective_max)
4470 return _pywrapcp.LocalSearchFilter_IsIncremental(self)
4474 Synchronizes the filter with the current solution, delta being the
4475 difference with the solution passed to the previous call to Synchronize()
4476 or IncrementalSynchronize(). 'delta' can be used to incrementally
4477 synchronizing the filter with the new solution by only considering the
4480 return _pywrapcp.LocalSearchFilter_Synchronize(self, assignment, delta)
4481 __swig_destroy__ = _pywrapcp.delete_LocalSearchFilter
4484_pywrapcp.LocalSearchFilter_swigregister(LocalSearchFilter)
4487 Filter manager: when a move is made, filters are executed to decide whether
4488 the solution is feasible and compute parts of the new cost. This class
4489 schedules filter execution and composes costs as a sum.
4492 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4493 __repr__ = _swig_repr
4496 return _pywrapcp.LocalSearchFilterManager_DebugString(self)
4499 _pywrapcp.LocalSearchFilterManager_swiginit(self, _pywrapcp.new_LocalSearchFilterManager(*args))
4501 def Accept(self, monitor, delta, deltadelta, objective_min, objective_max):
4503 Returns true iff all filters return true, and the sum of their accepted
4504 objectives is between objective_min and objective_max.
4505 The monitor has its Begin/EndFiltering events triggered.
4507 return _pywrapcp.LocalSearchFilterManager_Accept(self, monitor, delta, deltadelta, objective_min, objective_max)
4510 r"""Synchronizes all filters to assignment."""
4511 return _pywrapcp.LocalSearchFilterManager_Synchronize(self, assignment, delta)
4512 __swig_destroy__ = _pywrapcp.delete_LocalSearchFilterManager
4515_pywrapcp.LocalSearchFilterManager_swigregister(LocalSearchFilterManager)
4517 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4518 __repr__ = _swig_repr
4521 if self.
__class__ == IntVarLocalSearchFilter:
4525 _pywrapcp.IntVarLocalSearchFilter_swiginit(self, _pywrapcp.new_IntVarLocalSearchFilter(_self, vars))
4526 __swig_destroy__ = _pywrapcp.delete_IntVarLocalSearchFilter
4530 This method should not be overridden. Override OnSynchronize() instead
4531 which is called before exiting this method.
4533 return _pywrapcp.IntVarLocalSearchFilter_Synchronize(self, assignment, delta)
4536 return _pywrapcp.IntVarLocalSearchFilter_Size(self)
4539 return _pywrapcp.IntVarLocalSearchFilter_Value(self, index)
4542 return _pywrapcp.IntVarLocalSearchFilter_IndexFromVar(self, var)
4545 _pywrapcp.disown_IntVarLocalSearchFilter(self)
4546 return weakref.proxy(self)
4549_pywrapcp.IntVarLocalSearchFilter_swigregister(IntVarLocalSearchFilter)
4551 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4554 raise AttributeError(
"No constructor defined - class is abstract")
4555 __repr__ = _swig_repr
4558 return _pywrapcp.BooleanVar_Min(self)
4561 return _pywrapcp.BooleanVar_SetMin(self, m)
4564 return _pywrapcp.BooleanVar_Max(self)
4567 return _pywrapcp.BooleanVar_SetMax(self, m)
4570 return _pywrapcp.BooleanVar_SetRange(self, mi, ma)
4573 return _pywrapcp.BooleanVar_Bound(self)
4576 return _pywrapcp.BooleanVar_Value(self)
4579 return _pywrapcp.BooleanVar_RemoveValue(self, v)
4582 return _pywrapcp.BooleanVar_RemoveInterval(self, l, u)
4585 return _pywrapcp.BooleanVar_WhenBound(self, d)
4588 return _pywrapcp.BooleanVar_WhenRange(self, d)
4591 return _pywrapcp.BooleanVar_WhenDomain(self, d)
4594 return _pywrapcp.BooleanVar_Size(self)
4597 return _pywrapcp.BooleanVar_Contains(self, v)
4600 return _pywrapcp.BooleanVar_HoleIteratorAux(self, reversible)
4603 return _pywrapcp.BooleanVar_DomainIteratorAux(self, reversible)
4606 return _pywrapcp.BooleanVar_DebugString(self)
4609_pywrapcp.BooleanVar_swigregister(BooleanVar)
4615 except Exception
as e:
4616 if 'CP Solver fail' in str(e):
4624 except Exception
as e:
4625 if 'CP Solver fail' in str(e):
4637 return self.Next(solver)
4638 except Exception
as e:
4639 if 'CP Solver fail' in str(e):
4640 return solver.FailDecision()
4645 return "PyDecisionBuilder"
4652 except Exception
as e:
4653 if 'CP Solver fail' in str(e):
4674 return Solver.DELAYED_PRIORITY
if self.
__delayed else Solver.NORMAL_PRIORITY
4677 return 'PyConstraintDemon'
4696 return self.
solver().ConstraintInitialPropagateCallback(self)
4699 return self.
solver().DelayedConstraintInitialPropagateCallback(self)
4703 self.InitialPropagate()
4704 except Exception
as e:
4705 if 'CP Solver fail' in str(e):
4706 self.
solver().ShouldFail()
4711 return "PyConstraint"
4715 Manager for any NodeIndex <-> variable index conversion. The routing solver
4716 uses variable indices internally and through its API. These variable indices
4717 are tricky to manage directly because one Node can correspond to a multitude
4718 of variables, depending on the number of times they appear in the model, and
4719 if they're used as start and/or end points. This class aims to simplify
4720 variable index usage, allowing users to use NodeIndex instead.
4726 auto starts_ends = ...; /// These are NodeIndex.
4727 RoutingIndexManager manager(10, 4, starts_ends); // 10 nodes, 4 vehicles.
4728 RoutingModel model(manager);
4730 Then, use 'manager.NodeToIndex(node)' whenever model requires a variable
4733 Note: the mapping between node indices and variables indices is subject to
4734 change so no assumption should be made on it. The only guarantee is that
4735 indices range between 0 and n-1, where n = number of vehicles * 2 (for start
4736 and end nodes) + number of non-start or end nodes.
4739 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4740 __repr__ = _swig_repr
4744 Creates a NodeIndex to variable index mapping for a problem containing
4745 'num_nodes', 'num_vehicles' and the given starts and ends for each
4746 vehicle. If used, any start/end arrays have to have exactly 'num_vehicles'
4749 _pywrapcp.RoutingIndexManager_swiginit(self, _pywrapcp.new_RoutingIndexManager(*args))
4752 return _pywrapcp.RoutingIndexManager_GetNumberOfNodes(self)
4755 return _pywrapcp.RoutingIndexManager_GetNumberOfVehicles(self)
4758 return _pywrapcp.RoutingIndexManager_GetNumberOfIndices(self)
4761 return _pywrapcp.RoutingIndexManager_GetStartIndex(self, vehicle)
4764 return _pywrapcp.RoutingIndexManager_GetEndIndex(self, vehicle)
4767 return _pywrapcp.RoutingIndexManager_NodeToIndex(self, node)
4770 return _pywrapcp.RoutingIndexManager_IndexToNode(self, index)
4771 __swig_destroy__ = _pywrapcp.delete_RoutingIndexManager
4774_pywrapcp.RoutingIndexManager_swigregister(RoutingIndexManager)
4777 return _pywrapcp.DefaultRoutingModelParameters()
4780 return _pywrapcp.DefaultRoutingSearchParameters()
4784 Returns an empty std::string if the routing search parameters are valid, and
4785 a non-empty, human readable error description if they're not.
4787 return _pywrapcp.FindErrorInRoutingSearchParameters(search_parameters)
4788BOOL_UNSPECIFIED = _pywrapcp.BOOL_UNSPECIFIED
4789BOOL_FALSE = _pywrapcp.BOOL_FALSE
4790BOOL_TRUE = _pywrapcp.BOOL_TRUE
4792 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4793 __repr__ = _swig_repr
4796 _pywrapcp.FirstSolutionStrategy_swiginit(self, _pywrapcp.new_FirstSolutionStrategy())
4797 __swig_destroy__ = _pywrapcp.delete_FirstSolutionStrategy
4800_pywrapcp.FirstSolutionStrategy_swigregister(FirstSolutionStrategy)
4802 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4803 __repr__ = _swig_repr
4806 _pywrapcp.LocalSearchMetaheuristic_swiginit(self, _pywrapcp.new_LocalSearchMetaheuristic())
4807 __swig_destroy__ = _pywrapcp.delete_LocalSearchMetaheuristic
4810_pywrapcp.LocalSearchMetaheuristic_swigregister(LocalSearchMetaheuristic)
4812 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4813 __repr__ = _swig_repr
4816 _pywrapcp.RoutingSearchStatus_swiginit(self, _pywrapcp.new_RoutingSearchStatus())
4817 __swig_destroy__ = _pywrapcp.delete_RoutingSearchStatus
4820_pywrapcp.RoutingSearchStatus_swigregister(RoutingSearchStatus)
4822 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4823 __repr__ = _swig_repr
4826 _pywrapcp.PathsMetadata_swiginit(self, _pywrapcp.new_PathsMetadata(manager))
4829 return _pywrapcp.PathsMetadata_IsStart(self, node)
4832 return _pywrapcp.PathsMetadata_IsEnd(self, node)
4835 return _pywrapcp.PathsMetadata_GetPath(self, start_or_end_node)
4838 return _pywrapcp.PathsMetadata_NumPaths(self)
4841 return _pywrapcp.PathsMetadata_Paths(self)
4844 return _pywrapcp.PathsMetadata_Starts(self)
4847 return _pywrapcp.PathsMetadata_Start(self, path)
4850 return _pywrapcp.PathsMetadata_End(self, path)
4853 return _pywrapcp.PathsMetadata_Ends(self)
4854 __swig_destroy__ = _pywrapcp.delete_PathsMetadata
4857_pywrapcp.PathsMetadata_swigregister(PathsMetadata)
4859 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
4860 __repr__ = _swig_repr
4861 PICKUP_AND_DELIVERY_NO_ORDER = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_NO_ORDER
4862 r"""Any precedence is accepted."""
4863 PICKUP_AND_DELIVERY_LIFO = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_LIFO
4864 r"""Deliveries must be performed in reverse order of pickups."""
4865 PICKUP_AND_DELIVERY_FIFO = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_FIFO
4866 r"""Deliveries must be performed in the same order as pickups."""
4870 Constructor taking an index manager. The version which does not take
4871 RoutingModelParameters is equivalent to passing
4872 DefaultRoutingModelParameters().
4874 _pywrapcp.RoutingModel_swiginit(self, _pywrapcp.new_RoutingModel(*args))
4875 __swig_destroy__ = _pywrapcp.delete_RoutingModel
4876 kTransitEvaluatorSignUnknown = _pywrapcp.RoutingModel_kTransitEvaluatorSignUnknown
4877 kTransitEvaluatorSignPositiveOrZero = _pywrapcp.RoutingModel_kTransitEvaluatorSignPositiveOrZero
4878 kTransitEvaluatorSignNegativeOrZero = _pywrapcp.RoutingModel_kTransitEvaluatorSignNegativeOrZero
4882 Registers 'callback' and returns its index.
4883 The sign parameter allows to notify the solver that the callback only
4884 return values of the given sign. This can help the solver, but passing
4885 an incorrect sign may crash in non-opt compilation mode, and yield
4886 incorrect results in opt.
4888 return _pywrapcp.RoutingModel_RegisterUnaryTransitVector(self, values)
4891 return _pywrapcp.RoutingModel_RegisterUnaryTransitCallback(self, *args)
4894 return _pywrapcp.RoutingModel_RegisterTransitMatrix(self, values)
4897 return _pywrapcp.RoutingModel_RegisterTransitCallback(self, *args)
4900 return _pywrapcp.RoutingModel_RegisterCumulDependentTransitCallback(self, callback)
4903 return _pywrapcp.RoutingModel_TransitCallback(self, callback_index)
4906 return _pywrapcp.RoutingModel_UnaryTransitCallbackOrNull(self, callback_index)
4909 return _pywrapcp.RoutingModel_CumulDependentTransitCallback(self, callback_index)
4911 def AddDimension(self, evaluator_index, slack_max, capacity, fix_start_cumul_to_zero, name):
4914 Methods to add dimensions to routes; dimensions represent quantities
4915 accumulated at nodes along the routes. They represent quantities such as
4916 weights or volumes carried along the route, or distance or times.
4917 Quantities at a node are represented by "cumul" variables and the increase
4918 or decrease of quantities between nodes are represented by "transit"
4919 variables. These variables are linked as follows:
4920 if j == next(i), cumul(j) = cumul(i) + transit(i, j) + slack(i)
4921 where slack is a positive slack variable (can represent waiting times for
4923 Setting the value of fix_start_cumul_to_zero to true will force the
4924 "cumul" variable of the start node of all vehicles to be equal to 0.
4925 Creates a dimension where the transit variable is constrained to be
4926 equal to evaluator(i, next(i)); 'slack_max' is the upper bound of the
4927 slack variable and 'capacity' is the upper bound of the cumul variables.
4928 'name' is the name used to reference the dimension; this name is used to
4929 get cumul and transit variables from the routing model.
4930 Returns false if a dimension with the same name has already been created
4931 (and doesn't create the new dimension).
4932 Takes ownership of the callback 'evaluator'.
4934 return _pywrapcp.RoutingModel_AddDimension(self, evaluator_index, slack_max, capacity, fix_start_cumul_to_zero, name)
4937 return _pywrapcp.RoutingModel_AddDimensionWithVehicleTransits(self, evaluator_indices, slack_max, capacity, fix_start_cumul_to_zero, name)
4940 return _pywrapcp.RoutingModel_AddDimensionWithVehicleCapacity(self, evaluator_index, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name)
4943 return _pywrapcp.RoutingModel_AddDimensionWithVehicleTransitAndCapacity(self, evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name)
4947 Creates a dimension where the transit variable on arc i->j is the sum of:
4948 - A "fixed" transit value, obtained from the fixed_evaluator_index for
4949 this vehicle, referencing evaluators in transit_evaluators_, and
4950 - A FloatSlopePiecewiseLinearFunction of the cumul of node i, obtained
4951 from the cumul_dependent_evaluator_index of this vehicle, pointing to
4952 an evaluator in cumul_dependent_transit_evaluators_.
4954 return _pywrapcp.RoutingModel_AddDimensionWithCumulDependentVehicleTransitAndCapacity(self, fixed_evaluator_indices, cumul_dependent_evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name)
4958 Creates a dimension where the transit variable is constrained to be
4959 equal to 'value'; 'capacity' is the upper bound of the cumul variables.
4960 'name' is the name used to reference the dimension; this name is used to
4961 get cumul and transit variables from the routing model.
4962 Returns a pair consisting of an index to the registered unary transit
4963 callback and a bool denoting whether the dimension has been created.
4964 It is false if a dimension with the same name has already been created
4965 (and doesn't create the new dimension but still register a new callback).
4967 return _pywrapcp.RoutingModel_AddConstantDimensionWithSlack(self, value, capacity, slack_max, fix_start_cumul_to_zero, name)
4970 return _pywrapcp.RoutingModel_AddConstantDimension(self, value, capacity, fix_start_cumul_to_zero, name)
4974 Creates a dimension where the transit variable is constrained to be
4975 equal to 'values[i]' for node i; 'capacity' is the upper bound of
4976 the cumul variables. 'name' is the name used to reference the dimension;
4977 this name is used to get cumul and transit variables from the routing
4979 Returns a pair consisting of an index to the registered unary transit
4980 callback and a bool denoting whether the dimension has been created.
4981 It is false if a dimension with the same name has already been created
4982 (and doesn't create the new dimension but still register a new callback).
4984 return _pywrapcp.RoutingModel_AddVectorDimension(self, values, capacity, fix_start_cumul_to_zero, name)
4988 Creates a dimension where the transit variable is constrained to be
4989 equal to 'values[i][next(i)]' for node i; 'capacity' is the upper bound of
4990 the cumul variables. 'name' is the name used to reference the dimension;
4991 this name is used to get cumul and transit variables from the routing
4993 Returns a pair consisting of an index to the registered transit callback
4994 and a bool denoting whether the dimension has been created.
4995 It is false if a dimension with the same name has already been created
4996 (and doesn't create the new dimension but still register a new callback).
4998 return _pywrapcp.RoutingModel_AddMatrixDimension(self, values, capacity, fix_start_cumul_to_zero, name)
5001 r"""Outputs the names of all dimensions added to the routing engine."""
5002 return _pywrapcp.RoutingModel_GetAllDimensionNames(self)
5005 r"""Returns all dimensions of the model."""
5006 return _pywrapcp.RoutingModel_GetDimensions(self)
5009 r"""Returns dimensions with soft or vehicle span costs."""
5010 return _pywrapcp.RoutingModel_GetDimensionsWithSoftOrSpanCosts(self)
5013 r"""Returns dimensions for which all transit evaluators are unary."""
5014 return _pywrapcp.RoutingModel_GetUnaryDimensions(self)
5017 r"""Returns the dimensions which have [global|local]_dimension_optimizers_."""
5018 return _pywrapcp.RoutingModel_GetDimensionsWithGlobalCumulOptimizers(self)
5021 return _pywrapcp.RoutingModel_GetDimensionsWithLocalCumulOptimizers(self)
5024 r"""Returns whether the given dimension has global/local cumul optimizers."""
5025 return _pywrapcp.RoutingModel_HasGlobalCumulOptimizer(self, dimension)
5028 return _pywrapcp.RoutingModel_HasLocalCumulOptimizer(self, dimension)
5032 Returns the global/local dimension cumul optimizer for a given dimension,
5033 or nullptr if there is none.
5035 return _pywrapcp.RoutingModel_GetMutableGlobalCumulLPOptimizer(self, dimension)
5038 return _pywrapcp.RoutingModel_GetMutableGlobalCumulMPOptimizer(self, dimension)
5041 return _pywrapcp.RoutingModel_GetMutableLocalCumulLPOptimizer(self, dimension)
5044 return _pywrapcp.RoutingModel_GetMutableLocalCumulMPOptimizer(self, dimension)
5047 r"""Returns true if a dimension exists for a given dimension name."""
5048 return _pywrapcp.RoutingModel_HasDimension(self, dimension_name)
5051 r"""Returns a dimension from its name. Dies if the dimension does not exist."""
5052 return _pywrapcp.RoutingModel_GetDimensionOrDie(self, dimension_name)
5056 Returns a dimension from its name. Returns nullptr if the dimension does
5059 return _pywrapcp.RoutingModel_GetMutableDimension(self, dimension_name)
5063 Set the given dimension as "primary constrained". As of August 2013, this
5064 is only used by ArcIsMoreConstrainedThanArc().
5065 "dimension" must be the name of an existing dimension, or be empty, in
5066 which case there will not be a primary dimension after this call.
5068 return _pywrapcp.RoutingModel_SetPrimaryConstrainedDimension(self, dimension_name)
5071 r"""Get the primary constrained dimension, or an empty string if it is unset."""
5072 return _pywrapcp.RoutingModel_GetPrimaryConstrainedDimension(self)
5075 return _pywrapcp.RoutingModel_GetResourceGroup(self, rg_index)
5079 Returns the indices of resource groups for this dimension. This method can
5080 only be called after the model has been closed.
5082 return _pywrapcp.RoutingModel_GetDimensionResourceGroupIndices(self, dimension)
5086 Returns the index of the resource group attached to the dimension.
5087 DCHECKS that there's exactly one resource group for this dimension.
5089 return _pywrapcp.RoutingModel_GetDimensionResourceGroupIndex(self, dimension)
5090 PENALIZE_ONCE = _pywrapcp.RoutingModel_PENALIZE_ONCE
5091 PENALIZE_PER_INACTIVE = _pywrapcp.RoutingModel_PENALIZE_PER_INACTIVE
5095 Adds a disjunction constraint on the indices: exactly 'max_cardinality' of
5096 the indices are active. Start and end indices of any vehicle cannot be
5097 part of a disjunction.
5099 If a penalty is given, at most 'max_cardinality' of the indices can be
5100 active, and if less are active, 'penalty' is payed per inactive index if
5101 the penalty cost is set to `PENALIZE_PER_INACTIVE`.
5102 This is equivalent to adding the constraint:
5103 p + Sum(i)active[i] == max_cardinality
5104 where p is an integer variable.
5105 If the penalty cost is set to `PENALIZE_ONCE`, then 'penalty' is payed
5106 once if there are less than `max_cardinality` of the indices active.
5107 This is equivalent to adding the constraint:
5108 p == (Sum(i)active[i] != max_cardinality)
5109 where p is a boolean variable.
5110 The following cost is added to the cost function: p * penalty.
5111 'penalty' must be positive to make the disjunction optional; a negative
5112 penalty will force 'max_cardinality' indices of the disjunction to be
5113 performed, and therefore p == 0.
5114 Note: passing a vector with a single index will model an optional index
5115 with a penalty cost if it is not visited.
5117 return _pywrapcp.RoutingModel_AddDisjunction(self, *args)
5120 r"""Returns the indices of the disjunctions to which an index belongs."""
5121 return _pywrapcp.RoutingModel_GetDisjunctionIndices(self, index)
5124 r"""Returns the penalty of the node disjunction of index 'index'."""
5125 return _pywrapcp.RoutingModel_GetDisjunctionPenalty(self, index)
5129 Returns the maximum number of possible active nodes of the node
5130 disjunction of index 'index'.
5132 return _pywrapcp.RoutingModel_GetDisjunctionMaxCardinality(self, index)
5136 Returns the 'PenaltyCostBehavior' used by the disjunction of index
5139 return _pywrapcp.RoutingModel_GetDisjunctionPenaltyCostBehavior(self, index)
5142 r"""Returns the number of node disjunctions in the model."""
5143 return _pywrapcp.RoutingModel_GetNumberOfDisjunctions(self)
5147 Returns true if the model contains mandatory disjunctions (ones with
5148 kNoPenalty as penalty).
5150 return _pywrapcp.RoutingModel_HasMandatoryDisjunctions(self)
5154 Returns true if the model contains at least one disjunction which is
5155 constrained by its max_cardinality.
5157 return _pywrapcp.RoutingModel_HasMaxCardinalityConstrainedDisjunctions(self)
5161 Returns the list of all perfect binary disjunctions, as pairs of variable
5162 indices: a disjunction is "perfect" when its variables do not appear in
5163 any other disjunction. Each pair is sorted (lowest variable index first),
5164 and the output vector is also sorted (lowest pairs first).
5166 return _pywrapcp.RoutingModel_GetPerfectBinaryDisjunctions(self)
5170 SPECIAL: Makes the solver ignore all the disjunctions whose active
5171 variables are all trivially zero (i.e. Max() == 0), by setting their
5172 max_cardinality to 0.
5173 This can be useful when using the BaseBinaryDisjunctionNeighborhood
5174 operators, in the context of arc-based routing.
5176 return _pywrapcp.RoutingModel_IgnoreDisjunctionsAlreadyForcedToZero(self)
5180 Adds a soft constraint to force a set of variable indices to be on the
5181 same vehicle. If all nodes are not on the same vehicle, each extra vehicle
5182 used adds 'cost' to the cost function.
5184 return _pywrapcp.RoutingModel_AddSoftSameVehicleConstraint(self, indices, cost)
5188 Sets the vehicles which can visit a given node. If the node is in a
5189 disjunction, this will not prevent it from being unperformed.
5190 Specifying an empty vector of vehicles has no effect (all vehicles
5191 will be allowed to visit the node).
5193 return _pywrapcp.RoutingModel_SetAllowedVehiclesForIndex(self, vehicles, index)
5196 r"""Returns true if a vehicle is allowed to visit a given node."""
5197 return _pywrapcp.RoutingModel_IsVehicleAllowedForIndex(self, vehicle, index)
5201 Notifies that index1 and index2 form a pair of nodes which should belong
5202 to the same route. This methods helps the search find better solutions,
5203 especially in the local search phase.
5204 It should be called each time you have an equality constraint linking
5205 the vehicle variables of two node (including for instance pickup and
5207 Solver* const solver = routing.solver();
5208 int64_t index1 = manager.NodeToIndex(node1);
5209 int64_t index2 = manager.NodeToIndex(node2);
5210 solver->AddConstraint(solver->MakeEquality(
5211 routing.VehicleVar(index1),
5212 routing.VehicleVar(index2)));
5213 routing.AddPickupAndDelivery(index1, index2);
5215 return _pywrapcp.RoutingModel_AddPickupAndDelivery(self, pickup, delivery)
5219 Same as AddPickupAndDelivery but notifying that the performed node from
5220 the disjunction of index 'pickup_disjunction' is on the same route as the
5221 performed node from the disjunction of index 'delivery_disjunction'.
5223 return _pywrapcp.RoutingModel_AddPickupAndDeliverySets(self, pickup_disjunction, delivery_disjunction)
5226 r"""Returns the pickup and delivery positions where the node is a pickup."""
5227 return _pywrapcp.RoutingModel_GetPickupPosition(self, node_index)
5230 r"""Returns the pickup and delivery positions where the node is a delivery."""
5231 return _pywrapcp.RoutingModel_GetDeliveryPosition(self, node_index)
5234 r"""Returns whether the node is a pickup (resp. delivery)."""
5235 return _pywrapcp.RoutingModel_IsPickup(self, node_index)
5238 return _pywrapcp.RoutingModel_IsDelivery(self, node_index)
5242 Sets the Pickup and delivery policy of all vehicles. It is equivalent to
5243 calling SetPickupAndDeliveryPolicyOfVehicle on all vehicles.
5245 return _pywrapcp.RoutingModel_SetPickupAndDeliveryPolicyOfAllVehicles(self, policy)
5248 return _pywrapcp.RoutingModel_SetPickupAndDeliveryPolicyOfVehicle(self, policy, vehicle)
5251 return _pywrapcp.RoutingModel_GetPickupAndDeliveryPolicyOfVehicle(self, vehicle)
5255 Returns the number of non-start/end nodes which do not appear in a
5256 pickup/delivery pair.
5258 return _pywrapcp.RoutingModel_GetNumOfSingletonNodes(self)
5261 return _pywrapcp.RoutingModel_GetFirstMatchingPickupDeliverySibling(self, node, is_match)
5262 TYPE_ADDED_TO_VEHICLE = _pywrapcp.RoutingModel_TYPE_ADDED_TO_VEHICLE
5263 r"""When visited, the number of types 'T' on the vehicle increases by one."""
5264 ADDED_TYPE_REMOVED_FROM_VEHICLE = _pywrapcp.RoutingModel_ADDED_TYPE_REMOVED_FROM_VEHICLE
5266 When visited, one instance of type 'T' previously added to the route
5267 (TYPE_ADDED_TO_VEHICLE), if any, is removed from the vehicle.
5268 If the type was not previously added to the route or all added instances
5269 have already been removed, this visit has no effect on the types.
5271 TYPE_ON_VEHICLE_UP_TO_VISIT = _pywrapcp.RoutingModel_TYPE_ON_VEHICLE_UP_TO_VISIT
5273 With the following policy, the visit enforces that type 'T' is
5274 considered on the route from its start until this node is visited.
5276 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED = _pywrapcp.RoutingModel_TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED
5278 The visit doesn't have an impact on the number of types 'T' on the
5279 route, as it's (virtually) added and removed directly.
5280 This policy can be used for visits which are part of an incompatibility
5281 or requirement set without affecting the type count on the route.
5285 return _pywrapcp.RoutingModel_SetVisitType(self, index, type, type_policy)
5288 return _pywrapcp.RoutingModel_GetVisitType(self, index)
5291 return _pywrapcp.RoutingModel_GetSingleNodesOfType(self, type)
5294 return _pywrapcp.RoutingModel_GetPairIndicesOfType(self, type)
5297 return _pywrapcp.RoutingModel_GetVisitTypePolicy(self, index)
5300 return _pywrapcp.RoutingModel_GetNumberOfVisitTypes(self)
5305 Two nodes with "hard" incompatible types cannot share the same route at
5306 all, while with a "temporal" incompatibility they can't be on the same
5307 route at the same time.
5308 NOTE: To avoid unnecessary memory reallocations, it is recommended to only
5309 add incompatibilities once all the existing types have been set with
5312 return _pywrapcp.RoutingModel_AddHardTypeIncompatibility(self, type1, type2)
5315 return _pywrapcp.RoutingModel_AddTemporalTypeIncompatibility(self, type1, type2)
5318 r"""Returns visit types incompatible with a given type."""
5319 return _pywrapcp.RoutingModel_GetHardTypeIncompatibilitiesOfType(self, type)
5322 return _pywrapcp.RoutingModel_GetTemporalTypeIncompatibilitiesOfType(self, type)
5326 Returns true iff any hard (resp. temporal) type incompatibilities have
5327 been added to the model.
5329 return _pywrapcp.RoutingModel_HasHardTypeIncompatibilities(self)
5332 return _pywrapcp.RoutingModel_HasTemporalTypeIncompatibilities(self)
5337 NOTE: As of 2019-04, cycles in the requirement graph are not supported,
5338 and lead to the dependent nodes being skipped if possible (otherwise
5339 the model is considered infeasible).
5340 The following functions specify that "dependent_type" requires at least
5341 one of the types in "required_type_alternatives".
5343 For same-vehicle requirements, a node of dependent type type_D requires at
5344 least one node of type type_R among the required alternatives on the same
5346 NOTE: To avoid unnecessary memory reallocations, it is recommended to only
5347 add requirements once all the existing types have been set with
5350 return _pywrapcp.RoutingModel_AddSameVehicleRequiredTypeAlternatives(self, dependent_type, required_type_alternatives)
5354 If type_D depends on type_R when adding type_D, any node_D of type_D and
5355 VisitTypePolicy TYPE_ADDED_TO_VEHICLE or
5356 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED requires at least one type_R on its
5357 vehicle at the time node_D is visited.
5359 return _pywrapcp.RoutingModel_AddRequiredTypeAlternativesWhenAddingType(self, dependent_type, required_type_alternatives)
5363 The following requirements apply when visiting dependent nodes that remove
5364 their type from the route, i.e. type_R must be on the vehicle when type_D
5365 of VisitTypePolicy ADDED_TYPE_REMOVED_FROM_VEHICLE,
5366 TYPE_ON_VEHICLE_UP_TO_VISIT or TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED is
5369 return _pywrapcp.RoutingModel_AddRequiredTypeAlternativesWhenRemovingType(self, dependent_type, required_type_alternatives)
5373 Returns the set of same-vehicle requirement alternatives for the given
5376 return _pywrapcp.RoutingModel_GetSameVehicleRequiredTypeAlternativesOfType(self, type)
5379 r"""Returns the set of requirement alternatives when adding the given type."""
5380 return _pywrapcp.RoutingModel_GetRequiredTypeAlternativesWhenAddingType(self, type)
5383 r"""Returns the set of requirement alternatives when removing the given type."""
5384 return _pywrapcp.RoutingModel_GetRequiredTypeAlternativesWhenRemovingType(self, type)
5388 Returns true iff any same-route (resp. temporal) type requirements have
5389 been added to the model.
5391 return _pywrapcp.RoutingModel_HasSameVehicleTypeRequirements(self)
5394 return _pywrapcp.RoutingModel_HasTemporalTypeRequirements(self)
5398 Returns true iff the model has any incompatibilities or requirements set
5401 return _pywrapcp.RoutingModel_HasTypeRegulations(self)
5405 Get the "unperformed" penalty of a node. This is only well defined if the
5406 node is only part of a single Disjunction, and that disjunction has a
5407 penalty. For forced active nodes returns max int64_t. In all other cases,
5410 return _pywrapcp.RoutingModel_UnperformedPenalty(self, var_index)
5414 Same as above except that it returns default_value instead of 0 when
5415 penalty is not well defined (default value is passed as first argument to
5416 simplify the usage of the method in a callback).
5418 return _pywrapcp.RoutingModel_UnperformedPenaltyOrValue(self, default_value, var_index)
5422 Returns the variable index of the first starting or ending node of all
5423 routes. If all routes start and end at the same node (single depot), this
5424 is the node returned.
5426 return _pywrapcp.RoutingModel_GetDepot(self)
5430 Constrains the maximum number of active vehicles, aka the number of
5431 vehicles which do not have an empty route. For instance, this can be used
5432 to limit the number of routes in the case where there are fewer drivers
5433 than vehicles and that the fleet of vehicle is heterogeneous.
5435 return _pywrapcp.RoutingModel_SetMaximumNumberOfActiveVehicles(self, max_active_vehicles)
5438 r"""Returns the maximum number of active vehicles."""
5439 return _pywrapcp.RoutingModel_GetMaximumNumberOfActiveVehicles(self)
5443 Sets the cost function of the model such that the cost of a segment of a
5444 route between node 'from' and 'to' is evaluator(from, to), whatever the
5445 route or vehicle performing the route.
5447 return _pywrapcp.RoutingModel_SetArcCostEvaluatorOfAllVehicles(self, evaluator_index)
5450 r"""Sets the cost function for a given vehicle route."""
5451 return _pywrapcp.RoutingModel_SetArcCostEvaluatorOfVehicle(self, evaluator_index, vehicle)
5455 Sets the fixed cost of all vehicle routes. It is equivalent to calling
5456 SetFixedCostOfVehicle on all vehicle routes.
5458 return _pywrapcp.RoutingModel_SetFixedCostOfAllVehicles(self, cost)
5461 r"""Sets the fixed cost of one vehicle route."""
5462 return _pywrapcp.RoutingModel_SetFixedCostOfVehicle(self, cost, vehicle)
5466 Returns the route fixed cost taken into account if the route of the
5467 vehicle is not empty, aka there's at least one node on the route other
5468 than the first and last nodes.
5470 return _pywrapcp.RoutingModel_GetFixedCostOfVehicle(self, vehicle)
5473 return _pywrapcp.RoutingModel_SetPathEnergyCostOfVehicle(self, force, distance, cost_per_unit, vehicle)
5476 return _pywrapcp.RoutingModel_SetPathEnergyCostsOfVehicle(self, force, distance, threshold, cost_per_unit_below_threshold, cost_per_unit_above_threshold, vehicle)
5480 The following methods set the linear and quadratic cost factors of
5481 vehicles (must be positive values). The default value of these parameters
5482 is zero for all vehicles.
5484 When set, the cost_ of the model will contain terms aiming at reducing the
5485 number of vehicles used in the model, by adding the following to the
5486 objective for every vehicle v:
5487 INDICATOR(v used in the model) *
5488 [linear_cost_factor_of_vehicle_[v]
5489 - quadratic_cost_factor_of_vehicle_[v]*(square of length of route v)]
5490 i.e. for every used vehicle, we add the linear factor as fixed cost, and
5491 subtract the square of the route length multiplied by the quadratic
5492 factor. This second term aims at making the routes as dense as possible.
5494 Sets the linear and quadratic cost factor of all vehicles.
5496 return _pywrapcp.RoutingModel_SetAmortizedCostFactorsOfAllVehicles(self, linear_cost_factor, quadratic_cost_factor)
5499 r"""Sets the linear and quadratic cost factor of the given vehicle."""
5500 return _pywrapcp.RoutingModel_SetAmortizedCostFactorsOfVehicle(self, linear_cost_factor, quadratic_cost_factor, vehicle)
5503 return _pywrapcp.RoutingModel_GetAmortizedLinearCostFactorOfVehicles(self)
5506 return _pywrapcp.RoutingModel_GetAmortizedQuadraticCostFactorOfVehicles(self)
5509 return _pywrapcp.RoutingModel_AddRouteConstraint(self, route_evaluator, costs_are_homogeneous_across_vehicles)
5512 return _pywrapcp.RoutingModel_GetRouteCost(self, route)
5515 return _pywrapcp.RoutingModel_SetVehicleUsedWhenEmpty(self, is_used, vehicle)
5518 return _pywrapcp.RoutingModel_IsVehicleUsedWhenEmpty(self, vehicle)
5522 Gets/sets the evaluator used during the search. Only relevant when
5523 RoutingSearchParameters.first_solution_strategy = EVALUATOR_STRATEGY.
5524 Takes ownership of evaluator.
5526 return _pywrapcp.RoutingModel_SetFirstSolutionEvaluator(self, evaluator)
5530 Adds a hint to be used by first solution strategies. The hint assignment
5531 must outlive the search.
5532 As of 2024-12, only used by LOCAL_CHEAPEST_INSERTION and
5533 LOCAL_CHEAPEST_COST_INSERTION.
5535 return _pywrapcp.RoutingModel_SetFirstSolutionHint(self, hint)
5538 r"""Returns the current hint assignment."""
5539 return _pywrapcp.RoutingModel_GetFirstSolutionHint(self)
5543 Adds a local search operator to the set of operators used to solve the
5544 vehicle routing problem.
5546 return _pywrapcp.RoutingModel_AddLocalSearchOperator(self, ls_operator)
5549 r"""Adds a search monitor to the search used to solve the routing model."""
5550 return _pywrapcp.RoutingModel_AddSearchMonitor(self, monitor)
5553 return _pywrapcp.RoutingModel_AddEnterSearchCallback(self, callback)
5557 Adds a callback called each time a solution is found during the search.
5558 This is a shortcut to creating a monitor to call the callback on
5559 AtSolution() and adding it with AddSearchMonitor.
5560 If track_unchecked_neighbors is true, the callback will also be called on
5561 AcceptUncheckedNeighbor() events, which is useful to grab solutions
5562 obtained when solver_parameters.check_solution_period > 1 (aka fastLS).
5564 return _pywrapcp.RoutingModel_AddAtSolutionCallback(self, callback, track_unchecked_neighbors)
5567 return _pywrapcp.RoutingModel_AddRestoreDimensionValuesResetCallback(self, callback)
5571 Adds a variable to minimize in the solution finalizer. The solution
5572 finalizer is called each time a solution is found during the search and
5573 allows to instantiate secondary variables (such as dimension cumul
5576 return _pywrapcp.RoutingModel_AddVariableMinimizedByFinalizer(self, var)
5580 Adds a variable to maximize in the solution finalizer (see above for
5581 information on the solution finalizer).
5583 return _pywrapcp.RoutingModel_AddVariableMaximizedByFinalizer(self, var)
5587 Adds a variable to minimize in the solution finalizer, with a weighted
5588 priority: the higher the more priority it has.
5590 return _pywrapcp.RoutingModel_AddWeightedVariableMinimizedByFinalizer(self, var, cost)
5594 Adds a variable to maximize in the solution finalizer, with a weighted
5595 priority: the higher the more priority it has.
5597 return _pywrapcp.RoutingModel_AddWeightedVariableMaximizedByFinalizer(self, var, cost)
5601 Add a variable to set the closest possible to the target value in the
5604 return _pywrapcp.RoutingModel_AddVariableTargetToFinalizer(self, var, target)
5608 Same as above with a weighted priority: the higher the cost, the more
5609 priority it has to be set close to the target value.
5611 return _pywrapcp.RoutingModel_AddWeightedVariableTargetToFinalizer(self, var, target, cost)
5615 Closes the current routing model; after this method is called, no
5616 modification to the model can be done, but RoutesToAssignment becomes
5617 available. Note that CloseModel() is automatically called by Solve() and
5618 other methods that produce solution.
5619 This is equivalent to calling
5620 CloseModelWithParameters(DefaultRoutingSearchParameters()).
5622 return _pywrapcp.RoutingModel_CloseModel(self)
5626 Same as above taking search parameters (as of 10/2015 some the parameters
5627 have to be set when closing the model).
5629 return _pywrapcp.RoutingModel_CloseModelWithParameters(self, search_parameters)
5633 Solves the current routing model; closes the current model.
5634 This is equivalent to calling
5635 SolveWithParameters(DefaultRoutingSearchParameters())
5637 SolveFromAssignmentWithParameters(assignment,
5638 DefaultRoutingSearchParameters()).
5640 return _pywrapcp.RoutingModel_Solve(self, assignment)
5644 Solves the current routing model with the given parameters. If 'solutions'
5645 is specified, it will contain the k best solutions found during the search
5646 (from worst to best, including the one returned by this method), where k
5647 corresponds to the 'number_of_solutions_to_collect' in
5648 'search_parameters'. Note that the Assignment returned by the method and
5649 the ones in solutions are owned by the underlying solver and should not be
5652 return _pywrapcp.RoutingModel_SolveWithParameters(self, search_parameters, solutions)
5656 Same as above, except that if assignment is not null, it will be used as
5657 the initial solution.
5659 return _pywrapcp.RoutingModel_SolveFromAssignmentWithParameters(self, assignment, search_parameters, solutions)
5663 Improves a given assignment using unchecked local search.
5664 If check_solution_in_cp is true the final solution will be checked with
5666 As of 11/2023, only works with greedy descent.
5668 return _pywrapcp.RoutingModel_FastSolveFromAssignmentWithParameters(self, assignment, search_parameters, check_solution_in_cp, touched)
5672 Same as above but will try all assignments in order as first solutions
5675 return _pywrapcp.RoutingModel_SolveFromAssignmentsWithParameters(self, assignments, search_parameters, solutions)
5679 Solves the current routing model by using an Iterated Local Search
5682 return _pywrapcp.RoutingModel_SolveWithIteratedLocalSearch(self, search_parameters)
5686 Given a "source_model" and its "source_assignment", resets
5687 "target_assignment" with the IntVar variables (nexts_, and vehicle_vars_
5688 if costs aren't homogeneous across vehicles) of "this" model, with the
5689 values set according to those in "other_assignment".
5690 The objective_element of target_assignment is set to this->cost_.
5692 return _pywrapcp.RoutingModel_SetAssignmentFromOtherModelAssignment(self, target_assignment, source_model, source_assignment)
5696 Computes a lower bound to the routing problem solving a linear assignment
5697 problem. The routing model must be closed before calling this method.
5698 Note that problems with node disjunction constraints (including optional
5699 nodes) and non-homogenous costs are not supported (the method returns 0 in
5702 return _pywrapcp.RoutingModel_ComputeLowerBound(self)
5706 Returns the current lower bound found by internal solvers during the
5709 return _pywrapcp.RoutingModel_objective_lower_bound(self)
5712 r"""Returns the current status of the routing model."""
5713 return _pywrapcp.RoutingModel_status(self)
5716 r"""Returns the value of the internal enable_deep_serialization_ parameter."""
5717 return _pywrapcp.RoutingModel_enable_deep_serialization(self)
5721 Applies a lock chain to the next search. 'locks' represents an ordered
5722 vector of nodes representing a partial route which will be fixed during
5723 the next search; it will constrain next variables such that:
5724 next[locks[i]] == locks[i+1].
5726 Returns the next variable at the end of the locked chain; this variable is
5727 not locked. An assignment containing the locks can be obtained by calling
5730 return _pywrapcp.RoutingModel_ApplyLocks(self, locks)
5734 Applies lock chains to all vehicles to the next search, such that locks[p]
5735 is the lock chain for route p. Returns false if the locks do not contain
5736 valid routes; expects that the routes do not contain the depots,
5737 i.e. there are empty vectors in place of empty routes.
5738 If close_routes is set to true, adds the end nodes to the route of each
5739 vehicle and deactivates other nodes.
5740 An assignment containing the locks can be obtained by calling
5743 return _pywrapcp.RoutingModel_ApplyLocksToAllVehicles(self, locks, close_routes)
5747 Returns an assignment used to fix some of the variables of the problem.
5748 In practice, this assignment locks partial routes of the problem. This
5749 can be used in the context of locking the parts of the routes which have
5750 already been driven in online routing problems.
5752 return _pywrapcp.RoutingModel_PreAssignment(self)
5755 return _pywrapcp.RoutingModel_MutablePreAssignment(self)
5759 Writes the current solution to a file containing an AssignmentProto.
5760 Returns false if the file cannot be opened or if there is no current
5763 return _pywrapcp.RoutingModel_WriteAssignment(self, file_name)
5767 Reads an assignment from a file and returns the current solution.
5768 Returns nullptr if the file cannot be opened or if the assignment is not
5771 return _pywrapcp.RoutingModel_ReadAssignment(self, file_name)
5775 Restores an assignment as a solution in the routing model and returns the
5776 new solution. Returns nullptr if the assignment is not valid.
5778 return _pywrapcp.RoutingModel_RestoreAssignment(self, solution)
5782 Restores the routes as the current solution. Returns nullptr if the
5783 solution cannot be restored (routes do not contain a valid solution). Note
5784 that calling this method will run the solver to assign values to the
5785 dimension variables; this may take considerable amount of time, especially
5786 when using dimensions with slack.
5788 return _pywrapcp.RoutingModel_ReadAssignmentFromRoutes(self, routes, ignore_inactive_indices)
5792 Fills an assignment from a specification of the routes of the
5793 vehicles. The routes are specified as lists of variable indices that
5794 appear on the routes of the vehicles. The indices of the outer vector in
5795 'routes' correspond to vehicles IDs, the inner vector contains the
5796 variable indices on the routes for the given vehicle. The inner vectors
5797 must not contain the start and end indices, as these are determined by the
5798 routing model. Sets the value of NextVars in the assignment, adding the
5799 variables to the assignment if necessary. The method does not touch other
5800 variables in the assignment. The method can only be called after the model
5801 is closed. With ignore_inactive_indices set to false, this method will
5802 fail (return nullptr) in case some of the route contain indices that are
5803 deactivated in the model; when set to true, these indices will be
5804 skipped. Returns true if routes were successfully
5805 loaded. However, such assignment still might not be a valid
5806 solution to the routing problem due to more complex constraints;
5807 it is advisible to call solver()->CheckSolution() afterwards.
5809 return _pywrapcp.RoutingModel_RoutesToAssignment(self, routes, ignore_inactive_indices, close_routes, assignment)
5813 Converts the solution in the given assignment to routes for all vehicles.
5814 Expects that assignment contains a valid solution (i.e. routes for all
5815 vehicles end with an end index for that vehicle).
5817 return _pywrapcp.RoutingModel_AssignmentToRoutes(self, assignment, routes)
5821 Converts the solution in the given assignment to routes for all vehicles.
5822 If the returned vector is route_indices, route_indices[i][j] is the index
5823 for jth location visited on route i. Note that contrary to
5824 AssignmentToRoutes, the vectors do include start and end locations.
5825 Returns a compacted version of the given assignment, in which all vehicles
5826 with id lower or equal to some N have non-empty routes, and all vehicles
5827 with id greater than N have empty routes. Does not take ownership of the
5829 If found, the cost of the compact assignment is the same as in the
5830 original assignment and it preserves the values of 'active' variables.
5831 Returns nullptr if a compact assignment was not found.
5832 This method only works in homogenous mode, and it only swaps equivalent
5833 vehicles (vehicles with the same start and end nodes). When creating the
5834 compact assignment, the empty plan is replaced by the route assigned to
5835 the compatible vehicle with the highest id. Note that with more complex
5836 constraints on vehicle variables, this method might fail even if a compact
5838 This method changes the vehicle and dimension variables as necessary.
5839 While compacting the solution, only basic checks on vehicle variables are
5840 performed; if one of these checks fails no attempts to repair it are made
5841 (instead, the method returns nullptr).
5843 return _pywrapcp.RoutingModel_CompactAssignment(self, assignment)
5847 Same as CompactAssignment() but also checks the validity of the final
5848 compact solution; if it is not valid, no attempts to repair it are made
5849 (instead, the method returns nullptr).
5851 return _pywrapcp.RoutingModel_CompactAndCheckAssignment(self, assignment)
5854 r"""Adds an extra variable to the vehicle routing assignment."""
5855 return _pywrapcp.RoutingModel_AddToAssignment(self, var)
5858 return _pywrapcp.RoutingModel_AddIntervalToAssignment(self, interval)
5862 For every dimension in the model with an optimizer in
5863 local/global_dimension_optimizers_, this method tries to pack the cumul
5864 values of the dimension, such that:
5865 - The cumul costs (span costs, soft lower and upper bound costs, etc) are
5867 - The cumuls of the ends of the routes are minimized for this given
5869 - Given these minimal end cumuls, the route start cumuls are maximized.
5870 Returns the assignment resulting from allocating these packed cumuls with
5871 the solver, and nullptr if these cumuls could not be set by the solver.
5873 return _pywrapcp.RoutingModel_PackCumulsOfOptimizerDimensionsFromAssignment(self, original_assignment, duration_limit, time_limit_was_reached)
5878 Returns neighbors of all nodes for every cost class. The result is cached
5879 and is computed once. The number of neighbors considered is based on a
5880 ratio of non-vehicle nodes, specified by neighbors_ratio, with a minimum
5881 of min-neighbors node considered.
5886 Returns parameters.num_neighbors neighbors of all nodes for every cost
5887 class. The result is cached and is computed once.
5889 return _pywrapcp.RoutingModel_GetOrCreateNodeNeighborsByCostClass(self, *args)
5893 Adds a custom local search filter to the list of filters used to speed up
5894 local search by pruning unfeasible variable assignments.
5895 Calling this method after the routing model has been closed (CloseModel()
5896 or Solve() has been called) has no effect.
5897 The routing model does not take ownership of the filter.
5899 return _pywrapcp.RoutingModel_AddLocalSearchFilter(self, filter)
5904 Returns the variable index of the starting node of a vehicle route.
5906 return _pywrapcp.RoutingModel_Start(self, vehicle)
5909 r"""Returns the variable index of the ending node of a vehicle route."""
5910 return _pywrapcp.RoutingModel_End(self, vehicle)
5913 r"""Returns true if 'index' represents the first node of a route."""
5914 return _pywrapcp.RoutingModel_IsStart(self, index)
5917 r"""Returns true if 'index' represents the last node of a route."""
5918 return _pywrapcp.RoutingModel_IsEnd(self, index)
5922 Returns the vehicle of the given start/end index, and -1 if the given
5923 index is not a vehicle start/end.
5925 return _pywrapcp.RoutingModel_VehicleIndex(self, index)
5929 Assignment inspection
5930 Returns the variable index of the node directly after the node
5931 corresponding to 'index' in 'assignment'.
5933 return _pywrapcp.RoutingModel_Next(self, assignment, index)
5936 r"""Returns true if the route of 'vehicle' is non empty in 'assignment'."""
5937 return _pywrapcp.RoutingModel_IsVehicleUsed(self, assignment, vehicle)
5941 Returns the next variable of the node corresponding to index. Note that
5942 NextVar(index) == index is equivalent to ActiveVar(index) == 0.
5944 return _pywrapcp.RoutingModel_NextVar(self, index)
5947 r"""Returns the active variable of the node corresponding to index."""
5948 return _pywrapcp.RoutingModel_ActiveVar(self, index)
5952 Returns the active variable of the vehicle. It will be equal to 1 iff the
5953 route of the vehicle is not empty, 0 otherwise.
5955 return _pywrapcp.RoutingModel_ActiveVehicleVar(self, vehicle)
5959 Returns the variable specifying whether or not the given vehicle route is
5960 considered for costs and constraints. It will be equal to 1 iff the route
5961 of the vehicle is not empty OR vehicle_used_when_empty_[vehicle] is true.
5963 return _pywrapcp.RoutingModel_VehicleRouteConsideredVar(self, vehicle)
5967 Returns the vehicle variable of the node corresponding to index. Note that
5968 VehicleVar(index) == -1 is equivalent to ActiveVar(index) == 0.
5970 return _pywrapcp.RoutingModel_VehicleVar(self, index)
5974 Returns the resource variable for the given vehicle index in the given
5975 resource group. If a vehicle doesn't require a resource from the
5976 corresponding resource group, then ResourceVar(v, r_g) == -1.
5978 return _pywrapcp.RoutingModel_ResourceVar(self, vehicle, resource_group)
5981 r"""Returns the global cost variable which is being minimized."""
5982 return _pywrapcp.RoutingModel_CostVar(self)
5986 Returns the cost of the transit arc between two nodes for a given vehicle.
5987 Input are variable indices of node. This returns 0 if vehicle < 0.
5989 return _pywrapcp.RoutingModel_GetArcCostForVehicle(self, from_index, to_index, vehicle)
5992 r"""Whether costs are homogeneous across all vehicles."""
5993 return _pywrapcp.RoutingModel_CostsAreHomogeneousAcrossVehicles(self)
5997 Returns the cost of the segment between two nodes supposing all vehicle
5998 costs are the same (returns the cost for the first vehicle otherwise).
6000 return _pywrapcp.RoutingModel_GetHomogeneousCost(self, from_index, to_index)
6004 Returns the cost of the arc in the context of the first solution strategy.
6005 This is typically a simplification of the actual cost; see the .cc.
6007 return _pywrapcp.RoutingModel_GetArcCostForFirstSolution(self, from_index, to_index)
6011 Returns the cost of the segment between two nodes for a given cost
6012 class. Input are variable indices of nodes and the cost class.
6013 Unlike GetArcCostForVehicle(), if cost_class is kNoCost, then the
6014 returned cost won't necessarily be zero: only some of the components
6015 of the cost that depend on the cost class will be omited. See the code
6018 return _pywrapcp.RoutingModel_GetArcCostForClass(self, from_index, to_index, cost_class_index)
6021 r"""Get the cost class index of the given vehicle."""
6022 return _pywrapcp.RoutingModel_GetCostClassIndexOfVehicle(self, vehicle)
6026 Returns true iff the model contains a vehicle with the given
6029 return _pywrapcp.RoutingModel_HasVehicleWithCostClassIndex(self, cost_class_index)
6032 r"""Returns the number of different cost classes in the model."""
6033 return _pywrapcp.RoutingModel_GetCostClassesCount(self)
6036 r"""Ditto, minus the 'always zero', built-in cost class."""
6037 return _pywrapcp.RoutingModel_GetNonZeroCostClassesCount(self)
6040 return _pywrapcp.RoutingModel_GetVehicleClassIndexOfVehicle(self, vehicle)
6044 Returns a vehicle of the given vehicle class, and -1 if there are no
6045 vehicles for this class.
6047 return _pywrapcp.RoutingModel_GetVehicleOfClass(self, vehicle_class)
6050 r"""Returns the number of different vehicle classes in the model."""
6051 return _pywrapcp.RoutingModel_GetVehicleClassesCount(self)
6054 r"""Returns variable indices of nodes constrained to be on the same route."""
6055 return _pywrapcp.RoutingModel_GetSameVehicleIndicesOfIndex(self, node)
6058 r"""Returns variable indices of nodes constrained to have the same activity."""
6059 return _pywrapcp.RoutingModel_GetSameActivityIndicesOfIndex(self, node)
6062 r"""Returns the same activity group of the node."""
6063 return _pywrapcp.RoutingModel_GetSameActivityGroupOfIndex(self, node)
6066 r"""Returns the number of same activity groups."""
6067 return _pywrapcp.RoutingModel_GetSameActivityGroupsCount(self)
6070 r"""Returns variable indices of nodes in the same activity group."""
6071 return _pywrapcp.RoutingModel_GetSameActivityIndicesOfGroup(self, group)
6074 return _pywrapcp.RoutingModel_GetVehicleTypeContainer(self)
6078 Returns whether the arc from->to1 is more constrained than from->to2,
6079 taking into account, in order:
6080 - whether the destination node isn't an end node
6081 - whether the destination node is mandatory
6082 - whether the destination node is bound to the same vehicle as the source
6083 - the "primary constrained" dimension (see SetPrimaryConstrainedDimension)
6084 It then breaks ties using, in order:
6085 - the arc cost (taking unperformed penalties into account)
6086 - the size of the vehicle vars of "to1" and "to2" (lowest size wins)
6087 - the value: the lowest value of the indices to1 and to2 wins.
6088 See the .cc for details.
6089 The more constrained arc is typically preferable when building a
6090 first solution. This method is intended to be used as a callback for the
6091 BestValueByComparisonSelector value selector.
6093 from: the variable index of the source node
6094 to1: the variable index of the first candidate destination node.
6095 to2: the variable index of the second candidate destination node.
6097 return _pywrapcp.RoutingModel_ArcIsMoreConstrainedThanArc(self, _from, to1, to2)
6101 Print some debugging information about an assignment, including the
6102 feasible intervals of the CumulVar for dimension "dimension_to_print"
6103 at each step of the routes.
6104 If "dimension_to_print" is omitted, all dimensions will be printed.
6106 return _pywrapcp.RoutingModel_DebugOutputAssignment(self, solution_assignment, dimension_to_print)
6110 Returns a vector cumul_bounds, for which cumul_bounds[i][j] is a pair
6111 containing the minimum and maximum of the CumulVar of the jth node on
6113 - cumul_bounds[i][j].first is the minimum.
6114 - cumul_bounds[i][j].second is the maximum.
6115 Checks if an assignment is feasible.
6117 return _pywrapcp.RoutingModel_CheckIfAssignmentIsFeasible(self, assignment, call_at_solution_monitors)
6121 Returns the underlying constraint solver. Can be used to add extra
6122 constraints and/or modify search algorithms.
6124 return _pywrapcp.RoutingModel_solver(self)
6128 Returns true if the search limit has been crossed with the given time
6131 return _pywrapcp.RoutingModel_CheckLimit(self, *args)
6134 r"""Returns the time left in the search limit."""
6135 return _pywrapcp.RoutingModel_RemainingTime(self)
6138 r"""Updates the time limit of the search limit."""
6139 return _pywrapcp.RoutingModel_UpdateTimeLimit(self, time_limit)
6142 r"""Returns the time buffer to safely return a solution."""
6143 return _pywrapcp.RoutingModel_TimeBuffer(self)
6146 r"""Returns the atomic<bool> to stop the CP-SAT solver."""
6147 return _pywrapcp.RoutingModel_GetMutableCPSatInterrupt(self)
6150 r"""Returns the atomic<bool> to stop the CP solver."""
6151 return _pywrapcp.RoutingModel_GetMutableCPInterrupt(self)
6154 r"""Cancels the current search."""
6155 return _pywrapcp.RoutingModel_CancelSearch(self)
6160 Returns the number of nodes in the model.
6162 return _pywrapcp.RoutingModel_nodes(self)
6165 r"""Returns the number of vehicle routes in the model."""
6166 return _pywrapcp.RoutingModel_vehicles(self)
6169 r"""Returns the number of next variables in the model."""
6170 return _pywrapcp.RoutingModel_Size(self)
6174 Returns statistics on first solution search, number of decisions sent to
6175 filters, number of decisions rejected by filters.
6177 return _pywrapcp.RoutingModel_GetNumberOfDecisionsInFirstSolution(self, search_parameters)
6180 return _pywrapcp.RoutingModel_GetNumberOfRejectsInFirstSolution(self, search_parameters)
6183 r"""Returns the automatic first solution strategy selected."""
6184 return _pywrapcp.RoutingModel_GetAutomaticFirstSolutionStrategy(self)
6187 r"""Returns true if a vehicle/node matching problem is detected."""
6188 return _pywrapcp.RoutingModel_IsMatchingModel(self)
6192 Returns true if routes are interdependent. This means that any
6193 modification to a route might impact another.
6195 return _pywrapcp.RoutingModel_AreRoutesInterdependent(self, parameters)
6199 The next few members are in the public section only for testing purposes.
6201 MakeGuidedSlackFinalizer creates a DecisionBuilder for the slacks of a
6202 dimension using a callback to choose which values to start with.
6203 The finalizer works only when all next variables in the model have
6204 been fixed. It has the following two characteristics:
6205 1. It follows the routes defined by the nexts variables when choosing a
6206 variable to make a decision on.
6207 2. When it comes to choose a value for the slack of node i, the decision
6208 builder first calls the callback with argument i, and supposingly the
6209 returned value is x it creates decisions slack[i] = x, slack[i] = x +
6210 1, slack[i] = x - 1, slack[i] = x + 2, etc.
6212 return _pywrapcp.RoutingModel_MakeGuidedSlackFinalizer(self, dimension, initializer)
6216 MakeSelfDependentDimensionFinalizer is a finalizer for the slacks of a
6217 self-dependent dimension. It makes an extensive use of the caches of the
6218 state dependent transits.
6219 In detail, MakeSelfDependentDimensionFinalizer returns a composition of a
6220 local search decision builder with a greedy descent operator for the cumul
6221 of the start of each route and a guided slack finalizer. Provided there
6222 are no time windows and the maximum slacks are large enough, once the
6223 cumul of the start of route is fixed, the guided finalizer can find
6224 optimal values of the slacks for the rest of the route in time
6225 proportional to the length of the route. Therefore the composed finalizer
6226 generally works in time O(log(t)*n*m), where t is the latest possible
6227 departute time, n is the number of nodes in the network and m is the
6230 return _pywrapcp.RoutingModel_MakeSelfDependentDimensionFinalizer(self, dimension)
6233 return _pywrapcp.RoutingModel_GetPathsMetadata(self)
6237 Returns indices of the vehicles which are in the same vehicle class as the
6238 vehicle starting or ending at start_end_index.
6240 return _pywrapcp.RoutingModel_GetVehiclesOfSameClass(self, start_end_index)
6244 Returns all arcs which are equivalent to the {from_index, to_index} arc
6245 wrt vehicle classes. Arcs will be returned only if from_index is the
6246 start of a vehicle or if to_index is the end of a vehicle. The returned
6247 arcs will then be starting or ending at start or end nodes of vehicles in
6248 the same vehicle class. The input arc is included in the returned vector.
6250 return _pywrapcp.RoutingModel_GetSameVehicleClassArcs(self, from_index, to_index)
6253_pywrapcp.RoutingModel_swigregister(RoutingModel)
6254cvar = _pywrapcp.cvar
6255RoutingModel.kNoPenalty = _pywrapcp.cvar.RoutingModel_kNoPenalty
6256RoutingModel.kNoDisjunction = _pywrapcp.cvar.RoutingModel_kNoDisjunction
6257RoutingModel.kNoDimension = _pywrapcp.cvar.RoutingModel_kNoDimension
6260 r"""Routing model visitor."""
6262 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6263 __repr__ = _swig_repr
6266 _pywrapcp.RoutingModelVisitor_swiginit(self, _pywrapcp.new_RoutingModelVisitor())
6267 __swig_destroy__ = _pywrapcp.delete_RoutingModelVisitor
6270_pywrapcp.RoutingModelVisitor_swigregister(RoutingModelVisitor)
6271RoutingModelVisitor.kLightElement = _pywrapcp.cvar.RoutingModelVisitor_kLightElement
6272RoutingModelVisitor.kLightElement2 = _pywrapcp.cvar.RoutingModelVisitor_kLightElement2
6273RoutingModelVisitor.kRemoveValues = _pywrapcp.cvar.RoutingModelVisitor_kRemoveValues
6277 GlobalVehicleBreaksConstraint ensures breaks constraints are enforced on
6278 all vehicles in the dimension passed to its constructor.
6279 It is intended to be used for dimensions representing time.
6280 A break constraint ensures break intervals fit on the route of a vehicle.
6281 For a given vehicle, it forces break intervals to be disjoint from visit
6282 intervals, where visit intervals start at CumulVar(node) and last for
6283 node_visit_transit[node]. Moreover, it ensures that there is enough time
6284 between two consecutive nodes of a route to do transit and vehicle breaks,
6285 i.e. if Next(nodeA) = nodeB, CumulVar(nodeA) = tA and CumulVar(nodeB) = tB,
6286 then SlackVar(nodeA) >= sum_{breaks [tA, tB)} duration(break).
6289 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6290 __repr__ = _swig_repr
6293 _pywrapcp.GlobalVehicleBreaksConstraint_swiginit(self, _pywrapcp.new_GlobalVehicleBreaksConstraint(dimension))
6296 return _pywrapcp.GlobalVehicleBreaksConstraint_DebugString(self)
6299 return _pywrapcp.GlobalVehicleBreaksConstraint_Post(self)
6302 return _pywrapcp.GlobalVehicleBreaksConstraint_InitialPropagateWrapper(self)
6303 __swig_destroy__ = _pywrapcp.delete_GlobalVehicleBreaksConstraint
6306_pywrapcp.GlobalVehicleBreaksConstraint_swigregister(GlobalVehicleBreaksConstraint)
6308 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6311 raise AttributeError(
"No constructor defined - class is abstract")
6312 __repr__ = _swig_repr
6313 __swig_destroy__ = _pywrapcp.delete_TypeRegulationsChecker
6316 return _pywrapcp.TypeRegulationsChecker_CheckVehicle(self, vehicle, next_accessor)
6319_pywrapcp.TypeRegulationsChecker_swigregister(TypeRegulationsChecker)
6321 r"""Checker for type incompatibilities."""
6323 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6324 __repr__ = _swig_repr
6326 def __init__(self, model, check_hard_incompatibilities):
6327 _pywrapcp.TypeIncompatibilityChecker_swiginit(self, _pywrapcp.new_TypeIncompatibilityChecker(model, check_hard_incompatibilities))
6328 __swig_destroy__ = _pywrapcp.delete_TypeIncompatibilityChecker
6331_pywrapcp.TypeIncompatibilityChecker_swigregister(TypeIncompatibilityChecker)
6333 r"""Checker for type requirements."""
6335 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6336 __repr__ = _swig_repr
6339 _pywrapcp.TypeRequirementChecker_swiginit(self, _pywrapcp.new_TypeRequirementChecker(model))
6340 __swig_destroy__ = _pywrapcp.delete_TypeRequirementChecker
6343_pywrapcp.TypeRequirementChecker_swigregister(TypeRequirementChecker)
6346 The following constraint ensures that incompatibilities and requirements
6347 between types are respected.
6349 It verifies both "hard" and "temporal" incompatibilities.
6350 Two nodes with hard incompatible types cannot be served by the same vehicle
6351 at all, while with a temporal incompatibility they can't be on the same
6352 route at the same time.
6353 The VisitTypePolicy of a node determines how visiting it impacts the type
6357 - three temporally incompatible types T1 T2 and T3
6358 - 2 pairs of nodes a1/r1 and a2/r2 of type T1 and T2 respectively, with
6359 - a1 and a2 of VisitTypePolicy TYPE_ADDED_TO_VEHICLE
6360 - r1 and r2 of policy ADDED_TYPE_REMOVED_FROM_VEHICLE
6361 - 3 nodes A, UV and AR of type T3, respectively with type policies
6362 TYPE_ADDED_TO_VEHICLE, TYPE_ON_VEHICLE_UP_TO_VISIT and
6363 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED
6365 UV --> a1 --> r1 --> a2 --> r2, a1 --> r1 --> a2 --> r2 --> A and
6366 a1 --> r1 --> AR --> a2 --> r2 are acceptable, whereas the configurations
6367 a1 --> a2 --> r1 --> ..., or A --> a1 --> r1 --> ..., or
6368 a1 --> r1 --> UV --> ... are not feasible.
6370 It also verifies same-vehicle and temporal type requirements.
6371 A node of type T_d with a same-vehicle requirement for type T_r needs to be
6372 served by the same vehicle as a node of type T_r.
6373 Temporal requirements, on the other hand, can take effect either when the
6374 dependent type is being added to the route or when it's removed from it,
6375 which is determined by the dependent node's VisitTypePolicy.
6376 In the above example:
6377 - If T3 is required on the same vehicle as T1, A, AR or UV must be on the
6379 - If T2 is required when adding T1, a2 must be visited *before* a1, and if
6380 r2 is also visited on the route, it must be *after* a1, i.e. T2 must be on
6381 the vehicle when a1 is visited:
6382 ... --> a2 --> ... --> a1 --> ... --> r2 --> ...
6383 - If T3 is required when removing T1, T3 needs to be on the vehicle when
6385 ... --> A --> ... --> r1 --> ... OR ... --> r1 --> ... --> UV --> ...
6388 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6389 __repr__ = _swig_repr
6392 _pywrapcp.TypeRegulationsConstraint_swiginit(self, _pywrapcp.new_TypeRegulationsConstraint(model))
6395 return _pywrapcp.TypeRegulationsConstraint_Post(self)
6398 return _pywrapcp.TypeRegulationsConstraint_InitialPropagateWrapper(self)
6399 __swig_destroy__ = _pywrapcp.delete_TypeRegulationsConstraint
6402_pywrapcp.TypeRegulationsConstraint_swigregister(TypeRegulationsConstraint)
6405 A structure meant to store soft bounds and associated violation constants.
6406 It is 'Simple' because it has one BoundCost per element,
6407 in contrast to 'Multiple'. Design notes:
6408 - it is meant to store model information to be shared through pointers,
6409 so it disallows copy and assign to avoid accidental duplication.
6410 - it keeps soft bounds as an array of structs to help cache,
6411 because code that uses such bounds typically use both bound and cost.
6412 - soft bounds are named pairs, prevents some mistakes.
6413 - using operator[] to access elements is not interesting,
6414 because the structure will be accessed through pointers, moreover having
6415 to type bound_cost reminds the user of the order if they do a copy
6416 assignment of the element.
6419 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6420 __repr__ = _swig_repr
6421 bound = property(_pywrapcp.BoundCost_bound_get, _pywrapcp.BoundCost_bound_set)
6422 cost = property(_pywrapcp.BoundCost_cost_get, _pywrapcp.BoundCost_cost_set)
6425 _pywrapcp.BoundCost_swiginit(self, _pywrapcp.new_BoundCost(*args))
6426 __swig_destroy__ = _pywrapcp.delete_BoundCost
6429_pywrapcp.BoundCost_swigregister(BoundCost)
6431 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6432 __repr__ = _swig_repr
6435 _pywrapcp.SimpleBoundCosts_swiginit(self, _pywrapcp.new_SimpleBoundCosts(num_bounds, default_bound_cost))
6438 return _pywrapcp.SimpleBoundCosts_bound_cost(self, element)
6441 return _pywrapcp.SimpleBoundCosts_size(self)
6442 __swig_destroy__ = _pywrapcp.delete_SimpleBoundCosts
6445_pywrapcp.SimpleBoundCosts_swigregister(SimpleBoundCosts)
6448 Dimensions represent quantities accumulated at nodes along the routes. They
6449 represent quantities such as weights or volumes carried along the route, or
6452 Quantities at a node are represented by "cumul" variables and the increase
6453 or decrease of quantities between nodes are represented by "transit"
6454 variables. These variables are linked as follows:
6457 cumuls(j) = cumuls(i) + transits(i) + slacks(i) +
6458 state_dependent_transits(i)
6460 where slack is a positive slack variable (can represent waiting times for
6461 a time dimension), and state_dependent_transits is a non-purely functional
6462 version of transits_. Favour transits over state_dependent_transits when
6463 possible, because purely functional callbacks allow more optimisations and
6464 make the model faster and easier to solve.
6465 for a given vehicle, it is passed as an external vector, it would be better
6466 to have this information here.
6469 thisown = property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
"The membership flag")
6472 raise AttributeError(
"No constructor defined")
6473 __repr__ = _swig_repr
6474 __swig_destroy__ = _pywrapcp.delete_RoutingDimension
6477 r"""Returns the model on which the dimension was created."""
6478 return _pywrapcp.RoutingDimension_model(self)
6482 Returns the transition value for a given pair of nodes (as var index);
6483 this value is the one taken by the corresponding transit variable when
6484 the 'next' variable for 'from_index' is bound to 'to_index'.
6486 return _pywrapcp.RoutingDimension_GetTransitValue(self, from_index, to_index, vehicle)
6490 Same as above but taking a vehicle class of the dimension instead of a
6491 vehicle (the class of a vehicle can be obtained with vehicle_to_class()).
6493 return _pywrapcp.RoutingDimension_GetTransitValueFromClass(self, from_index, to_index, vehicle_class)
6497 Get the cumul, transit and slack variables for the given node (given as
6500 return _pywrapcp.RoutingDimension_CumulVar(self, index)
6503 return _pywrapcp.RoutingDimension_TransitVar(self, index)
6506 return _pywrapcp.RoutingDimension_FixedTransitVar(self, index)
6509 return _pywrapcp.RoutingDimension_SlackVar(self, index)
6513 Some functions to allow users to use the interface without knowing about
6514 the underlying CP model.
6515 Restricts the range of the cumul variable associated to index.
6517 return _pywrapcp.RoutingDimension_SetCumulVarRange(self, index, min, max)
6520 r"""Gets the current minimum of the cumul variable associated to index."""
6521 return _pywrapcp.RoutingDimension_GetCumulVarMin(self, index)
6524 r"""Gets the current maximum of the cumul variable associated to index."""
6525 return _pywrapcp.RoutingDimension_GetCumulVarMax(self, index)
6529 Sets an upper bound on the dimension span on a given vehicle. This is the
6530 preferred way to limit the "length" of the route of a vehicle according to
6533 return _pywrapcp.RoutingDimension_SetSpanUpperBoundForVehicle(self, upper_bound, vehicle)
6537 Sets a cost proportional to the dimension span on a given vehicle,
6538 or on all vehicles at once. "coefficient" must be nonnegative.
6539 This is handy to model costs proportional to idle time when the dimension
6541 The cost for a vehicle is
6542 span_cost = coefficient * (dimension end value - dimension start value).
6544 return _pywrapcp.RoutingDimension_SetSpanCostCoefficientForVehicle(self, coefficient, vehicle)
6547 return _pywrapcp.RoutingDimension_SetSpanCostCoefficientForAllVehicles(self, coefficient)
6551 Sets a cost proportional to the dimension total slack on a given vehicle,
6552 or on all vehicles at once. "coefficient" must be nonnegative.
6553 This is handy to model costs only proportional to idle time when the
6554 dimension represents time.
6555 The cost for a vehicle is
6556 slack_cost = coefficient *
6557 (dimension end value - dimension start value - total_transit).
6559 return _pywrapcp.RoutingDimension_SetSlackCostCoefficientForVehicle(self, coefficient, vehicle)
6562 return _pywrapcp.RoutingDimension_SetSlackCostCoefficientForAllVehicles(self, coefficient)
6566 Sets a cost proportional to the *global* dimension span, that is the
6567 difference between the largest value of route end cumul variables and
6568 the smallest value of route start cumul variables.
6571 coefficient * (Max(dimension end value) - Min(dimension start value)).
6573 return _pywrapcp.RoutingDimension_SetGlobalSpanCostCoefficient(self, coefficient)
6577 Sets a soft upper bound to the cumul variable of a given variable index.
6578 If the value of the cumul variable is greater than the bound, a cost
6579 proportional to the difference between this value and the bound is added
6580 to the cost function of the model:
6581 cumulVar <= upper_bound -> cost = 0
6582 cumulVar > upper_bound -> cost = coefficient * (cumulVar - upper_bound)
6583 This is also handy to model tardiness costs when the dimension represents
6586 return _pywrapcp.RoutingDimension_SetCumulVarSoftUpperBound(self, index, upper_bound, coefficient)
6590 Returns true if a soft upper bound has been set for a given variable
6593 return _pywrapcp.RoutingDimension_HasCumulVarSoftUpperBound(self, index)
6597 Returns the soft upper bound of a cumul variable for a given variable
6598 index. The "hard" upper bound of the variable is returned if no soft upper
6601 return _pywrapcp.RoutingDimension_GetCumulVarSoftUpperBound(self, index)
6605 Returns the cost coefficient of the soft upper bound of a cumul variable
6606 for a given variable index. If no soft upper bound has been set, 0 is
6609 return _pywrapcp.RoutingDimension_GetCumulVarSoftUpperBoundCoefficient(self, index)
6613 Sets a soft lower bound to the cumul variable of a given variable index.
6614 If the value of the cumul variable is less than the bound, a cost
6615 proportional to the difference between this value and the bound is added
6616 to the cost function of the model:
6617 cumulVar > lower_bound -> cost = 0
6618 cumulVar <= lower_bound -> cost = coefficient * (lower_bound -
6620 This is also handy to model earliness costs when the dimension represents
6623 return _pywrapcp.RoutingDimension_SetCumulVarSoftLowerBound(self, index, lower_bound, coefficient)
6627 Returns true if a soft lower bound has been set for a given variable
6630 return _pywrapcp.RoutingDimension_HasCumulVarSoftLowerBound(self, index)
6634 Returns the soft lower bound of a cumul variable for a given variable
6635 index. The "hard" lower bound of the variable is returned if no soft lower
6638 return _pywrapcp.RoutingDimension_GetCumulVarSoftLowerBound(self, index)
6642 Returns the cost coefficient of the soft lower bound of a cumul variable
6643 for a given variable index. If no soft lower bound has been set, 0 is
6646 return _pywrapcp.RoutingDimension_GetCumulVarSoftLowerBoundCoefficient(self, index)
6650 Sets the breaks for a given vehicle. Breaks are represented by
6651 IntervalVars. They may interrupt transits between nodes and increase
6652 the value of corresponding slack variables.
6653 A break may take place before the start of a vehicle, after the end of
6654 a vehicle, or during a travel i -> j.
6656 In that case, the interval [break.Start(), break.End()) must be a subset
6657 of [CumulVar(i) + pre_travel(i, j), CumulVar(j) - post_travel(i, j)). In
6658 other words, a break may not overlap any node n's visit, given by
6659 [CumulVar(n) - post_travel(_, n), CumulVar(n) + pre_travel(n, _)).
6660 This formula considers post_travel(_, start) and pre_travel(end, _) to be
6661 0; pre_travel will never be called on any (_, start) and post_travel will
6662 never we called on any (end, _). If pre_travel_evaluator or
6663 post_travel_evaluator is -1, it will be taken as a function that always
6665 Deprecated, sets pre_travel(i, j) = node_visit_transit[i].
6667 return _pywrapcp.RoutingDimension_SetBreakIntervalsOfVehicle(self, breaks, vehicle, node_visit_transits)
6671 With breaks supposed to be consecutive, this forces the distance between
6672 breaks of size at least minimum_break_duration to be at most distance.
6673 This supposes that the time until route start and after route end are
6676 return _pywrapcp.RoutingDimension_SetBreakDistanceDurationOfVehicle(self, distance, duration, vehicle)
6680 Sets up vehicle_break_intervals_, vehicle_break_distance_duration_,
6681 pre_travel_evaluators and post_travel_evaluators.
6683 return _pywrapcp.RoutingDimension_InitializeBreaks(self)
6686 r"""Returns true if any break interval or break distance was defined."""
6687 return _pywrapcp.RoutingDimension_HasBreakConstraints(self)
6690 return _pywrapcp.RoutingDimension_GetPreTravelEvaluatorOfVehicle(self, vehicle)
6693 return _pywrapcp.RoutingDimension_GetPostTravelEvaluatorOfVehicle(self, vehicle)
6696 r"""Returns the parent in the dependency tree if any or nullptr otherwise."""
6697 return _pywrapcp.RoutingDimension_base_dimension(self)
6701 It makes sense to use the function only for self-dependent dimension.
6702 For such dimensions the value of the slack of a node determines the
6703 transition cost of the next transit. Provided that
6704 1. cumul[node] is fixed,
6705 2. next[node] and next[next[node]] (if exists) are fixed,
6706 the value of slack[node] for which cumul[next[node]] + transit[next[node]]
6707 is minimized can be found in O(1) using this function.
6709 return _pywrapcp.RoutingDimension_ShortestTransitionSlack(self, node)
6712 r"""Returns the name of the dimension."""
6713 return _pywrapcp.RoutingDimension_name(self)
6716 return _pywrapcp.RoutingDimension_SetPickupToDeliveryLimitFunctionForPair(self, limit_function, pair_index)
6719 return _pywrapcp.RoutingDimension_HasPickupToDeliveryLimits(self)
6722 return _pywrapcp.RoutingDimension_AddNodePrecedence(self, first_node, second_node, offset)
6725 return _pywrapcp.RoutingDimension_GetSpanUpperBoundForVehicle(self, vehicle)
6728 return _pywrapcp.RoutingDimension_GetSpanCostCoefficientForVehicle(self, vehicle)
6731 return _pywrapcp.RoutingDimension_GetSlackCostCoefficientForVehicle(self, vehicle)
6734 return _pywrapcp.RoutingDimension_global_span_cost_coefficient(self)
6737 return _pywrapcp.RoutingDimension_GetGlobalOptimizerOffset(self)
6740 return _pywrapcp.RoutingDimension_GetLocalOptimizerOffsetForVehicle(self, vehicle)
6744 If the span of vehicle on this dimension is larger than bound,
6745 the cost will be increased by cost * (span - bound).
6747 return _pywrapcp.RoutingDimension_SetSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle)
6750 return _pywrapcp.RoutingDimension_HasSoftSpanUpperBounds(self)
6753 return _pywrapcp.RoutingDimension_GetSoftSpanUpperBoundForVehicle(self, vehicle)
6757 If the span of vehicle on this dimension is larger than bound,
6758 the cost will be increased by cost * (span - bound)^2.
6760 return _pywrapcp.RoutingDimension_SetQuadraticCostSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle)
6763 return _pywrapcp.RoutingDimension_HasQuadraticCostSoftSpanUpperBounds(self)
6766 return _pywrapcp.RoutingDimension_GetQuadraticCostSoftSpanUpperBoundForVehicle(self, vehicle)
6769_pywrapcp.RoutingDimension_swigregister(RoutingDimension)
6773 Attempts to solve the model using the cp-sat solver. As of 5/2019, will
6774 solve the TSP corresponding to the model if it has a single vehicle.
6775 Therefore the resulting solution might not actually be feasible. Will return
6776 false if a solution could not be found.
6778 return _pywrapcp.SolveModelWithSat(model, search_parameters, initial_solution, solution)