ortools.constraint_solver.pywrapcp
1# This file was automatically generated by SWIG (https://www.swig.org). 2# Version 4.4.0 3# 4# Do not make changes to this file unless you know what you are doing - modify 5# the SWIG interface file instead. 6 7from sys import version_info as _swig_python_version_info 8# Import the low-level C/C++ module 9if getattr(globals().get("__spec__"), "parent", None) or __package__ or "." in __name__: 10 from . import _pywrapcp 11else: 12 import _pywrapcp 13 14try: 15 import builtins as __builtin__ 16except ImportError: 17 import __builtin__ 18 19def _swig_repr(self): 20 try: 21 strthis = "proxy of " + self.this.__repr__() 22 except __builtin__.Exception: 23 strthis = "" 24 return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) 25 26 27def _swig_setattr_nondynamic_instance_variable(set): 28 def set_instance_attr(self, name, value): 29 if name == "this": 30 set(self, name, value) 31 elif name == "thisown": 32 self.this.own(value) 33 elif hasattr(self, name) and isinstance(getattr(type(self), name), property): 34 set(self, name, value) 35 else: 36 raise AttributeError("You cannot add instance attributes to %s" % self) 37 return set_instance_attr 38 39 40def _swig_setattr_nondynamic_class_variable(set): 41 def set_class_attr(cls, name, value): 42 if hasattr(cls, name) and not isinstance(getattr(cls, name), property): 43 set(cls, name, value) 44 else: 45 raise AttributeError("You cannot add class attributes to %s" % cls) 46 return set_class_attr 47 48 49def _swig_add_metaclass(metaclass): 50 """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" 51 def wrapper(cls): 52 return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) 53 return wrapper 54 55 56class _SwigNonDynamicMeta(type): 57 """Meta class to enforce nondynamic attributes (no new attributes) for a class""" 58 __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__) 59 60 61import weakref 62 63class DefaultPhaseParameters(object): 64 r""" 65 This struct holds all parameters for the default search. 66 DefaultPhaseParameters is only used by Solver::MakeDefaultPhase 67 methods. Note this is for advanced users only. 68 """ 69 70 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 71 __repr__ = _swig_repr 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 82 will be chosen. 83 """) 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 87 per variable. 88 """) 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 92 one. 93 """) 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 97 at all. 98 """) 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. 103 """) 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. 108 """) 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.""") 110 111 def __init__(self): 112 _pywrapcp.DefaultPhaseParameters_swiginit(self, _pywrapcp.new_DefaultPhaseParameters()) 113 __swig_destroy__ = _pywrapcp.delete_DefaultPhaseParameters 114 115# Register DefaultPhaseParameters in _pywrapcp: 116_pywrapcp.DefaultPhaseParameters_swigregister(DefaultPhaseParameters) 117class Solver(object): 118 r""" 119 Solver Class. 120 A solver represents the main computation engine. It implements the 121 entire range of Constraint Programming protocols: 122 - Reversibility 123 - Propagation 124 - Search 125 126 Usually, Constraint Programming code consists of 127 - the creation of the Solver, 128 - the creation of the decision variables of the model, 129 - the creation of the constraints of the model and their addition to the 130 solver() through the AddConstraint() method, 131 - the creation of the main DecisionBuilder class, 132 - the launch of the solve() method with the decision builder. 133 134 For the time being, Solver is neither MT_SAFE nor MT_HOT. 135 """ 136 137 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 138 __repr__ = _swig_repr 139 INT_VAR_DEFAULT = _pywrapcp.Solver_INT_VAR_DEFAULT 140 r"""The default behavior is CHOOSE_FIRST_UNBOUND.""" 141 INT_VAR_SIMPLE = _pywrapcp.Solver_INT_VAR_SIMPLE 142 r"""The simple selection is CHOOSE_FIRST_UNBOUND.""" 143 CHOOSE_FIRST_UNBOUND = _pywrapcp.Solver_CHOOSE_FIRST_UNBOUND 144 r""" 145 Select the first unbound variable. 146 Variables are considered in the order of the vector of IntVars used 147 to create the selector. 148 """ 149 CHOOSE_RANDOM = _pywrapcp.Solver_CHOOSE_RANDOM 150 r"""Randomly select one of the remaining unbound variables.""" 151 CHOOSE_MIN_SIZE_LOWEST_MIN = _pywrapcp.Solver_CHOOSE_MIN_SIZE_LOWEST_MIN 152 r""" 153 Among unbound variables, select the variable with the smallest size, 154 i.e., the smallest number of possible values. 155 In case of a tie, the selected variables is the one with the lowest min 156 value. 157 In case of a tie, the first one is selected, first being defined by the 158 order in the vector of IntVars used to create the selector. 159 """ 160 CHOOSE_MIN_SIZE_HIGHEST_MIN = _pywrapcp.Solver_CHOOSE_MIN_SIZE_HIGHEST_MIN 161 r""" 162 Among unbound variables, select the variable with the smallest size, 163 i.e., the smallest number of possible values. 164 In case of a tie, the selected variable is the one with the highest min 165 value. 166 In case of a tie, the first one is selected, first being defined by the 167 order in the vector of IntVars used to create the selector. 168 """ 169 CHOOSE_MIN_SIZE_LOWEST_MAX = _pywrapcp.Solver_CHOOSE_MIN_SIZE_LOWEST_MAX 170 r""" 171 Among unbound variables, select the variable with the smallest size, 172 i.e., the smallest number of possible values. 173 In case of a tie, the selected variables is the one with the lowest max 174 value. 175 In case of a tie, the first one is selected, first being defined by the 176 order in the vector of IntVars used to create the selector. 177 """ 178 CHOOSE_MIN_SIZE_HIGHEST_MAX = _pywrapcp.Solver_CHOOSE_MIN_SIZE_HIGHEST_MAX 179 r""" 180 Among unbound variables, select the variable with the smallest size, 181 i.e., the smallest number of possible values. 182 In case of a tie, the selected variable is the one with the highest max 183 value. 184 In case of a tie, the first one is selected, first being defined by the 185 order in the vector of IntVars used to create the selector. 186 """ 187 CHOOSE_LOWEST_MIN = _pywrapcp.Solver_CHOOSE_LOWEST_MIN 188 r""" 189 Among unbound variables, select the variable with the smallest minimal 190 value. 191 In case of a tie, the first one is selected, "first" defined by the 192 order in the vector of IntVars used to create the selector. 193 """ 194 CHOOSE_HIGHEST_MAX = _pywrapcp.Solver_CHOOSE_HIGHEST_MAX 195 r""" 196 Among unbound variables, select the variable with the highest maximal 197 value. 198 In case of a tie, the first one is selected, first being defined by the 199 order in the vector of IntVars used to create the selector. 200 """ 201 CHOOSE_MIN_SIZE = _pywrapcp.Solver_CHOOSE_MIN_SIZE 202 r""" 203 Among unbound variables, select the variable with the smallest size. 204 In case of a tie, the first one is selected, first being defined by the 205 order in the vector of IntVars used to create the selector. 206 """ 207 CHOOSE_MAX_SIZE = _pywrapcp.Solver_CHOOSE_MAX_SIZE 208 r""" 209 Among unbound variables, select the variable with the highest size. 210 In case of a tie, the first one is selected, first being defined by the 211 order in the vector of IntVars used to create the selector. 212 """ 213 CHOOSE_MAX_REGRET_ON_MIN = _pywrapcp.Solver_CHOOSE_MAX_REGRET_ON_MIN 214 r""" 215 Among unbound variables, select the variable with the largest 216 gap between the first and the second values of the domain. 217 """ 218 CHOOSE_PATH = _pywrapcp.Solver_CHOOSE_PATH 219 r""" 220 Selects the next unbound variable on a path, the path being defined by 221 the variables: var[i] corresponds to the index of the next of i. 222 """ 223 INT_VALUE_DEFAULT = _pywrapcp.Solver_INT_VALUE_DEFAULT 224 r"""The default behavior is ASSIGN_MIN_VALUE.""" 225 INT_VALUE_SIMPLE = _pywrapcp.Solver_INT_VALUE_SIMPLE 226 r"""The simple selection is ASSIGN_MIN_VALUE.""" 227 ASSIGN_MIN_VALUE = _pywrapcp.Solver_ASSIGN_MIN_VALUE 228 r"""Selects the min value of the selected variable.""" 229 ASSIGN_MAX_VALUE = _pywrapcp.Solver_ASSIGN_MAX_VALUE 230 r"""Selects the max value of the selected variable.""" 231 ASSIGN_RANDOM_VALUE = _pywrapcp.Solver_ASSIGN_RANDOM_VALUE 232 r"""Selects randomly one of the possible values of the selected variable.""" 233 ASSIGN_CENTER_VALUE = _pywrapcp.Solver_ASSIGN_CENTER_VALUE 234 r""" 235 Selects the first possible value which is the closest to the center 236 of the domain of the selected variable. 237 The center is defined as (min + max) / 2. 238 """ 239 SPLIT_LOWER_HALF = _pywrapcp.Solver_SPLIT_LOWER_HALF 240 r""" 241 Split the domain in two around the center, and choose the lower 242 part first. 243 """ 244 SPLIT_UPPER_HALF = _pywrapcp.Solver_SPLIT_UPPER_HALF 245 r""" 246 Split the domain in two around the center, and choose the lower 247 part first. 248 """ 249 SEQUENCE_DEFAULT = _pywrapcp.Solver_SEQUENCE_DEFAULT 250 SEQUENCE_SIMPLE = _pywrapcp.Solver_SEQUENCE_SIMPLE 251 CHOOSE_MIN_SLACK_RANK_FORWARD = _pywrapcp.Solver_CHOOSE_MIN_SLACK_RANK_FORWARD 252 CHOOSE_RANDOM_RANK_FORWARD = _pywrapcp.Solver_CHOOSE_RANDOM_RANK_FORWARD 253 INTERVAL_DEFAULT = _pywrapcp.Solver_INTERVAL_DEFAULT 254 r"""The default is INTERVAL_SET_TIMES_FORWARD.""" 255 INTERVAL_SIMPLE = _pywrapcp.Solver_INTERVAL_SIMPLE 256 r"""The simple is INTERVAL_SET_TIMES_FORWARD.""" 257 INTERVAL_SET_TIMES_FORWARD = _pywrapcp.Solver_INTERVAL_SET_TIMES_FORWARD 258 r""" 259 Selects the variable with the lowest starting time of all variables, 260 and fixes its starting time to this lowest value. 261 """ 262 INTERVAL_SET_TIMES_BACKWARD = _pywrapcp.Solver_INTERVAL_SET_TIMES_BACKWARD 263 r""" 264 Selects the variable with the highest ending time of all variables, 265 and fixes the ending time to this highest values. 266 """ 267 TWOOPT = _pywrapcp.Solver_TWOOPT 268 r""" 269 Operator which reverses a sub-chain of a path. It is called TwoOpt 270 because it breaks two arcs on the path; resulting paths are called 271 two-optimal. 272 Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5 273 (where (1, 5) are first and last nodes of the path and can therefore not 274 be moved): 275 276 .. code-block:: c++ 277 278 1 -> [3 -> 2] -> 4 -> 5 279 1 -> [4 -> 3 -> 2] -> 5 280 1 -> 2 -> [4 -> 3] -> 5 281 """ 282 OROPT = _pywrapcp.Solver_OROPT 283 r""" 284 Relocate: OROPT and RELOCATE. 285 Operator which moves a sub-chain of a path to another position; the 286 specified chain length is the fixed length of the chains being moved. 287 When this length is 1, the operator simply moves a node to another 288 position. 289 Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5, for a chain 290 length of 2 (where (1, 5) are first and last nodes of the path and can 291 therefore not be moved): 292 293 .. code-block:: c++ 294 295 1 -> 4 -> [2 -> 3] -> 5 296 1 -> [3 -> 4] -> 2 -> 5 297 Using Relocate with chain lengths of 1, 2 and 3 together is equivalent 298 to the OrOpt operator on a path. The OrOpt operator is a limited 299 version of 3Opt (breaks 3 arcs on a path). 300 """ 301 RELOCATE = _pywrapcp.Solver_RELOCATE 302 r"""Relocate neighborhood with length of 1 (see OROPT comment).""" 303 EXCHANGE = _pywrapcp.Solver_EXCHANGE 304 r""" 305 Operator which exchanges the positions of two nodes. 306 Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5 307 (where (1, 5) are first and last nodes of the path and can therefore not 308 be moved): 309 310 .. code-block:: c++ 311 312 1 -> [3] -> [2] -> 4 -> 5 313 1 -> [4] -> 3 -> [2] -> 5 314 1 -> 2 -> [4] -> [3] -> 5 315 """ 316 CROSS = _pywrapcp.Solver_CROSS 317 r""" 318 Operator which cross exchanges the starting chains of 2 paths, including 319 exchanging the whole paths. 320 First and last nodes are not moved. 321 Possible neighbors for the paths 1 -> 2 -> 3 -> 4 -> 5 and 6 -> 7 -> 8 322 (where (1, 5) and (6, 8) are first and last nodes of the paths and can 323 therefore not be moved): 324 325 .. code-block:: c++ 326 327 1 -> [7] -> 3 -> 4 -> 5 6 -> [2] -> 8 328 1 -> [7] -> 4 -> 5 6 -> [2 -> 3] -> 8 329 1 -> [7] -> 5 6 -> [2 -> 3 -> 4] -> 8 330 """ 331 MAKEACTIVE = _pywrapcp.Solver_MAKEACTIVE 332 r""" 333 Operator which inserts an inactive node into a path. 334 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive 335 (where 1 and 4 are first and last nodes of the path) are: 336 337 .. code-block:: c++ 338 339 1 -> [5] -> 2 -> 3 -> 4 340 1 -> 2 -> [5] -> 3 -> 4 341 1 -> 2 -> 3 -> [5] -> 4 342 """ 343 MAKEINACTIVE = _pywrapcp.Solver_MAKEINACTIVE 344 r""" 345 Operator which makes path nodes inactive. 346 Possible neighbors for the path 1 -> 2 -> 3 -> 4 (where 1 and 4 are 347 first and last nodes of the path) are: 348 349 .. code-block:: c++ 350 351 1 -> 3 -> 4 with 2 inactive 352 1 -> 2 -> 4 with 3 inactive 353 """ 354 MAKECHAININACTIVE = _pywrapcp.Solver_MAKECHAININACTIVE 355 r""" 356 Operator which makes a "chain" of path nodes inactive. 357 Possible neighbors for the path 1 -> 2 -> 3 -> 4 (where 1 and 4 are 358 first and last nodes of the path) are: 359 360 .. code-block:: c++ 361 362 1 -> 3 -> 4 with 2 inactive 363 1 -> 2 -> 4 with 3 inactive 364 1 -> 4 with 2 and 3 inactive 365 """ 366 SWAPACTIVE = _pywrapcp.Solver_SWAPACTIVE 367 r""" 368 Operator which replaces an active node by an inactive one. 369 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive 370 (where 1 and 4 are first and last nodes of the path) are: 371 372 .. code-block:: c++ 373 374 1 -> [5] -> 3 -> 4 with 2 inactive 375 1 -> 2 -> [5] -> 4 with 3 inactive 376 """ 377 EXTENDEDSWAPACTIVE = _pywrapcp.Solver_EXTENDEDSWAPACTIVE 378 r""" 379 Operator which makes an inactive node active and an active one inactive. 380 It is similar to SwapActiveOperator except that it tries to insert the 381 inactive node in all possible positions instead of just the position of 382 the node made inactive. 383 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive 384 (where 1 and 4 are first and last nodes of the path) are: 385 386 .. code-block:: c++ 387 388 1 -> [5] -> 3 -> 4 with 2 inactive 389 1 -> 3 -> [5] -> 4 with 2 inactive 390 1 -> [5] -> 2 -> 4 with 3 inactive 391 1 -> 2 -> [5] -> 4 with 3 inactive 392 """ 393 PATHLNS = _pywrapcp.Solver_PATHLNS 394 r""" 395 Operator which relaxes two sub-chains of three consecutive arcs each. 396 Each sub-chain is defined by a start node and the next three arcs. Those 397 six arcs are relaxed to build a new neighbor. 398 PATHLNS explores all possible pairs of starting nodes and so defines 399 n^2 neighbors, n being the number of nodes. 400 Note that the two sub-chains can be part of the same path; they even may 401 overlap. 402 """ 403 FULLPATHLNS = _pywrapcp.Solver_FULLPATHLNS 404 r""" 405 Operator which relaxes one entire path and all inactive nodes, thus 406 defining num_paths neighbors. 407 """ 408 UNACTIVELNS = _pywrapcp.Solver_UNACTIVELNS 409 r""" 410 Operator which relaxes all inactive nodes and one sub-chain of six 411 consecutive arcs. That way the path can be improved by inserting 412 inactive nodes or swapping arcs. 413 """ 414 INCREMENT = _pywrapcp.Solver_INCREMENT 415 r""" 416 Operator which defines one neighbor per variable. Each neighbor tries to 417 increment by one the value of the corresponding variable. When a new 418 solution is found the neighborhood is rebuilt from scratch, i.e., tries 419 to increment values in the variable order. 420 Consider for instance variables x and y. x is incremented one by one to 421 its max, and when it is not possible to increment x anymore, y is 422 incremented once. If this is a solution, then next neighbor tries to 423 increment x. 424 """ 425 DECREMENT = _pywrapcp.Solver_DECREMENT 426 r""" 427 Operator which defines a neighborhood to decrement values. 428 The behavior is the same as INCREMENT, except values are decremented 429 instead of incremented. 430 """ 431 SIMPLELNS = _pywrapcp.Solver_SIMPLELNS 432 r""" 433 Operator which defines one neighbor per variable. Each neighbor relaxes 434 one variable. 435 When a new solution is found the neighborhood is rebuilt from scratch. 436 Consider for instance variables x and y. First x is relaxed and the 437 solver is looking for the best possible solution (with only x relaxed). 438 Then y is relaxed, and the solver is looking for a new solution. 439 If a new solution is found, then the next variable to be relaxed is x. 440 """ 441 GE = _pywrapcp.Solver_GE 442 r"""Move is accepted when the current objective value >= objective.Min.""" 443 LE = _pywrapcp.Solver_LE 444 r"""Move is accepted when the current objective value <= objective.Max.""" 445 EQ = _pywrapcp.Solver_EQ 446 r""" 447 Move is accepted when the current objective value is in the interval 448 objective.Min .. objective.Max. 449 """ 450 DELAYED_PRIORITY = _pywrapcp.Solver_DELAYED_PRIORITY 451 r""" 452 DELAYED_PRIORITY is the lowest priority: Demons will be processed after 453 VAR_PRIORITY and NORMAL_PRIORITY demons. 454 """ 455 VAR_PRIORITY = _pywrapcp.Solver_VAR_PRIORITY 456 r"""VAR_PRIORITY is between DELAYED_PRIORITY and NORMAL_PRIORITY.""" 457 NORMAL_PRIORITY = _pywrapcp.Solver_NORMAL_PRIORITY 458 r"""NORMAL_PRIORITY is the highest priority: Demons will be processed first.""" 459 460 def __init__(self, *args): 461 r"""Solver API""" 462 _pywrapcp.Solver_swiginit(self, _pywrapcp.new_Solver(*args)) 463 464 self.__python_constraints = [] 465 466 467 468 __swig_destroy__ = _pywrapcp.delete_Solver 469 470 def Parameters(self): 471 r"""Stored Parameters.""" 472 return _pywrapcp.Solver_Parameters(self) 473 474 @staticmethod 475 def DefaultSolverParameters(): 476 r"""Create a ConstraintSolverParameters proto with all the default values.""" 477 return _pywrapcp.Solver_DefaultSolverParameters() 478 479 def AddConstraint(self, c): 480 r""" 481 Adds the constraint 'c' to the model. 482 483 After calling this method, and until there is a backtrack that undoes the 484 addition, any assignment of variables to values must satisfy the given 485 constraint in order to be considered feasible. There are two fairly 486 different use cases: 487 488 - the most common use case is modeling: the given constraint is really 489 part of the problem that the user is trying to solve. In this use case, 490 AddConstraint is called outside of search (i.e., with state() == 491 OUTSIDE_SEARCH). Most users should only use AddConstraint in this 492 way. In this case, the constraint will belong to the model forever: it 493 cannot be removed by backtracking. 494 495 - a rarer use case is that 'c' is not a real constraint of the model. It 496 may be a constraint generated by a branching decision (a constraint whose 497 goal is to restrict the search space), a symmetry breaking constraint (a 498 constraint that does restrict the search space, but in a way that cannot 499 have an impact on the quality of the solutions in the subtree), or an 500 inferred constraint that, while having no semantic value to the model (it 501 does not restrict the set of solutions), is worth having because we 502 believe it may strengthen the propagation. In these cases, it happens 503 that the constraint is added during the search (i.e., with state() == 504 IN_SEARCH or state() == IN_ROOT_NODE). When a constraint is 505 added during a search, it applies only to the subtree of the search tree 506 rooted at the current node, and will be automatically removed by 507 backtracking. 508 509 This method does not take ownership of the constraint. If the constraint 510 has been created by any factory method (Solver::MakeXXX), it will 511 automatically be deleted. However, power users who implement their own 512 constraints should do: solver.AddConstraint(solver.RevAlloc(new 513 MyConstraint(...)); 514 """ 515 return _pywrapcp.Solver_AddConstraint(self, c) 516 517 def Solve(self, *args): 518 r""" 519 Solves the problem using the given DecisionBuilder and returns true if a 520 solution was found and accepted. 521 522 These methods are the ones most users should use to search for a solution. 523 Note that the definition of 'solution' is subtle. A solution here is 524 defined as a leaf of the search tree with respect to the given decision 525 builder for which there is no failure. What this means is that, contrary 526 to intuition, a solution may not have all variables of the model bound. 527 It is the responsibility of the decision builder to keep returning 528 decisions until all variables are indeed bound. The most extreme 529 counterexample is calling Solve with a trivial decision builder whose 530 Next() method always returns nullptr. In this case, Solve immediately 531 returns 'true', since not assigning any variable to any value is a 532 solution, unless the root node propagation discovers that the model is 533 infeasible. 534 535 This function must be called either from outside of search, 536 or from within the Next() method of a decision builder. 537 538 Solve will terminate whenever any of the following event arise: 539 A search monitor asks the solver to terminate the search by calling 540 solver()->FinishCurrentSearch(). 541 A solution is found that is accepted by all search monitors, and none of 542 the search monitors decides to search for another one. 543 544 Upon search termination, there will be a series of backtracks all the way 545 to the top level. This means that a user cannot expect to inspect the 546 solution by querying variables after a call to Solve(): all the 547 information will be lost. In order to do something with the solution, the 548 user must either: 549 550 Use a search monitor that can process such a leaf. See, in particular, 551 the SolutionCollector class. 552 Do not use Solve. Instead, use the more fine-grained approach using 553 methods NewSearch(...), NextSolution(), and EndSearch(). 554 555 :type db: :py:class:`DecisionBuilder` 556 :param db: The decision builder that will generate the search tree. 557 :type monitors: std::vector< operations_research::SearchMonitor * > 558 :param monitors: A vector of search monitors that will be notified of 559 various events during the search. In their reaction to these events, such 560 monitors may influence the search. 561 """ 562 return _pywrapcp.Solver_Solve(self, *args) 563 564 def NewSearch(self, *args): 565 r""" 566 Decomposed search. 567 The code for a top level search should look like 568 solver->NewSearch(db); 569 while (solver->NextSolution()) { 570 .. use the current solution 571 } 572 solver()->EndSearch(); 573 """ 574 return _pywrapcp.Solver_NewSearch(self, *args) 575 576 def NextSolution(self): 577 return _pywrapcp.Solver_NextSolution(self) 578 579 def RestartSearch(self): 580 return _pywrapcp.Solver_RestartSearch(self) 581 582 def EndSearch(self): 583 return _pywrapcp.Solver_EndSearch(self) 584 585 def SolveAndCommit(self, *args): 586 r""" 587 SolveAndCommit using a decision builder and up to three 588 search monitors, usually one for the objective, one for the limits 589 and one to collect solutions. 590 591 The difference between a SolveAndCommit() and a Solve() method 592 call is the fact that SolveAndCommit will not backtrack all 593 modifications at the end of the search. This method is only 594 usable during the Next() method of a decision builder. 595 """ 596 return _pywrapcp.Solver_SolveAndCommit(self, *args) 597 598 def CheckAssignment(self, solution): 599 r"""Checks whether the given assignment satisfies all relevant constraints.""" 600 return _pywrapcp.Solver_CheckAssignment(self, solution) 601 602 def CheckConstraint(self, ct): 603 r""" 604 Checks whether adding this constraint will lead to an immediate 605 failure. It will return false if the model is already inconsistent, or if 606 adding the constraint makes it inconsistent. 607 """ 608 return _pywrapcp.Solver_CheckConstraint(self, ct) 609 610 def Fail(self): 611 r"""Abandon the current branch in the search tree. A backtrack will follow.""" 612 return _pywrapcp.Solver_Fail(self) 613 614 @staticmethod 615 def MemoryUsage(): 616 r"""Current memory usage in bytes""" 617 return _pywrapcp.Solver_MemoryUsage() 618 619 def WallTime(self): 620 r""" 621 Deprecated: Use Now() instead. 622 Time elapsed, in ms since the creation of the solver. 623 """ 624 return _pywrapcp.Solver_WallTime(self) 625 626 def Branches(self): 627 r"""The number of branches explored since the creation of the solver.""" 628 return _pywrapcp.Solver_Branches(self) 629 630 def Solutions(self): 631 r"""The number of solutions found since the start of the search.""" 632 return _pywrapcp.Solver_Solutions(self) 633 634 def Failures(self): 635 r"""The number of failures encountered since the creation of the solver.""" 636 return _pywrapcp.Solver_Failures(self) 637 638 def AcceptedNeighbors(self): 639 r"""The number of accepted neighbors.""" 640 return _pywrapcp.Solver_AcceptedNeighbors(self) 641 642 def Stamp(self): 643 r""" 644 The stamp indicates how many moves in the search tree we have performed. 645 It is useful to detect if we need to update same lazy structures. 646 """ 647 return _pywrapcp.Solver_Stamp(self) 648 649 def FailStamp(self): 650 r"""The fail_stamp() is incremented after each backtrack.""" 651 return _pywrapcp.Solver_FailStamp(self) 652 653 def IntVar(self, *args): 654 r""" 655 *Overload 1:* 656 MakeIntVar will create the best range based int var for the bounds given. 657 658 | 659 660 *Overload 2:* 661 MakeIntVar will create a variable with the given sparse domain. 662 663 | 664 665 *Overload 3:* 666 MakeIntVar will create a variable with the given sparse domain. 667 668 | 669 670 *Overload 4:* 671 MakeIntVar will create the best range based int var for the bounds given. 672 673 | 674 675 *Overload 5:* 676 MakeIntVar will create a variable with the given sparse domain. 677 678 | 679 680 *Overload 6:* 681 MakeIntVar will create a variable with the given sparse domain. 682 """ 683 return _pywrapcp.Solver_IntVar(self, *args) 684 685 def BoolVar(self, *args): 686 r""" 687 *Overload 1:* 688 MakeBoolVar will create a variable with a {0, 1} domain. 689 690 | 691 692 *Overload 2:* 693 MakeBoolVar will create a variable with a {0, 1} domain. 694 """ 695 return _pywrapcp.Solver_BoolVar(self, *args) 696 697 def IntConst(self, *args): 698 r""" 699 *Overload 1:* 700 IntConst will create a constant expression. 701 702 | 703 704 *Overload 2:* 705 IntConst will create a constant expression. 706 """ 707 return _pywrapcp.Solver_IntConst(self, *args) 708 709 def Sum(self, vars): 710 r"""sum of all vars.""" 711 return _pywrapcp.Solver_Sum(self, vars) 712 713 def ScalProd(self, *args): 714 r""" 715 *Overload 1:* 716 scalar product 717 718 | 719 720 *Overload 2:* 721 scalar product 722 """ 723 return _pywrapcp.Solver_ScalProd(self, *args) 724 725 def MonotonicElement(self, values, increasing, index): 726 r""" 727 Function based element. The constraint takes ownership of the 728 callback. The callback must be monotonic. It must be able to 729 cope with any possible value in the domain of 'index' 730 (potentially negative ones too). Furtermore, monotonicity is not 731 checked. Thus giving a non-monotonic function, or specifying an 732 incorrect increasing parameter will result in undefined behavior. 733 """ 734 return _pywrapcp.Solver_MonotonicElement(self, values, increasing, index) 735 736 def Element(self, *args): 737 r""" 738 *Overload 1:* 739 values[index] 740 741 | 742 743 *Overload 2:* 744 values[index] 745 746 | 747 748 *Overload 3:* 749 Function-based element. The constraint takes ownership of the 750 callback. The callback must be able to cope with any possible 751 value in the domain of 'index' (potentially negative ones too). 752 753 | 754 755 *Overload 4:* 756 2D version of function-based element expression, values(expr1, expr2). 757 758 | 759 760 *Overload 5:* 761 vars[expr] 762 """ 763 return _pywrapcp.Solver_Element(self, *args) 764 765 def IndexExpression(self, vars, value): 766 r""" 767 Returns the expression expr such that vars[expr] == value. 768 It assumes that vars are all different. 769 """ 770 return _pywrapcp.Solver_IndexExpression(self, vars, value) 771 772 def Min(self, *args): 773 r""" 774 *Overload 1:* 775 std::min(vars) 776 777 | 778 779 *Overload 2:* 780 std::min (left, right) 781 782 | 783 784 *Overload 3:* 785 std::min(expr, value) 786 787 | 788 789 *Overload 4:* 790 std::min(expr, value) 791 """ 792 return _pywrapcp.Solver_Min(self, *args) 793 794 def Max(self, *args): 795 r""" 796 *Overload 1:* 797 std::max(vars) 798 799 | 800 801 *Overload 2:* 802 std::max(left, right) 803 804 | 805 806 *Overload 3:* 807 std::max(expr, value) 808 809 | 810 811 *Overload 4:* 812 std::max(expr, value) 813 """ 814 return _pywrapcp.Solver_Max(self, *args) 815 816 def ConvexPiecewiseExpr(self, expr, early_cost, early_date, late_date, late_cost): 817 r"""Convex piecewise function.""" 818 return _pywrapcp.Solver_ConvexPiecewiseExpr(self, expr, early_cost, early_date, late_date, late_cost) 819 820 def SemiContinuousExpr(self, expr, fixed_charge, step): 821 r""" 822 Semi continuous Expression (x <= 0 -> f(x) = 0; x > 0 -> f(x) = ax + b) 823 a >= 0 and b >= 0 824 """ 825 return _pywrapcp.Solver_SemiContinuousExpr(self, expr, fixed_charge, step) 826 827 def ConditionalExpression(self, condition, expr, unperformed_value): 828 r"""Conditional Expr condition ? expr : unperformed_value""" 829 return _pywrapcp.Solver_ConditionalExpression(self, condition, expr, unperformed_value) 830 831 def TrueConstraint(self): 832 r"""This constraint always succeeds.""" 833 return _pywrapcp.Solver_TrueConstraint(self) 834 835 def FalseConstraint(self, *args): 836 r"""This constraint always fails.""" 837 return _pywrapcp.Solver_FalseConstraint(self, *args) 838 839 def IsEqualCstCt(self, var, value, boolvar): 840 r"""boolvar == (var == value)""" 841 return _pywrapcp.Solver_IsEqualCstCt(self, var, value, boolvar) 842 843 def IsEqualCstVar(self, var, value): 844 r"""status var of (var == value)""" 845 return _pywrapcp.Solver_IsEqualCstVar(self, var, value) 846 847 def IsEqualCt(self, v1, v2, b): 848 r"""b == (v1 == v2)""" 849 return _pywrapcp.Solver_IsEqualCt(self, v1, v2, b) 850 851 def IsEqualVar(self, v1, v2): 852 r"""status var of (v1 == v2)""" 853 return _pywrapcp.Solver_IsEqualVar(self, v1, v2) 854 855 def IsDifferentCstCt(self, var, value, boolvar): 856 r"""boolvar == (var != value)""" 857 return _pywrapcp.Solver_IsDifferentCstCt(self, var, value, boolvar) 858 859 def IsDifferentCstVar(self, var, value): 860 r"""status var of (var != value)""" 861 return _pywrapcp.Solver_IsDifferentCstVar(self, var, value) 862 863 def IsDifferentVar(self, v1, v2): 864 r"""status var of (v1 != v2)""" 865 return _pywrapcp.Solver_IsDifferentVar(self, v1, v2) 866 867 def IsDifferentCt(self, v1, v2, b): 868 r"""b == (v1 != v2)""" 869 return _pywrapcp.Solver_IsDifferentCt(self, v1, v2, b) 870 871 def IsLessOrEqualCstCt(self, var, value, boolvar): 872 r"""boolvar == (var <= value)""" 873 return _pywrapcp.Solver_IsLessOrEqualCstCt(self, var, value, boolvar) 874 875 def IsLessOrEqualCstVar(self, var, value): 876 r"""status var of (var <= value)""" 877 return _pywrapcp.Solver_IsLessOrEqualCstVar(self, var, value) 878 879 def IsLessOrEqualVar(self, left, right): 880 r"""status var of (left <= right)""" 881 return _pywrapcp.Solver_IsLessOrEqualVar(self, left, right) 882 883 def IsLessOrEqualCt(self, left, right, b): 884 r"""b == (left <= right)""" 885 return _pywrapcp.Solver_IsLessOrEqualCt(self, left, right, b) 886 887 def IsGreaterOrEqualCstCt(self, var, value, boolvar): 888 r"""boolvar == (var >= value)""" 889 return _pywrapcp.Solver_IsGreaterOrEqualCstCt(self, var, value, boolvar) 890 891 def IsGreaterOrEqualCstVar(self, var, value): 892 r"""status var of (var >= value)""" 893 return _pywrapcp.Solver_IsGreaterOrEqualCstVar(self, var, value) 894 895 def IsGreaterOrEqualVar(self, left, right): 896 r"""status var of (left >= right)""" 897 return _pywrapcp.Solver_IsGreaterOrEqualVar(self, left, right) 898 899 def IsGreaterOrEqualCt(self, left, right, b): 900 r"""b == (left >= right)""" 901 return _pywrapcp.Solver_IsGreaterOrEqualCt(self, left, right, b) 902 903 def IsGreaterCstCt(self, v, c, b): 904 r"""b == (v > c)""" 905 return _pywrapcp.Solver_IsGreaterCstCt(self, v, c, b) 906 907 def IsGreaterCstVar(self, var, value): 908 r"""status var of (var > value)""" 909 return _pywrapcp.Solver_IsGreaterCstVar(self, var, value) 910 911 def IsGreaterVar(self, left, right): 912 r"""status var of (left > right)""" 913 return _pywrapcp.Solver_IsGreaterVar(self, left, right) 914 915 def IsGreaterCt(self, left, right, b): 916 r"""b == (left > right)""" 917 return _pywrapcp.Solver_IsGreaterCt(self, left, right, b) 918 919 def IsLessCstCt(self, v, c, b): 920 r"""b == (v < c)""" 921 return _pywrapcp.Solver_IsLessCstCt(self, v, c, b) 922 923 def IsLessCstVar(self, var, value): 924 r"""status var of (var < value)""" 925 return _pywrapcp.Solver_IsLessCstVar(self, var, value) 926 927 def IsLessVar(self, left, right): 928 r"""status var of (left < right)""" 929 return _pywrapcp.Solver_IsLessVar(self, left, right) 930 931 def IsLessCt(self, left, right, b): 932 r"""b == (left < right)""" 933 return _pywrapcp.Solver_IsLessCt(self, left, right, b) 934 935 def SumLessOrEqual(self, vars, cst): 936 r"""Variation on arrays.""" 937 return _pywrapcp.Solver_SumLessOrEqual(self, vars, cst) 938 939 def SumGreaterOrEqual(self, vars, cst): 940 return _pywrapcp.Solver_SumGreaterOrEqual(self, vars, cst) 941 942 def SumEquality(self, *args): 943 return _pywrapcp.Solver_SumEquality(self, *args) 944 945 def ScalProdEquality(self, *args): 946 return _pywrapcp.Solver_ScalProdEquality(self, *args) 947 948 def ScalProdGreaterOrEqual(self, *args): 949 return _pywrapcp.Solver_ScalProdGreaterOrEqual(self, *args) 950 951 def ScalProdLessOrEqual(self, *args): 952 return _pywrapcp.Solver_ScalProdLessOrEqual(self, *args) 953 954 def MinEquality(self, vars, min_var): 955 return _pywrapcp.Solver_MinEquality(self, vars, min_var) 956 957 def MaxEquality(self, vars, max_var): 958 return _pywrapcp.Solver_MaxEquality(self, vars, max_var) 959 960 def ElementEquality(self, *args): 961 return _pywrapcp.Solver_ElementEquality(self, *args) 962 963 def AbsEquality(self, var, abs_var): 964 r"""Creates the constraint abs(var) == abs_var.""" 965 return _pywrapcp.Solver_AbsEquality(self, var, abs_var) 966 967 def IndexOfConstraint(self, vars, index, target): 968 r""" 969 This constraint is a special case of the element constraint with 970 an array of integer variables, where the variables are all 971 different and the index variable is constrained such that 972 vars[index] == target. 973 """ 974 return _pywrapcp.Solver_IndexOfConstraint(self, vars, index, target) 975 976 def ConstraintInitialPropagateCallback(self, ct): 977 r""" 978 This method is a specialized case of the MakeConstraintDemon 979 method to call the InitiatePropagate of the constraint 'ct'. 980 """ 981 return _pywrapcp.Solver_ConstraintInitialPropagateCallback(self, ct) 982 983 def DelayedConstraintInitialPropagateCallback(self, ct): 984 r""" 985 This method is a specialized case of the MakeConstraintDemon 986 method to call the InitiatePropagate of the constraint 'ct' with 987 low priority. 988 """ 989 return _pywrapcp.Solver_DelayedConstraintInitialPropagateCallback(self, ct) 990 991 def ClosureDemon(self, closure): 992 r"""Creates a demon from a closure.""" 993 return _pywrapcp.Solver_ClosureDemon(self, closure) 994 995 def BetweenCt(self, expr, l, u): 996 r"""(l <= expr <= u)""" 997 return _pywrapcp.Solver_BetweenCt(self, expr, l, u) 998 999 def IsBetweenCt(self, expr, l, u, b): 1000 r"""b == (l <= expr <= u)""" 1001 return _pywrapcp.Solver_IsBetweenCt(self, expr, l, u, b) 1002 1003 def IsBetweenVar(self, v, l, u): 1004 return _pywrapcp.Solver_IsBetweenVar(self, v, l, u) 1005 1006 def MemberCt(self, *args): 1007 r""" 1008 expr in set. Propagation is lazy, i.e. this constraint does not 1009 creates holes in the domain of the variable. 1010 """ 1011 return _pywrapcp.Solver_MemberCt(self, *args) 1012 1013 def NotMemberCt(self, *args): 1014 r""" 1015 *Overload 1:* 1016 expr not in set. 1017 1018 | 1019 1020 *Overload 2:* 1021 expr should not be in the list of forbidden intervals [start[i]..end[i]]. 1022 1023 | 1024 1025 *Overload 3:* 1026 expr should not be in the list of forbidden intervals [start[i]..end[i]]. 1027 """ 1028 return _pywrapcp.Solver_NotMemberCt(self, *args) 1029 1030 def IsMemberCt(self, *args): 1031 r"""boolvar == (expr in set)""" 1032 return _pywrapcp.Solver_IsMemberCt(self, *args) 1033 1034 def IsMemberVar(self, *args): 1035 return _pywrapcp.Solver_IsMemberVar(self, *args) 1036 1037 def Count(self, *args): 1038 r""" 1039 *Overload 1:* 1040 |{i | vars[i] == value}| == max_count 1041 1042 | 1043 1044 *Overload 2:* 1045 |{i | vars[i] == value}| == max_count 1046 """ 1047 return _pywrapcp.Solver_Count(self, *args) 1048 1049 def Distribute(self, *args): 1050 r""" 1051 *Overload 1:* 1052 Aggregated version of count: |{i | v[i] == values[j]}| == cards[j] 1053 1054 | 1055 1056 *Overload 2:* 1057 Aggregated version of count: |{i | v[i] == values[j]}| == cards[j] 1058 1059 | 1060 1061 *Overload 3:* 1062 Aggregated version of count: |{i | v[i] == j}| == cards[j] 1063 1064 | 1065 1066 *Overload 4:* 1067 Aggregated version of count with bounded cardinalities: 1068 forall j in 0 .. card_size - 1: card_min <= |{i | v[i] == j}| <= card_max 1069 1070 | 1071 1072 *Overload 5:* 1073 Aggregated version of count with bounded cardinalities: 1074 forall j in 0 .. card_size - 1: 1075 card_min[j] <= |{i | v[i] == j}| <= card_max[j] 1076 1077 | 1078 1079 *Overload 6:* 1080 Aggregated version of count with bounded cardinalities: 1081 forall j in 0 .. card_size - 1: 1082 card_min[j] <= |{i | v[i] == j}| <= card_max[j] 1083 1084 | 1085 1086 *Overload 7:* 1087 Aggregated version of count with bounded cardinalities: 1088 forall j in 0 .. card_size - 1: 1089 card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j] 1090 1091 | 1092 1093 *Overload 8:* 1094 Aggregated version of count with bounded cardinalities: 1095 forall j in 0 .. card_size - 1: 1096 card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j] 1097 """ 1098 return _pywrapcp.Solver_Distribute(self, *args) 1099 1100 def Deviation(self, vars, deviation_var, total_sum): 1101 r""" 1102 Deviation constraint: 1103 sum_i |n * vars[i] - total_sum| <= deviation_var and 1104 sum_i vars[i] == total_sum 1105 n = #vars 1106 """ 1107 return _pywrapcp.Solver_Deviation(self, vars, deviation_var, total_sum) 1108 1109 def AllDifferent(self, *args): 1110 r""" 1111 *Overload 1:* 1112 All variables are pairwise different. This corresponds to the 1113 stronger version of the propagation algorithm. 1114 1115 | 1116 1117 *Overload 2:* 1118 All variables are pairwise different. If 'stronger_propagation' 1119 is true, stronger, and potentially slower propagation will 1120 occur. This API will be deprecated in the future. 1121 """ 1122 return _pywrapcp.Solver_AllDifferent(self, *args) 1123 1124 def AllDifferentExcept(self, vars, escape_value): 1125 r""" 1126 All variables are pairwise different, unless they are assigned to 1127 the escape value. 1128 """ 1129 return _pywrapcp.Solver_AllDifferentExcept(self, vars, escape_value) 1130 1131 def SortingConstraint(self, vars, sorted): 1132 r""" 1133 Creates a constraint binding the arrays of variables "vars" and 1134 "sorted_vars": sorted_vars[0] must be equal to the minimum of all 1135 variables in vars, and so on: the value of sorted_vars[i] must be 1136 equal to the i-th value of variables invars. 1137 1138 This constraint propagates in both directions: from "vars" to 1139 "sorted_vars" and vice-versa. 1140 1141 Behind the scenes, this constraint maintains that: 1142 - sorted is always increasing. 1143 - whatever the values of vars, there exists a permutation that 1144 injects its values into the sorted variables. 1145 1146 For more info, please have a look at: 1147 https://mpi-inf.mpg.de/~mehlhorn/ftp/Mehlhorn-Thiel.pdf 1148 """ 1149 return _pywrapcp.Solver_SortingConstraint(self, vars, sorted) 1150 1151 def LexicalLess(self, left, right): 1152 r""" 1153 Creates a constraint that enforces that left is lexicographically less 1154 than right. 1155 """ 1156 return _pywrapcp.Solver_LexicalLess(self, left, right) 1157 1158 def LexicalLessOrEqual(self, left, right): 1159 r""" 1160 Creates a constraint that enforces that left is lexicographically less 1161 than or equal to right. 1162 """ 1163 return _pywrapcp.Solver_LexicalLessOrEqual(self, left, right) 1164 1165 def InversePermutationConstraint(self, left, right): 1166 r""" 1167 Creates a constraint that enforces that 'left' and 'right' both 1168 represent permutations of [0..left.size()-1], and that 'right' is 1169 the inverse permutation of 'left', i.e. for all i in 1170 [0..left.size()-1], right[left[i]] = i. 1171 """ 1172 return _pywrapcp.Solver_InversePermutationConstraint(self, left, right) 1173 1174 def NullIntersect(self, first_vars, second_vars): 1175 r""" 1176 Creates a constraint that states that all variables in the first 1177 vector are different from all variables in the second 1178 group. Thus the set of values in the first vector does not 1179 intersect with the set of values in the second vector. 1180 """ 1181 return _pywrapcp.Solver_NullIntersect(self, first_vars, second_vars) 1182 1183 def NullIntersectExcept(self, first_vars, second_vars, escape_value): 1184 r""" 1185 Creates a constraint that states that all variables in the first 1186 vector are different from all variables from the second group, 1187 unless they are assigned to the escape value. Thus the set of 1188 values in the first vector minus the escape value does not 1189 intersect with the set of values in the second vector. 1190 """ 1191 return _pywrapcp.Solver_NullIntersectExcept(self, first_vars, second_vars, escape_value) 1192 1193 def Circuit(self, nexts): 1194 r"""Force the "nexts" variable to create a complete Hamiltonian path.""" 1195 return _pywrapcp.Solver_Circuit(self, nexts) 1196 1197 def SubCircuit(self, nexts): 1198 r""" 1199 Force the "nexts" variable to create a complete Hamiltonian path 1200 for those that do not loop upon themselves. 1201 """ 1202 return _pywrapcp.Solver_SubCircuit(self, nexts) 1203 1204 def DelayedPathCumul(self, nexts, active, cumuls, transits): 1205 r""" 1206 Delayed version of the same constraint: propagation on the nexts variables 1207 is delayed until all constraints have propagated. 1208 """ 1209 return _pywrapcp.Solver_DelayedPathCumul(self, nexts, active, cumuls, transits) 1210 1211 def PathCumul(self, *args): 1212 r""" 1213 *Overload 1:* 1214 Creates a constraint which accumulates values along a path such that: 1215 cumuls[next[i]] = cumuls[i] + transits[i]. 1216 Active variables indicate if the corresponding next variable is active; 1217 this could be useful to model unperformed nodes in a routing problem. 1218 1219 | 1220 1221 *Overload 2:* 1222 Creates a constraint which accumulates values along a path such that: 1223 cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]). 1224 Active variables indicate if the corresponding next variable is active; 1225 this could be useful to model unperformed nodes in a routing problem. 1226 Ownership of transit_evaluator is taken and it must be a repeatable 1227 callback. 1228 1229 | 1230 1231 *Overload 3:* 1232 Creates a constraint which accumulates values along a path such that: 1233 cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]) + slacks[i]. 1234 Active variables indicate if the corresponding next variable is active; 1235 this could be useful to model unperformed nodes in a routing problem. 1236 Ownership of transit_evaluator is taken and it must be a repeatable 1237 callback. 1238 """ 1239 return _pywrapcp.Solver_PathCumul(self, *args) 1240 1241 def AllowedAssignments(self, *args): 1242 r""" 1243 *Overload 1:* 1244 This method creates a constraint where the graph of the relation 1245 between the variables is given in extension. There are 'arity' 1246 variables involved in the relation and the graph is given by a 1247 integer tuple set. 1248 1249 | 1250 1251 *Overload 2:* 1252 Compatibility layer for Python API. 1253 """ 1254 return _pywrapcp.Solver_AllowedAssignments(self, *args) 1255 1256 def TransitionConstraint(self, *args): 1257 r""" 1258 *Overload 1:* 1259 This constraint create a finite automaton that will check the 1260 sequence of variables vars. It uses a transition table called 1261 'transition_table'. Each transition is a triple 1262 (current_state, variable_value, new_state). 1263 The initial state is given, and the set of accepted states is decribed 1264 by 'final_states'. These states are hidden inside the constraint. 1265 Only the transitions (i.e. the variables) are visible. 1266 1267 | 1268 1269 *Overload 2:* 1270 This constraint create a finite automaton that will check the 1271 sequence of variables vars. It uses a transition table called 1272 'transition_table'. Each transition is a triple 1273 (current_state, variable_value, new_state). 1274 The initial state is given, and the set of accepted states is decribed 1275 by 'final_states'. These states are hidden inside the constraint. 1276 Only the transitions (i.e. the variables) are visible. 1277 """ 1278 return _pywrapcp.Solver_TransitionConstraint(self, *args) 1279 1280 def NonOverlappingBoxesConstraint(self, *args): 1281 r""" 1282 This constraint states that all the boxes must not overlap. 1283 The coordinates of box i are: 1284 (x_vars[i], y_vars[i]), 1285 (x_vars[i], y_vars[i] + y_size[i]), 1286 (x_vars[i] + x_size[i], y_vars[i]), 1287 (x_vars[i] + x_size[i], y_vars[i] + y_size[i]). 1288 The sizes must be non-negative. Boxes with a zero dimension can be 1289 pushed like any box. 1290 """ 1291 return _pywrapcp.Solver_NonOverlappingBoxesConstraint(self, *args) 1292 1293 def Pack(self, vars, number_of_bins): 1294 r""" 1295 This constraint packs all variables onto 'number_of_bins' 1296 variables. For any given variable, a value of 'number_of_bins' 1297 indicates that the variable is not assigned to any bin. 1298 Dimensions, i.e., cumulative constraints on this packing, can be 1299 added directly from the pack class. 1300 """ 1301 return _pywrapcp.Solver_Pack(self, vars, number_of_bins) 1302 1303 def FixedDurationIntervalVar(self, *args): 1304 r""" 1305 *Overload 1:* 1306 Creates an interval var with a fixed duration. The duration must 1307 be greater than 0. If optional is true, then the interval can be 1308 performed or unperformed. If optional is false, then the interval 1309 is always performed. 1310 1311 | 1312 1313 *Overload 2:* 1314 Creates a performed interval var with a fixed duration. The duration must 1315 be greater than 0. 1316 1317 | 1318 1319 *Overload 3:* 1320 Creates an interval var with a fixed duration, and performed_variable. 1321 The duration must be greater than 0. 1322 """ 1323 return _pywrapcp.Solver_FixedDurationIntervalVar(self, *args) 1324 1325 def FixedInterval(self, start, duration, name): 1326 r"""Creates a fixed and performed interval.""" 1327 return _pywrapcp.Solver_FixedInterval(self, start, duration, name) 1328 1329 def IntervalVar(self, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name): 1330 r""" 1331 Creates an interval var by specifying the bounds on start, 1332 duration, and end. 1333 """ 1334 return _pywrapcp.Solver_IntervalVar(self, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name) 1335 1336 def MirrorInterval(self, interval_var): 1337 r""" 1338 Creates an interval var that is the mirror image of the given one, that 1339 is, the interval var obtained by reversing the axis. 1340 """ 1341 return _pywrapcp.Solver_MirrorInterval(self, interval_var) 1342 1343 def FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset): 1344 r""" 1345 Creates an interval var with a fixed duration whose start is 1346 synchronized with the start of another interval, with a given 1347 offset. The performed status is also in sync with the performed 1348 status of the given interval variable. 1349 """ 1350 return _pywrapcp.Solver_FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset) 1351 1352 def FixedDurationStartSyncedOnEndIntervalVar(self, interval_var, duration, offset): 1353 r""" 1354 Creates an interval var with a fixed duration whose start is 1355 synchronized with the end of another interval, with a given 1356 offset. The performed status is also in sync with the performed 1357 status of the given interval variable. 1358 """ 1359 return _pywrapcp.Solver_FixedDurationStartSyncedOnEndIntervalVar(self, interval_var, duration, offset) 1360 1361 def FixedDurationEndSyncedOnStartIntervalVar(self, interval_var, duration, offset): 1362 r""" 1363 Creates an interval var with a fixed duration whose end is 1364 synchronized with the start of another interval, with a given 1365 offset. The performed status is also in sync with the performed 1366 status of the given interval variable. 1367 """ 1368 return _pywrapcp.Solver_FixedDurationEndSyncedOnStartIntervalVar(self, interval_var, duration, offset) 1369 1370 def FixedDurationEndSyncedOnEndIntervalVar(self, interval_var, duration, offset): 1371 r""" 1372 Creates an interval var with a fixed duration whose end is 1373 synchronized with the end of another interval, with a given 1374 offset. The performed status is also in sync with the performed 1375 status of the given interval variable. 1376 """ 1377 return _pywrapcp.Solver_FixedDurationEndSyncedOnEndIntervalVar(self, interval_var, duration, offset) 1378 1379 def IntervalRelaxedMin(self, interval_var): 1380 r""" 1381 Creates and returns an interval variable that wraps around the given one, 1382 relaxing the min start and end. Relaxing means making unbounded when 1383 optional. If the variable is non-optional, this method returns 1384 interval_var. 1385 1386 More precisely, such an interval variable behaves as follows: 1387 When the underlying must be performed, the returned interval variable 1388 behaves exactly as the underlying; 1389 When the underlying may or may not be performed, the returned interval 1390 variable behaves like the underlying, except that it is unbounded on 1391 the min side; 1392 When the underlying cannot be performed, the returned interval variable 1393 is of duration 0 and must be performed in an interval unbounded on 1394 both sides. 1395 1396 This is very useful to implement propagators that may only modify 1397 the start max or end max. 1398 """ 1399 return _pywrapcp.Solver_IntervalRelaxedMin(self, interval_var) 1400 1401 def IntervalRelaxedMax(self, interval_var): 1402 r""" 1403 Creates and returns an interval variable that wraps around the given one, 1404 relaxing the max start and end. Relaxing means making unbounded when 1405 optional. If the variable is non optional, this method returns 1406 interval_var. 1407 1408 More precisely, such an interval variable behaves as follows: 1409 When the underlying must be performed, the returned interval variable 1410 behaves exactly as the underlying; 1411 When the underlying may or may not be performed, the returned interval 1412 variable behaves like the underlying, except that it is unbounded on 1413 the max side; 1414 When the underlying cannot be performed, the returned interval variable 1415 is of duration 0 and must be performed in an interval unbounded on 1416 both sides. 1417 1418 This is very useful for implementing propagators that may only modify 1419 the start min or end min. 1420 """ 1421 return _pywrapcp.Solver_IntervalRelaxedMax(self, interval_var) 1422 1423 def TemporalDisjunction(self, *args): 1424 r""" 1425 *Overload 1:* 1426 This constraint implements a temporal disjunction between two 1427 interval vars t1 and t2. 'alt' indicates which alternative was 1428 chosen (alt == 0 is equivalent to t1 before t2). 1429 1430 | 1431 1432 *Overload 2:* 1433 This constraint implements a temporal disjunction between two 1434 interval vars. 1435 """ 1436 return _pywrapcp.Solver_TemporalDisjunction(self, *args) 1437 1438 def DisjunctiveConstraint(self, intervals, name): 1439 r""" 1440 This constraint forces all interval vars into an non-overlapping 1441 sequence. Intervals with zero duration can be scheduled anywhere. 1442 """ 1443 return _pywrapcp.Solver_DisjunctiveConstraint(self, intervals, name) 1444 1445 def Cumulative(self, *args): 1446 r""" 1447 *Overload 1:* 1448 This constraint forces that, for any integer t, the sum of the demands 1449 corresponding to an interval containing t does not exceed the given 1450 capacity. 1451 1452 Intervals and demands should be vectors of equal size. 1453 1454 Demands should only contain non-negative values. Zero values are 1455 supported, and the corresponding intervals are filtered out, as they 1456 neither impact nor are impacted by this constraint. 1457 1458 | 1459 1460 *Overload 2:* 1461 This constraint forces that, for any integer t, the sum of the demands 1462 corresponding to an interval containing t does not exceed the given 1463 capacity. 1464 1465 Intervals and demands should be vectors of equal size. 1466 1467 Demands should only contain non-negative values. Zero values are 1468 supported, and the corresponding intervals are filtered out, as they 1469 neither impact nor are impacted by this constraint. 1470 1471 | 1472 1473 *Overload 3:* 1474 This constraint forces that, for any integer t, the sum of the demands 1475 corresponding to an interval containing t does not exceed the given 1476 capacity. 1477 1478 Intervals and demands should be vectors of equal size. 1479 1480 Demands should only contain non-negative values. Zero values are 1481 supported, and the corresponding intervals are filtered out, as they 1482 neither impact nor are impacted by this constraint. 1483 1484 | 1485 1486 *Overload 4:* 1487 This constraint enforces that, for any integer t, the sum of the demands 1488 corresponding to an interval containing t does not exceed the given 1489 capacity. 1490 1491 Intervals and demands should be vectors of equal size. 1492 1493 Demands should only contain non-negative values. Zero values are 1494 supported, and the corresponding intervals are filtered out, as they 1495 neither impact nor are impacted by this constraint. 1496 1497 | 1498 1499 *Overload 5:* 1500 This constraint enforces that, for any integer t, the sum of demands 1501 corresponding to an interval containing t does not exceed the given 1502 capacity. 1503 1504 Intervals and demands should be vectors of equal size. 1505 1506 Demands should be positive. 1507 1508 | 1509 1510 *Overload 6:* 1511 This constraint enforces that, for any integer t, the sum of demands 1512 corresponding to an interval containing t does not exceed the given 1513 capacity. 1514 1515 Intervals and demands should be vectors of equal size. 1516 1517 Demands should be positive. 1518 """ 1519 return _pywrapcp.Solver_Cumulative(self, *args) 1520 1521 def Cover(self, vars, target_var): 1522 r""" 1523 This constraint states that the target_var is the convex hull of 1524 the intervals. If none of the interval variables is performed, 1525 then the target var is unperformed too. Also, if the target 1526 variable is unperformed, then all the intervals variables are 1527 unperformed too. 1528 """ 1529 return _pywrapcp.Solver_Cover(self, vars, target_var) 1530 1531 def Assignment(self, *args): 1532 r""" 1533 *Overload 1:* 1534 This method creates an empty assignment. 1535 1536 | 1537 1538 *Overload 2:* 1539 This method creates an assignment which is a copy of 'a'. 1540 """ 1541 return _pywrapcp.Solver_Assignment(self, *args) 1542 1543 def FirstSolutionCollector(self, *args): 1544 r""" 1545 *Overload 1:* 1546 Collect the first solution of the search. 1547 1548 | 1549 1550 *Overload 2:* 1551 Collect the first solution of the search. The variables will need to 1552 be added later. 1553 """ 1554 return _pywrapcp.Solver_FirstSolutionCollector(self, *args) 1555 1556 def LastSolutionCollector(self, *args): 1557 r""" 1558 *Overload 1:* 1559 Collect the last solution of the search. 1560 1561 | 1562 1563 *Overload 2:* 1564 Collect the last solution of the search. The variables will need to 1565 be added later. 1566 """ 1567 return _pywrapcp.Solver_LastSolutionCollector(self, *args) 1568 1569 def BestValueSolutionCollector(self, *args): 1570 r""" 1571 *Overload 1:* 1572 Collect the solution corresponding to the optimal value of the objective 1573 of 'assignment'; if 'assignment' does not have an objective no solution is 1574 collected. This collector only collects one solution corresponding to the 1575 best objective value (the first one found). 1576 1577 | 1578 1579 *Overload 2:* 1580 Collect the solution corresponding to the optimal value of the 1581 objective of the internal assignment; if this assignment does not have an 1582 objective no solution is collected. This collector only collects one 1583 solution corresponding to the best objective value (the first one found). 1584 The variables and objective(s) will need to be added later. 1585 """ 1586 return _pywrapcp.Solver_BestValueSolutionCollector(self, *args) 1587 1588 def AllSolutionCollector(self, *args): 1589 r""" 1590 *Overload 1:* 1591 Collect all solutions of the search. 1592 1593 | 1594 1595 *Overload 2:* 1596 Collect all solutions of the search. The variables will need to 1597 be added later. 1598 """ 1599 return _pywrapcp.Solver_AllSolutionCollector(self, *args) 1600 1601 def Minimize(self, v, step): 1602 r"""Creates a minimization objective.""" 1603 return _pywrapcp.Solver_Minimize(self, v, step) 1604 1605 def Maximize(self, v, step): 1606 r"""Creates a maximization objective.""" 1607 return _pywrapcp.Solver_Maximize(self, v, step) 1608 1609 def Optimize(self, maximize, v, step): 1610 r"""Creates a objective with a given sense (true = maximization).""" 1611 return _pywrapcp.Solver_Optimize(self, maximize, v, step) 1612 1613 def WeightedMinimize(self, *args): 1614 r""" 1615 *Overload 1:* 1616 Creates a minimization weighted objective. The actual objective is 1617 scalar_prod(sub_objectives, weights). 1618 1619 | 1620 1621 *Overload 2:* 1622 Creates a minimization weighted objective. The actual objective is 1623 scalar_prod(sub_objectives, weights). 1624 """ 1625 return _pywrapcp.Solver_WeightedMinimize(self, *args) 1626 1627 def WeightedMaximize(self, *args): 1628 r""" 1629 *Overload 1:* 1630 Creates a maximization weigthed objective. 1631 1632 | 1633 1634 *Overload 2:* 1635 Creates a maximization weigthed objective. 1636 """ 1637 return _pywrapcp.Solver_WeightedMaximize(self, *args) 1638 1639 def WeightedOptimize(self, *args): 1640 r""" 1641 *Overload 1:* 1642 Creates a weighted objective with a given sense (true = maximization). 1643 1644 | 1645 1646 *Overload 2:* 1647 Creates a weighted objective with a given sense (true = maximization). 1648 """ 1649 return _pywrapcp.Solver_WeightedOptimize(self, *args) 1650 1651 def TabuSearch(self, maximize, objective, step, vars, keep_tenure, forbid_tenure, tabu_factor): 1652 r""" 1653 MetaHeuristics which try to get the search out of local optima. 1654 Creates a Tabu Search monitor. 1655 In the context of local search the behavior is similar to MakeOptimize(), 1656 creating an objective in a given sense. The behavior differs once a local 1657 optimum is reached: thereafter solutions which degrade the value of the 1658 objective are allowed if they are not "tabu". A solution is "tabu" if it 1659 doesn't respect the following rules: 1660 - improving the best solution found so far 1661 - variables in the "keep" list must keep their value, variables in the 1662 "forbid" list must not take the value they have in the list. 1663 Variables with new values enter the tabu lists after each new solution 1664 found and leave the lists after a given number of iterations (called 1665 tenure). Only the variables passed to the method can enter the lists. 1666 The tabu criterion is softened by the tabu factor which gives the number 1667 of "tabu" violations which is tolerated; a factor of 1 means no violations 1668 allowed; a factor of 0 means all violations are allowed. 1669 """ 1670 return _pywrapcp.Solver_TabuSearch(self, maximize, objective, step, vars, keep_tenure, forbid_tenure, tabu_factor) 1671 1672 def SimulatedAnnealing(self, maximize, v, step, initial_temperature): 1673 r"""Creates a Simulated Annealing monitor.""" 1674 return _pywrapcp.Solver_SimulatedAnnealing(self, maximize, v, step, initial_temperature) 1675 1676 def LubyRestart(self, scale_factor): 1677 r""" 1678 This search monitor will restart the search periodically. 1679 At the iteration n, it will restart after scale_factor * Luby(n) failures 1680 where Luby is the Luby Strategy (i.e. 1 1 2 1 1 2 4 1 1 2 1 1 2 4 8...). 1681 """ 1682 return _pywrapcp.Solver_LubyRestart(self, scale_factor) 1683 1684 def ConstantRestart(self, frequency): 1685 r""" 1686 This search monitor will restart the search periodically after 'frequency' 1687 failures. 1688 """ 1689 return _pywrapcp.Solver_ConstantRestart(self, frequency) 1690 1691 def TimeLimit(self, *args): 1692 r"""Creates a search limit that constrains the running time.""" 1693 return _pywrapcp.Solver_TimeLimit(self, *args) 1694 1695 def BranchesLimit(self, branches): 1696 r""" 1697 Creates a search limit that constrains the number of branches 1698 explored in the search tree. 1699 """ 1700 return _pywrapcp.Solver_BranchesLimit(self, branches) 1701 1702 def FailuresLimit(self, failures): 1703 r""" 1704 Creates a search limit that constrains the number of failures 1705 that can happen when exploring the search tree. 1706 """ 1707 return _pywrapcp.Solver_FailuresLimit(self, failures) 1708 1709 def SolutionsLimit(self, solutions): 1710 r""" 1711 Creates a search limit that constrains the number of solutions found 1712 during the search. 1713 """ 1714 return _pywrapcp.Solver_SolutionsLimit(self, solutions) 1715 1716 def Limit(self, *args): 1717 r""" 1718 *Overload 1:* 1719 Limits the search with the 'time', 'branches', 'failures' and 1720 'solutions' limits. 'smart_time_check' reduces the calls to the wall 1721 1722 | 1723 1724 *Overload 2:* 1725 Creates a search limit from its protobuf description 1726 1727 | 1728 1729 *Overload 3:* 1730 Creates a search limit that is reached when either of the underlying limit 1731 is reached. That is, the returned limit is more stringent than both 1732 argument limits. 1733 """ 1734 return _pywrapcp.Solver_Limit(self, *args) 1735 1736 def CustomLimit(self, limiter): 1737 r""" 1738 Callback-based search limit. Search stops when limiter returns true; if 1739 this happens at a leaf the corresponding solution will be rejected. 1740 """ 1741 return _pywrapcp.Solver_CustomLimit(self, limiter) 1742 1743 def SearchLog(self, *args): 1744 r""" 1745 *Overload 1:* 1746 The SearchMonitors below will display a periodic search log 1747 on LOG(INFO) every branch_period branches explored. 1748 1749 | 1750 1751 *Overload 2:* 1752 At each solution, this monitor also display the var value. 1753 1754 | 1755 1756 *Overload 3:* 1757 At each solution, this monitor will also display result of 1758 ``display_callback``. 1759 1760 | 1761 1762 *Overload 4:* 1763 At each solution, this monitor will display the 'var' value and the 1764 result of ``display_callback``. 1765 1766 | 1767 1768 *Overload 5:* 1769 At each solution, this monitor will display the 'vars' values and the 1770 result of ``display_callback``. 1771 1772 | 1773 1774 *Overload 6:* 1775 OptimizeVar Search Logs 1776 At each solution, this monitor will also display the 'opt_var' value. 1777 1778 | 1779 1780 *Overload 7:* 1781 Creates a search monitor that will also print the result of the 1782 display callback. 1783 """ 1784 return _pywrapcp.Solver_SearchLog(self, *args) 1785 1786 def SearchTrace(self, prefix): 1787 r""" 1788 Creates a search monitor that will trace precisely the behavior of the 1789 search. Use this only for low level debugging. 1790 """ 1791 return _pywrapcp.Solver_SearchTrace(self, prefix) 1792 1793 def PrintModelVisitor(self): 1794 r"""Prints the model.""" 1795 return _pywrapcp.Solver_PrintModelVisitor(self) 1796 1797 def StatisticsModelVisitor(self): 1798 r"""Displays some nice statistics on the model.""" 1799 return _pywrapcp.Solver_StatisticsModelVisitor(self) 1800 1801 def AssignVariableValue(self, var, val): 1802 r"""Decisions.""" 1803 return _pywrapcp.Solver_AssignVariableValue(self, var, val) 1804 1805 def VariableLessOrEqualValue(self, var, value): 1806 return _pywrapcp.Solver_VariableLessOrEqualValue(self, var, value) 1807 1808 def VariableGreaterOrEqualValue(self, var, value): 1809 return _pywrapcp.Solver_VariableGreaterOrEqualValue(self, var, value) 1810 1811 def SplitVariableDomain(self, var, val, start_with_lower_half): 1812 return _pywrapcp.Solver_SplitVariableDomain(self, var, val, start_with_lower_half) 1813 1814 def AssignVariableValueOrFail(self, var, value): 1815 return _pywrapcp.Solver_AssignVariableValueOrFail(self, var, value) 1816 1817 def AssignVariablesValues(self, vars, values): 1818 return _pywrapcp.Solver_AssignVariablesValues(self, vars, values) 1819 1820 def FailDecision(self): 1821 return _pywrapcp.Solver_FailDecision(self) 1822 1823 def Decision(self, apply, refute): 1824 return _pywrapcp.Solver_Decision(self, apply, refute) 1825 1826 def Compose(self, dbs): 1827 return _pywrapcp.Solver_Compose(self, dbs) 1828 1829 def Try(self, dbs): 1830 return _pywrapcp.Solver_Try(self, dbs) 1831 1832 def DefaultPhase(self, *args): 1833 return _pywrapcp.Solver_DefaultPhase(self, *args) 1834 1835 def ScheduleOrPostpone(self, var, est, marker): 1836 r""" 1837 Returns a decision that tries to schedule a task at a given time. 1838 On the Apply branch, it will set that interval var as performed and set 1839 its start to 'est'. On the Refute branch, it will just update the 1840 'marker' to 'est' + 1. This decision is used in the 1841 INTERVAL_SET_TIMES_FORWARD strategy. 1842 """ 1843 return _pywrapcp.Solver_ScheduleOrPostpone(self, var, est, marker) 1844 1845 def ScheduleOrExpedite(self, var, est, marker): 1846 r""" 1847 Returns a decision that tries to schedule a task at a given time. 1848 On the Apply branch, it will set that interval var as performed and set 1849 its end to 'est'. On the Refute branch, it will just update the 1850 'marker' to 'est' - 1. This decision is used in the 1851 INTERVAL_SET_TIMES_BACKWARD strategy. 1852 """ 1853 return _pywrapcp.Solver_ScheduleOrExpedite(self, var, est, marker) 1854 1855 def RankFirstInterval(self, sequence, index): 1856 r""" 1857 Returns a decision that tries to rank first the ith interval var 1858 in the sequence variable. 1859 """ 1860 return _pywrapcp.Solver_RankFirstInterval(self, sequence, index) 1861 1862 def RankLastInterval(self, sequence, index): 1863 r""" 1864 Returns a decision that tries to rank last the ith interval var 1865 in the sequence variable. 1866 """ 1867 return _pywrapcp.Solver_RankLastInterval(self, sequence, index) 1868 1869 def Phase(self, *args): 1870 r""" 1871 *Overload 1:* 1872 Phases on IntVar arrays. 1873 for all other functions that have several homonyms in this .h). 1874 1875 | 1876 1877 *Overload 2:* 1878 Scheduling phases. 1879 """ 1880 return _pywrapcp.Solver_Phase(self, *args) 1881 1882 def DecisionBuilderFromAssignment(self, assignment, db, vars): 1883 r""" 1884 Returns a decision builder for which the left-most leaf corresponds 1885 to assignment, the rest of the tree being explored using 'db'. 1886 """ 1887 return _pywrapcp.Solver_DecisionBuilderFromAssignment(self, assignment, db, vars) 1888 1889 def ConstraintAdder(self, ct): 1890 r""" 1891 Returns a decision builder that will add the given constraint to 1892 the model. 1893 """ 1894 return _pywrapcp.Solver_ConstraintAdder(self, ct) 1895 1896 def SolveOnce(self, db, monitors): 1897 return _pywrapcp.Solver_SolveOnce(self, db, monitors) 1898 1899 def NestedOptimize(self, *args): 1900 r""" 1901 NestedOptimize will collapse a search tree described by a 1902 decision builder 'db' and a set of monitors and wrap it into a 1903 single point. If there are no solutions to this nested tree, then 1904 NestedOptimize will fail. If there are solutions, it will find 1905 the best as described by the mandatory objective in the solution 1906 as well as the optimization direction, instantiate all variables 1907 to this solution, and return nullptr. 1908 """ 1909 return _pywrapcp.Solver_NestedOptimize(self, *args) 1910 1911 def RestoreAssignment(self, assignment): 1912 r""" 1913 Returns a DecisionBuilder which restores an Assignment 1914 (calls void Assignment::Restore()) 1915 """ 1916 return _pywrapcp.Solver_RestoreAssignment(self, assignment) 1917 1918 def StoreAssignment(self, assignment): 1919 r""" 1920 Returns a DecisionBuilder which stores an Assignment 1921 (calls void Assignment::Store()) 1922 """ 1923 return _pywrapcp.Solver_StoreAssignment(self, assignment) 1924 1925 def Operator(self, *args): 1926 r"""Local Search Operators.""" 1927 return _pywrapcp.Solver_Operator(self, *args) 1928 1929 def RandomLnsOperator(self, *args): 1930 r""" 1931 Creates a large neighborhood search operator which creates fragments (set 1932 of relaxed variables) with up to number_of_variables random variables 1933 (sampling with replacement is performed meaning that at most 1934 number_of_variables variables are selected). Warning: this operator will 1935 always return neighbors; using it without a search limit will result in a 1936 non-ending search. 1937 Optionally a random seed can be specified. 1938 """ 1939 return _pywrapcp.Solver_RandomLnsOperator(self, *args) 1940 1941 def MoveTowardTargetOperator(self, *args): 1942 r""" 1943 *Overload 1:* 1944 Creates a local search operator that tries to move the assignment of some 1945 variables toward a target. The target is given as an Assignment. This 1946 operator generates neighbors in which the only difference compared to the 1947 current state is that one variable that belongs to the target assignment 1948 is set to its target value. 1949 1950 | 1951 1952 *Overload 2:* 1953 Creates a local search operator that tries to move the assignment of some 1954 variables toward a target. The target is given either as two vectors: a 1955 vector of variables and a vector of associated target values. The two 1956 vectors should be of the same length. This operator generates neighbors in 1957 which the only difference compared to the current state is that one 1958 variable that belongs to the given vector is set to its target value. 1959 """ 1960 return _pywrapcp.Solver_MoveTowardTargetOperator(self, *args) 1961 1962 def ConcatenateOperators(self, *args): 1963 r""" 1964 Creates a local search operator which concatenates a vector of operators. 1965 Each operator from the vector is called sequentially. By default, when a 1966 neighbor is found the neighborhood exploration restarts from the last 1967 active operator (the one which produced the neighbor). 1968 This can be overridden by setting restart to true to force the exploration 1969 to start from the first operator in the vector. 1970 1971 The default behavior can also be overridden using an evaluation callback 1972 to set the order in which the operators are explored (the callback is 1973 called in LocalSearchOperator::Start()). The first argument of the 1974 callback is the index of the operator which produced the last move, the 1975 second argument is the index of the operator to be evaluated. Ownership of 1976 the callback is taken by ConcatenateOperators. 1977 1978 Example: 1979 1980 const int kPriorities = {10, 100, 10, 0}; 1981 int64_t Evaluate(int active_operator, int current_operator) { 1982 return kPriorities[current_operator]; 1983 } 1984 1985 LocalSearchOperator* concat = 1986 solver.ConcatenateOperators(operators, 1987 NewPermanentCallback(&Evaluate)); 1988 1989 The elements of the vector operators will be sorted by increasing priority 1990 and explored in that order (tie-breaks are handled by keeping the relative 1991 operator order in the vector). This would result in the following order: 1992 operators[3], operators[0], operators[2], operators[1]. 1993 """ 1994 return _pywrapcp.Solver_ConcatenateOperators(self, *args) 1995 1996 def RandomConcatenateOperators(self, *args): 1997 r""" 1998 *Overload 1:* 1999 Randomized version of local search concatenator; calls a random operator 2000 at each call to MakeNextNeighbor(). 2001 2002 | 2003 2004 *Overload 2:* 2005 Randomized version of local search concatenator; calls a random operator 2006 at each call to MakeNextNeighbor(). The provided seed is used to 2007 initialize the random number generator. 2008 """ 2009 return _pywrapcp.Solver_RandomConcatenateOperators(self, *args) 2010 2011 def NeighborhoodLimit(self, op, limit): 2012 r""" 2013 Creates a local search operator that wraps another local search 2014 operator and limits the number of neighbors explored (i.e., calls 2015 to MakeNextNeighbor from the current solution (between two calls 2016 to Start()). When this limit is reached, MakeNextNeighbor() 2017 returns false. The counter is cleared when Start() is called. 2018 """ 2019 return _pywrapcp.Solver_NeighborhoodLimit(self, op, limit) 2020 2021 def LocalSearchPhase(self, *args): 2022 r""" 2023 *Overload 1:* 2024 Local Search decision builders factories. 2025 Local search is used to improve a given solution. This initial solution 2026 can be specified either by an Assignment or by a DecisionBulder, and the 2027 corresponding variables, the initial solution being the first solution 2028 found by the DecisionBuilder. 2029 The LocalSearchPhaseParameters parameter holds the actual definition of 2030 the local search phase: 2031 - a local search operator used to explore the neighborhood of the current 2032 solution, 2033 - a decision builder to instantiate unbound variables once a neighbor has 2034 been defined; in the case of LNS-based operators instantiates fragment 2035 variables; search monitors can be added to this sub-search by wrapping 2036 the decision builder with MakeSolveOnce. 2037 - a search limit specifying how long local search looks for neighbors 2038 before accepting one; the last neighbor is always taken and in the case 2039 of a greedy search, this corresponds to the best local neighbor; 2040 first-accept (which is the default behavior) can be modeled using a 2041 solution found limit of 1, 2042 - a vector of local search filters used to speed up the search by pruning 2043 unfeasible neighbors. 2044 Metaheuristics can be added by defining specialized search monitors; 2045 currently down/up-hill climbing is available through OptimizeVar, as well 2046 as Guided Local Search, Tabu Search and Simulated Annealing. 2047 2048 | 2049 2050 *Overload 2:* 2051 Variant with a sub_decison_builder specific to the first solution. 2052 """ 2053 return _pywrapcp.Solver_LocalSearchPhase(self, *args) 2054 2055 def LocalSearchPhaseParameters(self, *args): 2056 r"""Local Search Phase Parameters""" 2057 return _pywrapcp.Solver_LocalSearchPhaseParameters(self, *args) 2058 2059 def TopProgressPercent(self): 2060 r""" 2061 Returns a percentage representing the propress of the search before 2062 reaching the limits of the top-level search (can be called from a nested 2063 solve). 2064 """ 2065 return _pywrapcp.Solver_TopProgressPercent(self) 2066 2067 def SearchDepth(self): 2068 r""" 2069 Gets the search depth of the current active search. Returns -1 if 2070 there is no active search opened. 2071 """ 2072 return _pywrapcp.Solver_SearchDepth(self) 2073 2074 def SearchLeftDepth(self): 2075 r""" 2076 Gets the search left depth of the current active search. Returns -1 if 2077 there is no active search opened. 2078 """ 2079 return _pywrapcp.Solver_SearchLeftDepth(self) 2080 2081 def SolveDepth(self): 2082 r""" 2083 Gets the number of nested searches. It returns 0 outside search, 2084 1 during the top level search, 2 or more in case of nested searches. 2085 """ 2086 return _pywrapcp.Solver_SolveDepth(self) 2087 2088 def Rand64(self, size): 2089 r"""Returns a random value between 0 and 'size' - 1;""" 2090 return _pywrapcp.Solver_Rand64(self, size) 2091 2092 def Rand32(self, size): 2093 r"""Returns a random value between 0 and 'size' - 1;""" 2094 return _pywrapcp.Solver_Rand32(self, size) 2095 2096 def ReSeed(self, seed): 2097 r"""Reseed the solver random generator.""" 2098 return _pywrapcp.Solver_ReSeed(self, seed) 2099 2100 def LocalSearchProfile(self): 2101 r"""Returns local search profiling information in a human readable format.""" 2102 return _pywrapcp.Solver_LocalSearchProfile(self) 2103 2104 def Constraints(self): 2105 r""" 2106 Counts the number of constraints that have been added 2107 to the solver before the search. 2108 """ 2109 return _pywrapcp.Solver_Constraints(self) 2110 2111 def Accept(self, visitor): 2112 r"""Accepts the given model visitor.""" 2113 return _pywrapcp.Solver_Accept(self, visitor) 2114 2115 def FinishCurrentSearch(self): 2116 r"""Tells the solver to kill or restart the current search.""" 2117 return _pywrapcp.Solver_FinishCurrentSearch(self) 2118 2119 def RestartCurrentSearch(self): 2120 return _pywrapcp.Solver_RestartCurrentSearch(self) 2121 2122 def ShouldFail(self): 2123 r""" 2124 These methods are only useful for the SWIG wrappers, which need a way 2125 to externally cause the Solver to fail. 2126 """ 2127 return _pywrapcp.Solver_ShouldFail(self) 2128 2129 def __str__(self): 2130 return _pywrapcp.Solver___str__(self) 2131 2132 def Add(self, ct): 2133 if isinstance(ct, PyConstraint): 2134 self.__python_constraints.append(ct) 2135 self.AddConstraint(ct) 2136 2137 2138 def TreeNoCycle(self, nexts, active, callback=0): 2139 return _pywrapcp.Solver_TreeNoCycle(self, nexts, active, callback) 2140 2141 def SearchLogWithCallback(self, period, callback): 2142 return _pywrapcp.Solver_SearchLogWithCallback(self, period, callback) 2143 2144 def ElementFunction(self, values, index): 2145 return _pywrapcp.Solver_ElementFunction(self, values, index) 2146 2147 def VarEvalValStrPhase(self, vars, var_evaluator, val_str): 2148 return _pywrapcp.Solver_VarEvalValStrPhase(self, vars, var_evaluator, val_str) 2149 2150 def VarStrValEvalPhase(self, vars, var_str, val_eval): 2151 return _pywrapcp.Solver_VarStrValEvalPhase(self, vars, var_str, val_eval) 2152 2153 def VarEvalValEvalPhase(self, vars, var_eval, val_eval): 2154 return _pywrapcp.Solver_VarEvalValEvalPhase(self, vars, var_eval, val_eval) 2155 2156 def VarStrValEvalTieBreakPhase(self, vars, var_str, val_eval, tie_breaker): 2157 return _pywrapcp.Solver_VarStrValEvalTieBreakPhase(self, vars, var_str, val_eval, tie_breaker) 2158 2159 def VarEvalValEvalTieBreakPhase(self, vars, var_eval, val_eval, tie_breaker): 2160 return _pywrapcp.Solver_VarEvalValEvalTieBreakPhase(self, vars, var_eval, val_eval, tie_breaker) 2161 2162 def EvalEvalStrPhase(self, vars, evaluator, str): 2163 return _pywrapcp.Solver_EvalEvalStrPhase(self, vars, evaluator, str) 2164 2165 def EvalEvalStrTieBreakPhase(self, vars, evaluator, tie_breaker, str): 2166 return _pywrapcp.Solver_EvalEvalStrTieBreakPhase(self, vars, evaluator, tie_breaker, str) 2167 2168 def GuidedLocalSearch(self, maximize, objective, objective_function, step, vars, penalty_factor): 2169 return _pywrapcp.Solver_GuidedLocalSearch(self, maximize, objective, objective_function, step, vars, penalty_factor) 2170 2171 def SumObjectiveFilter(self, vars, values, filter_enum): 2172 return _pywrapcp.Solver_SumObjectiveFilter(self, vars, values, filter_enum) 2173 2174# Register Solver in _pywrapcp: 2175_pywrapcp.Solver_swigregister(Solver) 2176class BaseObject(object): 2177 r""" 2178 A BaseObject is the root of all reversibly allocated objects. 2179 A DebugString method and the associated << operator are implemented 2180 as a convenience. 2181 """ 2182 2183 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2184 2185 def __init__(self): 2186 if self.__class__ == BaseObject: 2187 _self = None 2188 else: 2189 _self = self 2190 _pywrapcp.BaseObject_swiginit(self, _pywrapcp.new_BaseObject(_self, )) 2191 __swig_destroy__ = _pywrapcp.delete_BaseObject 2192 2193 def DebugString(self): 2194 return _pywrapcp.BaseObject_DebugString(self) 2195 2196 def __str__(self): 2197 return _pywrapcp.BaseObject___str__(self) 2198 2199 def __repr__(self): 2200 return _pywrapcp.BaseObject___repr__(self) 2201 def __disown__(self): 2202 self.this.disown() 2203 _pywrapcp.disown_BaseObject(self) 2204 return weakref.proxy(self) 2205 2206# Register BaseObject in _pywrapcp: 2207_pywrapcp.BaseObject_swigregister(BaseObject) 2208class PropagationBaseObject(BaseObject): 2209 r""" 2210 NOLINT 2211 The PropagationBaseObject is a subclass of BaseObject that is also 2212 friend to the Solver class. It allows accessing methods useful when 2213 writing new constraints or new expressions. 2214 """ 2215 2216 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2217 __repr__ = _swig_repr 2218 2219 def __init__(self, s): 2220 if self.__class__ == PropagationBaseObject: 2221 _self = None 2222 else: 2223 _self = self 2224 _pywrapcp.PropagationBaseObject_swiginit(self, _pywrapcp.new_PropagationBaseObject(_self, s)) 2225 __swig_destroy__ = _pywrapcp.delete_PropagationBaseObject 2226 2227 def DebugString(self): 2228 return _pywrapcp.PropagationBaseObject_DebugString(self) 2229 2230 def solver(self): 2231 return _pywrapcp.PropagationBaseObject_solver(self) 2232 2233 def Name(self): 2234 r"""Object naming.""" 2235 return _pywrapcp.PropagationBaseObject_Name(self) 2236 def __disown__(self): 2237 self.this.disown() 2238 _pywrapcp.disown_PropagationBaseObject(self) 2239 return weakref.proxy(self) 2240 2241# Register PropagationBaseObject in _pywrapcp: 2242_pywrapcp.PropagationBaseObject_swigregister(PropagationBaseObject) 2243class Decision(BaseObject): 2244 r""" 2245 A Decision represents a choice point in the search tree. The two main 2246 methods are Apply() to go left, or Refute() to go right. 2247 """ 2248 2249 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2250 2251 def __init__(self): 2252 if self.__class__ == Decision: 2253 _self = None 2254 else: 2255 _self = self 2256 _pywrapcp.Decision_swiginit(self, _pywrapcp.new_Decision(_self, )) 2257 __swig_destroy__ = _pywrapcp.delete_Decision 2258 2259 def ApplyWrapper(self, s): 2260 r"""Apply will be called first when the decision is executed.""" 2261 return _pywrapcp.Decision_ApplyWrapper(self, s) 2262 2263 def RefuteWrapper(self, s): 2264 r"""Refute will be called after a backtrack.""" 2265 return _pywrapcp.Decision_RefuteWrapper(self, s) 2266 2267 def DebugString(self): 2268 return _pywrapcp.Decision_DebugString(self) 2269 2270 def __repr__(self): 2271 return _pywrapcp.Decision___repr__(self) 2272 2273 def __str__(self): 2274 return _pywrapcp.Decision___str__(self) 2275 def __disown__(self): 2276 self.this.disown() 2277 _pywrapcp.disown_Decision(self) 2278 return weakref.proxy(self) 2279 2280# Register Decision in _pywrapcp: 2281_pywrapcp.Decision_swigregister(Decision) 2282class DecisionBuilder(BaseObject): 2283 r""" 2284 A DecisionBuilder is responsible for creating the search tree. The 2285 important method is Next(), which returns the next decision to execute. 2286 """ 2287 2288 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2289 2290 def __init__(self): 2291 if self.__class__ == DecisionBuilder: 2292 _self = None 2293 else: 2294 _self = self 2295 _pywrapcp.DecisionBuilder_swiginit(self, _pywrapcp.new_DecisionBuilder(_self, )) 2296 __swig_destroy__ = _pywrapcp.delete_DecisionBuilder 2297 2298 def NextWrapper(self, s): 2299 r""" 2300 This is the main method of the decision builder class. It must 2301 return a decision (an instance of the class Decision). If it 2302 returns nullptr, this means that the decision builder has finished 2303 its work. 2304 """ 2305 return _pywrapcp.DecisionBuilder_NextWrapper(self, s) 2306 2307 def DebugString(self): 2308 return _pywrapcp.DecisionBuilder_DebugString(self) 2309 2310 def __repr__(self): 2311 return _pywrapcp.DecisionBuilder___repr__(self) 2312 2313 def __str__(self): 2314 return _pywrapcp.DecisionBuilder___str__(self) 2315 def __disown__(self): 2316 self.this.disown() 2317 _pywrapcp.disown_DecisionBuilder(self) 2318 return weakref.proxy(self) 2319 2320# Register DecisionBuilder in _pywrapcp: 2321_pywrapcp.DecisionBuilder_swigregister(DecisionBuilder) 2322class Demon(BaseObject): 2323 r""" 2324 A Demon is the base element of a propagation queue. It is the main 2325 object responsible for implementing the actual propagation 2326 of the constraint and pruning the inconsistent values in the domains 2327 of the variables. The main concept is that demons are listeners that are 2328 attached to the variables and listen to their modifications. 2329 There are two methods: 2330 - Run() is the actual method called when the demon is processed. 2331 - priority() returns its priority. Standard priorities are slow, normal 2332 or fast. "immediate" is reserved for variables and is treated separately. 2333 """ 2334 2335 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2336 __repr__ = _swig_repr 2337 2338 def __init__(self): 2339 r""" 2340 This indicates the priority of a demon. Immediate demons are treated 2341 separately and corresponds to variables. 2342 """ 2343 if self.__class__ == Demon: 2344 _self = None 2345 else: 2346 _self = self 2347 _pywrapcp.Demon_swiginit(self, _pywrapcp.new_Demon(_self, )) 2348 __swig_destroy__ = _pywrapcp.delete_Demon 2349 2350 def RunWrapper(self, s): 2351 r"""This is the main callback of the demon.""" 2352 return _pywrapcp.Demon_RunWrapper(self, s) 2353 2354 def Priority(self): 2355 r""" 2356 This method returns the priority of the demon. Usually a demon is 2357 fast, slow or normal. Immediate demons are reserved for internal 2358 use to maintain variables. 2359 """ 2360 return _pywrapcp.Demon_Priority(self) 2361 2362 def DebugString(self): 2363 return _pywrapcp.Demon_DebugString(self) 2364 2365 def Inhibit(self, s): 2366 r""" 2367 This method inhibits the demon in the search tree below the 2368 current position. 2369 """ 2370 return _pywrapcp.Demon_Inhibit(self, s) 2371 2372 def Desinhibit(self, s): 2373 r"""This method un-inhibits the demon that was previously inhibited.""" 2374 return _pywrapcp.Demon_Desinhibit(self, s) 2375 def __disown__(self): 2376 self.this.disown() 2377 _pywrapcp.disown_Demon(self) 2378 return weakref.proxy(self) 2379 2380# Register Demon in _pywrapcp: 2381_pywrapcp.Demon_swigregister(Demon) 2382class Constraint(PropagationBaseObject): 2383 r""" 2384 A constraint is the main modeling object. It provides two methods: 2385 - Post() is responsible for creating the demons and attaching them to 2386 immediate demons(). 2387 - InitialPropagate() is called once just after Post and performs 2388 the initial propagation. The subsequent propagations will be performed 2389 by the demons Posted during the post() method. 2390 """ 2391 2392 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2393 2394 def __init__(self, solver): 2395 if self.__class__ == Constraint: 2396 _self = None 2397 else: 2398 _self = self 2399 _pywrapcp.Constraint_swiginit(self, _pywrapcp.new_Constraint(_self, solver)) 2400 __swig_destroy__ = _pywrapcp.delete_Constraint 2401 2402 def Post(self): 2403 r""" 2404 This method is called when the constraint is processed by the 2405 solver. Its main usage is to attach demons to variables. 2406 """ 2407 return _pywrapcp.Constraint_Post(self) 2408 2409 def InitialPropagateWrapper(self): 2410 r""" 2411 This method performs the initial propagation of the 2412 constraint. It is called just after the post. 2413 """ 2414 return _pywrapcp.Constraint_InitialPropagateWrapper(self) 2415 2416 def DebugString(self): 2417 return _pywrapcp.Constraint_DebugString(self) 2418 2419 def Var(self): 2420 r""" 2421 Creates a Boolean variable representing the status of the constraint 2422 (false = constraint is violated, true = constraint is satisfied). It 2423 returns nullptr if the constraint does not support this API. 2424 """ 2425 return _pywrapcp.Constraint_Var(self) 2426 2427 def __repr__(self): 2428 return _pywrapcp.Constraint___repr__(self) 2429 2430 def __str__(self): 2431 return _pywrapcp.Constraint___str__(self) 2432 2433 def __add__(self, *args): 2434 return _pywrapcp.Constraint___add__(self, *args) 2435 2436 def __radd__(self, v): 2437 return _pywrapcp.Constraint___radd__(self, v) 2438 2439 def __sub__(self, *args): 2440 return _pywrapcp.Constraint___sub__(self, *args) 2441 2442 def __rsub__(self, v): 2443 return _pywrapcp.Constraint___rsub__(self, v) 2444 2445 def __mul__(self, *args): 2446 return _pywrapcp.Constraint___mul__(self, *args) 2447 2448 def __rmul__(self, v): 2449 return _pywrapcp.Constraint___rmul__(self, v) 2450 2451 def __floordiv__(self, v): 2452 return _pywrapcp.Constraint___floordiv__(self, v) 2453 2454 def __neg__(self): 2455 return _pywrapcp.Constraint___neg__(self) 2456 2457 def __abs__(self): 2458 return _pywrapcp.Constraint___abs__(self) 2459 2460 def Square(self): 2461 return _pywrapcp.Constraint_Square(self) 2462 2463 def __eq__(self, *args): 2464 return _pywrapcp.Constraint___eq__(self, *args) 2465 2466 def __ne__(self, *args): 2467 return _pywrapcp.Constraint___ne__(self, *args) 2468 2469 def __ge__(self, *args): 2470 return _pywrapcp.Constraint___ge__(self, *args) 2471 2472 def __gt__(self, *args): 2473 return _pywrapcp.Constraint___gt__(self, *args) 2474 2475 def __le__(self, *args): 2476 return _pywrapcp.Constraint___le__(self, *args) 2477 2478 def __lt__(self, *args): 2479 return _pywrapcp.Constraint___lt__(self, *args) 2480 2481 def MapTo(self, vars): 2482 return _pywrapcp.Constraint_MapTo(self, vars) 2483 2484 def IndexOf(self, *args): 2485 return _pywrapcp.Constraint_IndexOf(self, *args) 2486 def __disown__(self): 2487 self.this.disown() 2488 _pywrapcp.disown_Constraint(self) 2489 return weakref.proxy(self) 2490 2491# Register Constraint in _pywrapcp: 2492_pywrapcp.Constraint_swigregister(Constraint) 2493class SearchMonitor(BaseObject): 2494 r"""A search monitor is a simple set of callbacks to monitor all search events""" 2495 2496 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2497 kNoProgress = _pywrapcp.SearchMonitor_kNoProgress 2498 2499 def __init__(self, s): 2500 if self.__class__ == SearchMonitor: 2501 _self = None 2502 else: 2503 _self = self 2504 _pywrapcp.SearchMonitor_swiginit(self, _pywrapcp.new_SearchMonitor(_self, s)) 2505 __swig_destroy__ = _pywrapcp.delete_SearchMonitor 2506 2507 def EnterSearch(self): 2508 r"""Beginning of the search.""" 2509 return _pywrapcp.SearchMonitor_EnterSearch(self) 2510 2511 def RestartSearch(self): 2512 r"""Restart the search.""" 2513 return _pywrapcp.SearchMonitor_RestartSearch(self) 2514 2515 def ExitSearch(self): 2516 r"""End of the search.""" 2517 return _pywrapcp.SearchMonitor_ExitSearch(self) 2518 2519 def BeginNextDecision(self, b): 2520 r"""Before calling DecisionBuilder::Next.""" 2521 return _pywrapcp.SearchMonitor_BeginNextDecision(self, b) 2522 2523 def EndNextDecision(self, b, d): 2524 r"""After calling DecisionBuilder::Next, along with the returned decision.""" 2525 return _pywrapcp.SearchMonitor_EndNextDecision(self, b, d) 2526 2527 def ApplyDecision(self, d): 2528 r"""Before applying the decision.""" 2529 return _pywrapcp.SearchMonitor_ApplyDecision(self, d) 2530 2531 def RefuteDecision(self, d): 2532 r"""Before refuting the decision.""" 2533 return _pywrapcp.SearchMonitor_RefuteDecision(self, d) 2534 2535 def AfterDecision(self, d, apply): 2536 r""" 2537 Just after refuting or applying the decision, apply is true after Apply. 2538 This is called only if the Apply() or Refute() methods have not failed. 2539 """ 2540 return _pywrapcp.SearchMonitor_AfterDecision(self, d, apply) 2541 2542 def BeginFail(self): 2543 r"""Just when the failure occurs.""" 2544 return _pywrapcp.SearchMonitor_BeginFail(self) 2545 2546 def EndFail(self): 2547 r"""After completing the backtrack.""" 2548 return _pywrapcp.SearchMonitor_EndFail(self) 2549 2550 def BeginInitialPropagation(self): 2551 r"""Before the initial propagation.""" 2552 return _pywrapcp.SearchMonitor_BeginInitialPropagation(self) 2553 2554 def EndInitialPropagation(self): 2555 r"""After the initial propagation.""" 2556 return _pywrapcp.SearchMonitor_EndInitialPropagation(self) 2557 2558 def AcceptSolution(self): 2559 r""" 2560 This method is called when a solution is found. It asserts whether the 2561 solution is valid. A value of false indicates that the solution 2562 should be discarded. 2563 """ 2564 return _pywrapcp.SearchMonitor_AcceptSolution(self) 2565 2566 def AtSolution(self): 2567 r""" 2568 This method is called when a valid solution is found. If the 2569 return value is true, then search will resume after. If the result 2570 is false, then search will stop there. 2571 """ 2572 return _pywrapcp.SearchMonitor_AtSolution(self) 2573 2574 def NoMoreSolutions(self): 2575 r"""When the search tree is finished.""" 2576 return _pywrapcp.SearchMonitor_NoMoreSolutions(self) 2577 2578 def AcceptDelta(self, delta, deltadelta): 2579 2580 return _pywrapcp.SearchMonitor_AcceptDelta(self, delta, deltadelta) 2581 2582 def AcceptNeighbor(self): 2583 r"""After accepting a neighbor during local search.""" 2584 return _pywrapcp.SearchMonitor_AcceptNeighbor(self) 2585 2586 def ProgressPercent(self): 2587 r""" 2588 Returns a percentage representing the propress of the search before 2589 reaching limits. 2590 """ 2591 return _pywrapcp.SearchMonitor_ProgressPercent(self) 2592 2593 def solver(self): 2594 return _pywrapcp.SearchMonitor_solver(self) 2595 2596 def __repr__(self): 2597 return _pywrapcp.SearchMonitor___repr__(self) 2598 2599 def __str__(self): 2600 return _pywrapcp.SearchMonitor___str__(self) 2601 def __disown__(self): 2602 self.this.disown() 2603 _pywrapcp.disown_SearchMonitor(self) 2604 return weakref.proxy(self) 2605 2606# Register SearchMonitor in _pywrapcp: 2607_pywrapcp.SearchMonitor_swigregister(SearchMonitor) 2608class IntExpr(PropagationBaseObject): 2609 r""" 2610 The class IntExpr is the base of all integer expressions in 2611 constraint programming. 2612 It contains the basic protocol for an expression: 2613 - setting and modifying its bound 2614 - querying if it is bound 2615 - listening to events modifying its bounds 2616 - casting it into a variable (instance of IntVar) 2617 """ 2618 2619 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2620 2621 def __init__(self, *args, **kwargs): 2622 raise AttributeError("No constructor defined - class is abstract") 2623 2624 def Min(self): 2625 return _pywrapcp.IntExpr_Min(self) 2626 2627 def SetMin(self, m): 2628 return _pywrapcp.IntExpr_SetMin(self, m) 2629 2630 def Max(self): 2631 return _pywrapcp.IntExpr_Max(self) 2632 2633 def SetMax(self, m): 2634 return _pywrapcp.IntExpr_SetMax(self, m) 2635 2636 def SetRange(self, l, u): 2637 r"""This method sets both the min and the max of the expression.""" 2638 return _pywrapcp.IntExpr_SetRange(self, l, u) 2639 2640 def SetValue(self, v): 2641 r"""This method sets the value of the expression.""" 2642 return _pywrapcp.IntExpr_SetValue(self, v) 2643 2644 def Bound(self): 2645 r"""Returns true if the min and the max of the expression are equal.""" 2646 return _pywrapcp.IntExpr_Bound(self) 2647 2648 def IsVar(self): 2649 r"""Returns true if the expression is indeed a variable.""" 2650 return _pywrapcp.IntExpr_IsVar(self) 2651 2652 def Var(self): 2653 r"""Creates a variable from the expression.""" 2654 return _pywrapcp.IntExpr_Var(self) 2655 2656 def VarWithName(self, name): 2657 r""" 2658 Creates a variable from the expression and set the name of the 2659 resulting var. If the expression is already a variable, then it 2660 will set the name of the expression, possibly overwriting it. 2661 This is just a shortcut to Var() followed by set_name(). 2662 """ 2663 return _pywrapcp.IntExpr_VarWithName(self, name) 2664 2665 def WhenRange(self, *args): 2666 r""" 2667 *Overload 1:* 2668 Attach a demon that will watch the min or the max of the expression. 2669 2670 | 2671 2672 *Overload 2:* 2673 Attach a demon that will watch the min or the max of the expression. 2674 """ 2675 return _pywrapcp.IntExpr_WhenRange(self, *args) 2676 2677 def __repr__(self): 2678 return _pywrapcp.IntExpr___repr__(self) 2679 2680 def __str__(self): 2681 return _pywrapcp.IntExpr___str__(self) 2682 2683 def __add__(self, *args): 2684 return _pywrapcp.IntExpr___add__(self, *args) 2685 2686 def __radd__(self, v): 2687 return _pywrapcp.IntExpr___radd__(self, v) 2688 2689 def __sub__(self, *args): 2690 return _pywrapcp.IntExpr___sub__(self, *args) 2691 2692 def __rsub__(self, v): 2693 return _pywrapcp.IntExpr___rsub__(self, v) 2694 2695 def __mul__(self, *args): 2696 return _pywrapcp.IntExpr___mul__(self, *args) 2697 2698 def __rmul__(self, v): 2699 return _pywrapcp.IntExpr___rmul__(self, v) 2700 2701 def __floordiv__(self, *args): 2702 return _pywrapcp.IntExpr___floordiv__(self, *args) 2703 2704 def __mod__(self, *args): 2705 return _pywrapcp.IntExpr___mod__(self, *args) 2706 2707 def __neg__(self): 2708 return _pywrapcp.IntExpr___neg__(self) 2709 2710 def __abs__(self): 2711 return _pywrapcp.IntExpr___abs__(self) 2712 2713 def Square(self): 2714 return _pywrapcp.IntExpr_Square(self) 2715 2716 def __eq__(self, *args): 2717 return _pywrapcp.IntExpr___eq__(self, *args) 2718 2719 def __ne__(self, *args): 2720 return _pywrapcp.IntExpr___ne__(self, *args) 2721 2722 def __ge__(self, *args): 2723 return _pywrapcp.IntExpr___ge__(self, *args) 2724 2725 def __gt__(self, *args): 2726 return _pywrapcp.IntExpr___gt__(self, *args) 2727 2728 def __le__(self, *args): 2729 return _pywrapcp.IntExpr___le__(self, *args) 2730 2731 def __lt__(self, *args): 2732 return _pywrapcp.IntExpr___lt__(self, *args) 2733 2734 def MapTo(self, vars): 2735 return _pywrapcp.IntExpr_MapTo(self, vars) 2736 2737 def IndexOf(self, *args): 2738 return _pywrapcp.IntExpr_IndexOf(self, *args) 2739 2740 def IsMember(self, values): 2741 return _pywrapcp.IntExpr_IsMember(self, values) 2742 2743 def Member(self, values): 2744 return _pywrapcp.IntExpr_Member(self, values) 2745 2746 def NotMember(self, starts, ends): 2747 return _pywrapcp.IntExpr_NotMember(self, starts, ends) 2748 2749# Register IntExpr in _pywrapcp: 2750_pywrapcp.IntExpr_swigregister(IntExpr) 2751class IntVarIterator(BaseObject): 2752 r""" 2753 The class Iterator has two direct subclasses. HoleIterators 2754 iterates over all holes, that is value removed between the 2755 current min and max of the variable since the last time the 2756 variable was processed in the queue. DomainIterators iterates 2757 over all elements of the variable domain. Both iterators are not 2758 robust to domain changes. Hole iterators can also report values outside 2759 the current min and max of the variable. 2760 HoleIterators should only be called from a demon attached to the 2761 variable that has created this iterator. 2762 IntVar* current_var; 2763 std::unique_ptr<IntVarIterator> it(current_var->MakeHoleIterator(false)); 2764 for (const int64_t hole : InitAndGetValues(it)) { 2765 use the hole 2766 } 2767 """ 2768 2769 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2770 2771 def __init__(self, *args, **kwargs): 2772 raise AttributeError("No constructor defined - class is abstract") 2773 __repr__ = _swig_repr 2774 2775 def Init(self): 2776 r"""This method must be called before each loop.""" 2777 return _pywrapcp.IntVarIterator_Init(self) 2778 2779 def Ok(self): 2780 r"""This method indicates if we can call Value() or not.""" 2781 return _pywrapcp.IntVarIterator_Ok(self) 2782 2783 def Value(self): 2784 r"""This method returns the current value of the iterator.""" 2785 return _pywrapcp.IntVarIterator_Value(self) 2786 2787 def Next(self): 2788 r"""This method moves the iterator to the next value.""" 2789 return _pywrapcp.IntVarIterator_Next(self) 2790 2791 def DebugString(self): 2792 r"""Pretty Print.""" 2793 return _pywrapcp.IntVarIterator_DebugString(self) 2794 2795 def __iter__(self): 2796 self.Init() 2797 return self 2798 2799 def next(self): 2800 if self.Ok(): 2801 result = self.Value() 2802 self.Next() 2803 return result 2804 else: 2805 raise StopIteration() 2806 2807 def __next__(self): 2808 return self.next() 2809 2810 2811# Register IntVarIterator in _pywrapcp: 2812_pywrapcp.IntVarIterator_swigregister(IntVarIterator) 2813class IntVar(IntExpr): 2814 r""" 2815 The class IntVar is a subset of IntExpr. In addition to the 2816 IntExpr protocol, it offers persistence, removing values from the domains, 2817 and a finer model for events. 2818 """ 2819 2820 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2821 2822 def __init__(self, *args, **kwargs): 2823 raise AttributeError("No constructor defined - class is abstract") 2824 2825 def IsVar(self): 2826 return _pywrapcp.IntVar_IsVar(self) 2827 2828 def Var(self): 2829 return _pywrapcp.IntVar_Var(self) 2830 2831 def Value(self): 2832 r""" 2833 This method returns the value of the variable. This method checks 2834 before that the variable is bound. 2835 """ 2836 return _pywrapcp.IntVar_Value(self) 2837 2838 def RemoveValue(self, v): 2839 r"""This method removes the value 'v' from the domain of the variable.""" 2840 return _pywrapcp.IntVar_RemoveValue(self, v) 2841 2842 def RemoveInterval(self, l, u): 2843 r""" 2844 This method removes the interval 'l' .. 'u' from the domain of 2845 the variable. It assumes that 'l' <= 'u'. 2846 """ 2847 return _pywrapcp.IntVar_RemoveInterval(self, l, u) 2848 2849 def RemoveValues(self, values): 2850 r"""This method remove the values from the domain of the variable.""" 2851 return _pywrapcp.IntVar_RemoveValues(self, values) 2852 2853 def SetValues(self, values): 2854 r"""This method intersects the current domain with the values in the array.""" 2855 return _pywrapcp.IntVar_SetValues(self, values) 2856 2857 def WhenBound(self, *args): 2858 r""" 2859 *Overload 1:* 2860 This method attaches a demon that will be awakened when the 2861 variable is bound. 2862 2863 | 2864 2865 *Overload 2:* 2866 This method attaches a closure that will be awakened when the 2867 variable is bound. 2868 """ 2869 return _pywrapcp.IntVar_WhenBound(self, *args) 2870 2871 def WhenDomain(self, *args): 2872 r""" 2873 *Overload 1:* 2874 This method attaches a demon that will watch any domain 2875 modification of the domain of the variable. 2876 2877 | 2878 2879 *Overload 2:* 2880 This method attaches a closure that will watch any domain 2881 modification of the domain of the variable. 2882 """ 2883 return _pywrapcp.IntVar_WhenDomain(self, *args) 2884 2885 def Size(self): 2886 r"""This method returns the number of values in the domain of the variable.""" 2887 return _pywrapcp.IntVar_Size(self) 2888 2889 def Contains(self, v): 2890 r""" 2891 This method returns whether the value 'v' is in the domain of the 2892 variable. 2893 """ 2894 return _pywrapcp.IntVar_Contains(self, v) 2895 2896 def HoleIteratorAux(self, reversible): 2897 r""" 2898 Creates a hole iterator. When 'reversible' is false, the returned 2899 object is created on the normal C++ heap and the solver does NOT 2900 take ownership of the object. 2901 """ 2902 return _pywrapcp.IntVar_HoleIteratorAux(self, reversible) 2903 2904 def DomainIteratorAux(self, reversible): 2905 r""" 2906 Creates a domain iterator. When 'reversible' is false, the 2907 returned object is created on the normal C++ heap and the solver 2908 does NOT take ownership of the object. 2909 """ 2910 return _pywrapcp.IntVar_DomainIteratorAux(self, reversible) 2911 2912 def OldMin(self): 2913 r"""Returns the previous min.""" 2914 return _pywrapcp.IntVar_OldMin(self) 2915 2916 def OldMax(self): 2917 r"""Returns the previous max.""" 2918 return _pywrapcp.IntVar_OldMax(self) 2919 2920 def __repr__(self): 2921 return _pywrapcp.IntVar___repr__(self) 2922 2923 def __str__(self): 2924 return _pywrapcp.IntVar___str__(self) 2925 2926 def DomainIterator(self): 2927 return iter(self.DomainIteratorAux(False)) 2928 2929 def HoleIterator(self): 2930 return iter(self.HoleIteratorAux(False)) 2931 2932 2933# Register IntVar in _pywrapcp: 2934_pywrapcp.IntVar_swigregister(IntVar) 2935class SolutionCollector(SearchMonitor): 2936 r""" 2937 This class is the root class of all solution collectors. 2938 It implements a basic query API to be used independently 2939 of the collector used. 2940 """ 2941 2942 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2943 2944 def __init__(self, *args, **kwargs): 2945 raise AttributeError("No constructor defined") 2946 __repr__ = _swig_repr 2947 2948 def DebugString(self): 2949 return _pywrapcp.SolutionCollector_DebugString(self) 2950 2951 def Add(self, *args): 2952 r"""Add API.""" 2953 return _pywrapcp.SolutionCollector_Add(self, *args) 2954 2955 def AddObjective(self, objective): 2956 return _pywrapcp.SolutionCollector_AddObjective(self, objective) 2957 2958 def EnterSearch(self): 2959 r"""Beginning of the search.""" 2960 return _pywrapcp.SolutionCollector_EnterSearch(self) 2961 2962 def SolutionCount(self): 2963 r"""Returns how many solutions were stored during the search.""" 2964 return _pywrapcp.SolutionCollector_SolutionCount(self) 2965 2966 def Solution(self, n): 2967 r"""Returns the nth solution.""" 2968 return _pywrapcp.SolutionCollector_Solution(self, n) 2969 2970 def WallTime(self, n): 2971 r"""Returns the wall time in ms for the nth solution.""" 2972 return _pywrapcp.SolutionCollector_WallTime(self, n) 2973 2974 def Branches(self, n): 2975 r"""Returns the number of branches when the nth solution was found.""" 2976 return _pywrapcp.SolutionCollector_Branches(self, n) 2977 2978 def Failures(self, n): 2979 r""" 2980 Returns the number of failures encountered at the time of the nth 2981 solution. 2982 """ 2983 return _pywrapcp.SolutionCollector_Failures(self, n) 2984 2985 def ObjectiveValue(self, n): 2986 r"""Returns the objective value of the nth solution.""" 2987 return _pywrapcp.SolutionCollector_ObjectiveValue(self, n) 2988 2989 def Value(self, n, var): 2990 r"""This is a shortcut to get the Value of 'var' in the nth solution.""" 2991 return _pywrapcp.SolutionCollector_Value(self, n, var) 2992 2993 def StartValue(self, n, var): 2994 r"""This is a shortcut to get the StartValue of 'var' in the nth solution.""" 2995 return _pywrapcp.SolutionCollector_StartValue(self, n, var) 2996 2997 def EndValue(self, n, var): 2998 r"""This is a shortcut to get the EndValue of 'var' in the nth solution.""" 2999 return _pywrapcp.SolutionCollector_EndValue(self, n, var) 3000 3001 def DurationValue(self, n, var): 3002 r"""This is a shortcut to get the DurationValue of 'var' in the nth solution.""" 3003 return _pywrapcp.SolutionCollector_DurationValue(self, n, var) 3004 3005 def PerformedValue(self, n, var): 3006 r"""This is a shortcut to get the PerformedValue of 'var' in the nth solution.""" 3007 return _pywrapcp.SolutionCollector_PerformedValue(self, n, var) 3008 3009 def ForwardSequence(self, n, var): 3010 r""" 3011 This is a shortcut to get the ForwardSequence of 'var' in the 3012 nth solution. The forward sequence is the list of ranked interval 3013 variables starting from the start of the sequence. 3014 """ 3015 return _pywrapcp.SolutionCollector_ForwardSequence(self, n, var) 3016 3017 def BackwardSequence(self, n, var): 3018 r""" 3019 This is a shortcut to get the BackwardSequence of 'var' in the 3020 nth solution. The backward sequence is the list of ranked interval 3021 variables starting from the end of the sequence. 3022 """ 3023 return _pywrapcp.SolutionCollector_BackwardSequence(self, n, var) 3024 3025 def Unperformed(self, n, var): 3026 r""" 3027 This is a shortcut to get the list of unperformed of 'var' in the 3028 nth solution. 3029 """ 3030 return _pywrapcp.SolutionCollector_Unperformed(self, n, var) 3031 3032# Register SolutionCollector in _pywrapcp: 3033_pywrapcp.SolutionCollector_swigregister(SolutionCollector) 3034class OptimizeVar(object): 3035 r""" 3036 This class encapsulates an objective. It requires the direction 3037 (minimize or maximize), the variable to optimize, and the 3038 improvement step. 3039 """ 3040 3041 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3042 3043 def __init__(self, *args, **kwargs): 3044 raise AttributeError("No constructor defined") 3045 __repr__ = _swig_repr 3046 3047 def Best(self): 3048 r"""Returns the best value found during search.""" 3049 return _pywrapcp.OptimizeVar_Best(self) 3050 3051 def BeginNextDecision(self, db): 3052 r"""Internal methods.""" 3053 return _pywrapcp.OptimizeVar_BeginNextDecision(self, db) 3054 3055 def RefuteDecision(self, d): 3056 return _pywrapcp.OptimizeVar_RefuteDecision(self, d) 3057 3058 def AtSolution(self): 3059 return _pywrapcp.OptimizeVar_AtSolution(self) 3060 3061 def AcceptSolution(self): 3062 return _pywrapcp.OptimizeVar_AcceptSolution(self) 3063 3064 def DebugString(self): 3065 return _pywrapcp.OptimizeVar_DebugString(self) 3066 __swig_destroy__ = _pywrapcp.delete_OptimizeVar 3067 3068# Register OptimizeVar in _pywrapcp: 3069_pywrapcp.OptimizeVar_swigregister(OptimizeVar) 3070class SearchLimit(SearchMonitor): 3071 r"""Base class of all search limits.""" 3072 3073 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3074 3075 def __init__(self, *args, **kwargs): 3076 raise AttributeError("No constructor defined - class is abstract") 3077 __repr__ = _swig_repr 3078 __swig_destroy__ = _pywrapcp.delete_SearchLimit 3079 3080 def Crossed(self): 3081 r"""Returns true if the limit has been crossed.""" 3082 return _pywrapcp.SearchLimit_Crossed(self) 3083 3084 def Check(self): 3085 r""" 3086 This method is called to check the status of the limit. A return 3087 value of true indicates that we have indeed crossed the limit. In 3088 that case, this method will not be called again and the remaining 3089 search will be discarded. 3090 """ 3091 return _pywrapcp.SearchLimit_Check(self) 3092 3093 def Init(self): 3094 r"""This method is called when the search limit is initialized.""" 3095 return _pywrapcp.SearchLimit_Init(self) 3096 3097 def EnterSearch(self): 3098 r"""Internal methods.""" 3099 return _pywrapcp.SearchLimit_EnterSearch(self) 3100 3101 def BeginNextDecision(self, b): 3102 return _pywrapcp.SearchLimit_BeginNextDecision(self, b) 3103 3104 def RefuteDecision(self, d): 3105 return _pywrapcp.SearchLimit_RefuteDecision(self, d) 3106 3107 def DebugString(self): 3108 return _pywrapcp.SearchLimit_DebugString(self) 3109 3110# Register SearchLimit in _pywrapcp: 3111_pywrapcp.SearchLimit_swigregister(SearchLimit) 3112class IntervalVar(PropagationBaseObject): 3113 r""" 3114 Interval variables are often used in scheduling. The main characteristics 3115 of an IntervalVar are the start position, duration, and end 3116 date. All these characteristics can be queried and set, and demons can 3117 be posted on their modifications. 3118 3119 An important aspect is optionality: an IntervalVar can be performed or not. 3120 If unperformed, then it simply does not exist, and its characteristics 3121 cannot be accessed any more. An interval var is automatically marked 3122 as unperformed when it is not consistent anymore (start greater 3123 than end, duration < 0...) 3124 """ 3125 3126 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3127 3128 def __init__(self, *args, **kwargs): 3129 raise AttributeError("No constructor defined - class is abstract") 3130 3131 def StartMin(self): 3132 r""" 3133 These methods query, set, and watch the start position of the 3134 interval var. 3135 """ 3136 return _pywrapcp.IntervalVar_StartMin(self) 3137 3138 def StartMax(self): 3139 return _pywrapcp.IntervalVar_StartMax(self) 3140 3141 def SetStartMin(self, m): 3142 return _pywrapcp.IntervalVar_SetStartMin(self, m) 3143 3144 def SetStartMax(self, m): 3145 return _pywrapcp.IntervalVar_SetStartMax(self, m) 3146 3147 def SetStartRange(self, mi, ma): 3148 return _pywrapcp.IntervalVar_SetStartRange(self, mi, ma) 3149 3150 def OldStartMin(self): 3151 return _pywrapcp.IntervalVar_OldStartMin(self) 3152 3153 def OldStartMax(self): 3154 return _pywrapcp.IntervalVar_OldStartMax(self) 3155 3156 def WhenStartRange(self, *args): 3157 return _pywrapcp.IntervalVar_WhenStartRange(self, *args) 3158 3159 def WhenStartBound(self, *args): 3160 return _pywrapcp.IntervalVar_WhenStartBound(self, *args) 3161 3162 def DurationMin(self): 3163 r"""These methods query, set, and watch the duration of the interval var.""" 3164 return _pywrapcp.IntervalVar_DurationMin(self) 3165 3166 def DurationMax(self): 3167 return _pywrapcp.IntervalVar_DurationMax(self) 3168 3169 def SetDurationMin(self, m): 3170 return _pywrapcp.IntervalVar_SetDurationMin(self, m) 3171 3172 def SetDurationMax(self, m): 3173 return _pywrapcp.IntervalVar_SetDurationMax(self, m) 3174 3175 def SetDurationRange(self, mi, ma): 3176 return _pywrapcp.IntervalVar_SetDurationRange(self, mi, ma) 3177 3178 def OldDurationMin(self): 3179 return _pywrapcp.IntervalVar_OldDurationMin(self) 3180 3181 def OldDurationMax(self): 3182 return _pywrapcp.IntervalVar_OldDurationMax(self) 3183 3184 def WhenDurationRange(self, *args): 3185 return _pywrapcp.IntervalVar_WhenDurationRange(self, *args) 3186 3187 def WhenDurationBound(self, *args): 3188 return _pywrapcp.IntervalVar_WhenDurationBound(self, *args) 3189 3190 def EndMin(self): 3191 r"""These methods query, set, and watch the end position of the interval var.""" 3192 return _pywrapcp.IntervalVar_EndMin(self) 3193 3194 def EndMax(self): 3195 return _pywrapcp.IntervalVar_EndMax(self) 3196 3197 def SetEndMin(self, m): 3198 return _pywrapcp.IntervalVar_SetEndMin(self, m) 3199 3200 def SetEndMax(self, m): 3201 return _pywrapcp.IntervalVar_SetEndMax(self, m) 3202 3203 def SetEndRange(self, mi, ma): 3204 return _pywrapcp.IntervalVar_SetEndRange(self, mi, ma) 3205 3206 def OldEndMin(self): 3207 return _pywrapcp.IntervalVar_OldEndMin(self) 3208 3209 def OldEndMax(self): 3210 return _pywrapcp.IntervalVar_OldEndMax(self) 3211 3212 def WhenEndRange(self, *args): 3213 return _pywrapcp.IntervalVar_WhenEndRange(self, *args) 3214 3215 def WhenEndBound(self, *args): 3216 return _pywrapcp.IntervalVar_WhenEndBound(self, *args) 3217 3218 def MustBePerformed(self): 3219 r""" 3220 These methods query, set, and watch the performed status of the 3221 interval var. 3222 """ 3223 return _pywrapcp.IntervalVar_MustBePerformed(self) 3224 3225 def MayBePerformed(self): 3226 return _pywrapcp.IntervalVar_MayBePerformed(self) 3227 3228 def CannotBePerformed(self): 3229 return _pywrapcp.IntervalVar_CannotBePerformed(self) 3230 3231 def IsPerformedBound(self): 3232 return _pywrapcp.IntervalVar_IsPerformedBound(self) 3233 3234 def SetPerformed(self, val): 3235 return _pywrapcp.IntervalVar_SetPerformed(self, val) 3236 3237 def WasPerformedBound(self): 3238 return _pywrapcp.IntervalVar_WasPerformedBound(self) 3239 3240 def WhenPerformedBound(self, *args): 3241 return _pywrapcp.IntervalVar_WhenPerformedBound(self, *args) 3242 3243 def WhenAnything(self, *args): 3244 r""" 3245 *Overload 1:* 3246 Attaches a demon awakened when anything about this interval changes. 3247 3248 | 3249 3250 *Overload 2:* 3251 Attaches a closure awakened when anything about this interval changes. 3252 """ 3253 return _pywrapcp.IntervalVar_WhenAnything(self, *args) 3254 3255 def StartExpr(self): 3256 r""" 3257 These methods create expressions encapsulating the start, end 3258 and duration of the interval var. Please note that these must not 3259 be used if the interval var is unperformed. 3260 """ 3261 return _pywrapcp.IntervalVar_StartExpr(self) 3262 3263 def DurationExpr(self): 3264 return _pywrapcp.IntervalVar_DurationExpr(self) 3265 3266 def EndExpr(self): 3267 return _pywrapcp.IntervalVar_EndExpr(self) 3268 3269 def PerformedExpr(self): 3270 return _pywrapcp.IntervalVar_PerformedExpr(self) 3271 3272 def SafeStartExpr(self, unperformed_value): 3273 r""" 3274 These methods create expressions encapsulating the start, end 3275 and duration of the interval var. If the interval var is 3276 unperformed, they will return the unperformed_value. 3277 """ 3278 return _pywrapcp.IntervalVar_SafeStartExpr(self, unperformed_value) 3279 3280 def SafeDurationExpr(self, unperformed_value): 3281 return _pywrapcp.IntervalVar_SafeDurationExpr(self, unperformed_value) 3282 3283 def SafeEndExpr(self, unperformed_value): 3284 return _pywrapcp.IntervalVar_SafeEndExpr(self, unperformed_value) 3285 3286 def EndsAfterEnd(self, other): 3287 return _pywrapcp.IntervalVar_EndsAfterEnd(self, other) 3288 3289 def EndsAfterEndWithDelay(self, other, delay): 3290 return _pywrapcp.IntervalVar_EndsAfterEndWithDelay(self, other, delay) 3291 3292 def EndsAfterStart(self, other): 3293 return _pywrapcp.IntervalVar_EndsAfterStart(self, other) 3294 3295 def EndsAfterStartWithDelay(self, other, delay): 3296 return _pywrapcp.IntervalVar_EndsAfterStartWithDelay(self, other, delay) 3297 3298 def EndsAtEnd(self, other): 3299 return _pywrapcp.IntervalVar_EndsAtEnd(self, other) 3300 3301 def EndsAtEndWithDelay(self, other, delay): 3302 return _pywrapcp.IntervalVar_EndsAtEndWithDelay(self, other, delay) 3303 3304 def EndsAtStart(self, other): 3305 return _pywrapcp.IntervalVar_EndsAtStart(self, other) 3306 3307 def EndsAtStartWithDelay(self, other, delay): 3308 return _pywrapcp.IntervalVar_EndsAtStartWithDelay(self, other, delay) 3309 3310 def StartsAfterEnd(self, other): 3311 return _pywrapcp.IntervalVar_StartsAfterEnd(self, other) 3312 3313 def StartsAfterEndWithDelay(self, other, delay): 3314 return _pywrapcp.IntervalVar_StartsAfterEndWithDelay(self, other, delay) 3315 3316 def StartsAfterStart(self, other): 3317 return _pywrapcp.IntervalVar_StartsAfterStart(self, other) 3318 3319 def StartsAfterStartWithDelay(self, other, delay): 3320 return _pywrapcp.IntervalVar_StartsAfterStartWithDelay(self, other, delay) 3321 3322 def StartsAtEnd(self, other): 3323 return _pywrapcp.IntervalVar_StartsAtEnd(self, other) 3324 3325 def StartsAtEndWithDelay(self, other, delay): 3326 return _pywrapcp.IntervalVar_StartsAtEndWithDelay(self, other, delay) 3327 3328 def StartsAtStart(self, other): 3329 return _pywrapcp.IntervalVar_StartsAtStart(self, other) 3330 3331 def StartsAtStartWithDelay(self, other, delay): 3332 return _pywrapcp.IntervalVar_StartsAtStartWithDelay(self, other, delay) 3333 3334 def StaysInSync(self, other): 3335 return _pywrapcp.IntervalVar_StaysInSync(self, other) 3336 3337 def StaysInSyncWithDelay(self, other, delay): 3338 return _pywrapcp.IntervalVar_StaysInSyncWithDelay(self, other, delay) 3339 3340 def EndsAfter(self, date): 3341 return _pywrapcp.IntervalVar_EndsAfter(self, date) 3342 3343 def EndsAt(self, date): 3344 return _pywrapcp.IntervalVar_EndsAt(self, date) 3345 3346 def EndsBefore(self, date): 3347 return _pywrapcp.IntervalVar_EndsBefore(self, date) 3348 3349 def StartsAfter(self, date): 3350 return _pywrapcp.IntervalVar_StartsAfter(self, date) 3351 3352 def StartsAt(self, date): 3353 return _pywrapcp.IntervalVar_StartsAt(self, date) 3354 3355 def StartsBefore(self, date): 3356 return _pywrapcp.IntervalVar_StartsBefore(self, date) 3357 3358 def CrossesDate(self, date): 3359 return _pywrapcp.IntervalVar_CrossesDate(self, date) 3360 3361 def AvoidsDate(self, date): 3362 return _pywrapcp.IntervalVar_AvoidsDate(self, date) 3363 3364 def __repr__(self): 3365 return _pywrapcp.IntervalVar___repr__(self) 3366 3367 def __str__(self): 3368 return _pywrapcp.IntervalVar___str__(self) 3369 3370# Register IntervalVar in _pywrapcp: 3371_pywrapcp.IntervalVar_swigregister(IntervalVar) 3372class SequenceVar(PropagationBaseObject): 3373 r""" 3374 A sequence variable is a variable whose domain is a set of possible 3375 orderings of the interval variables. It allows ordering of tasks. It 3376 has two sets of methods: ComputePossibleFirstsAndLasts(), which 3377 returns the list of interval variables that can be ranked first or 3378 last; and RankFirst/RankNotFirst/RankLast/RankNotLast, which can be 3379 used to create the search decision. 3380 """ 3381 3382 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3383 3384 def __init__(self, *args, **kwargs): 3385 raise AttributeError("No constructor defined") 3386 3387 def DebugString(self): 3388 return _pywrapcp.SequenceVar_DebugString(self) 3389 3390 def RankFirst(self, index): 3391 r""" 3392 Ranks the index_th interval var first of all unranked interval 3393 vars. After that, it will no longer be considered ranked. 3394 """ 3395 return _pywrapcp.SequenceVar_RankFirst(self, index) 3396 3397 def RankNotFirst(self, index): 3398 r""" 3399 Indicates that the index_th interval var will not be ranked first 3400 of all currently unranked interval vars. 3401 """ 3402 return _pywrapcp.SequenceVar_RankNotFirst(self, index) 3403 3404 def RankLast(self, index): 3405 r""" 3406 Ranks the index_th interval var first of all unranked interval 3407 vars. After that, it will no longer be considered ranked. 3408 """ 3409 return _pywrapcp.SequenceVar_RankLast(self, index) 3410 3411 def RankNotLast(self, index): 3412 r""" 3413 Indicates that the index_th interval var will not be ranked first 3414 of all currently unranked interval vars. 3415 """ 3416 return _pywrapcp.SequenceVar_RankNotLast(self, index) 3417 3418 def Interval(self, index): 3419 r"""Returns the index_th interval of the sequence.""" 3420 return _pywrapcp.SequenceVar_Interval(self, index) 3421 3422 def Next(self, index): 3423 r"""Returns the next of the index_th interval of the sequence.""" 3424 return _pywrapcp.SequenceVar_Next(self, index) 3425 3426 def Size(self): 3427 r"""Returns the number of interval vars in the sequence.""" 3428 return _pywrapcp.SequenceVar_Size(self) 3429 3430 def __repr__(self): 3431 return _pywrapcp.SequenceVar___repr__(self) 3432 3433 def __str__(self): 3434 return _pywrapcp.SequenceVar___str__(self) 3435 3436# Register SequenceVar in _pywrapcp: 3437_pywrapcp.SequenceVar_swigregister(SequenceVar) 3438class AssignmentElement(object): 3439 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3440 3441 def __init__(self, *args, **kwargs): 3442 raise AttributeError("No constructor defined") 3443 __repr__ = _swig_repr 3444 3445 def Activate(self): 3446 return _pywrapcp.AssignmentElement_Activate(self) 3447 3448 def Deactivate(self): 3449 return _pywrapcp.AssignmentElement_Deactivate(self) 3450 3451 def Activated(self): 3452 return _pywrapcp.AssignmentElement_Activated(self) 3453 __swig_destroy__ = _pywrapcp.delete_AssignmentElement 3454 3455# Register AssignmentElement in _pywrapcp: 3456_pywrapcp.AssignmentElement_swigregister(AssignmentElement) 3457class IntVarElement(AssignmentElement): 3458 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3459 3460 def __init__(self, *args, **kwargs): 3461 raise AttributeError("No constructor defined") 3462 __repr__ = _swig_repr 3463 3464 def Var(self): 3465 return _pywrapcp.IntVarElement_Var(self) 3466 3467 def Min(self): 3468 return _pywrapcp.IntVarElement_Min(self) 3469 3470 def SetMin(self, m): 3471 return _pywrapcp.IntVarElement_SetMin(self, m) 3472 3473 def Max(self): 3474 return _pywrapcp.IntVarElement_Max(self) 3475 3476 def SetMax(self, m): 3477 return _pywrapcp.IntVarElement_SetMax(self, m) 3478 3479 def Value(self): 3480 return _pywrapcp.IntVarElement_Value(self) 3481 3482 def Bound(self): 3483 return _pywrapcp.IntVarElement_Bound(self) 3484 3485 def SetRange(self, l, u): 3486 return _pywrapcp.IntVarElement_SetRange(self, l, u) 3487 3488 def SetValue(self, v): 3489 return _pywrapcp.IntVarElement_SetValue(self, v) 3490 3491 def __eq__(self, element): 3492 return _pywrapcp.IntVarElement___eq__(self, element) 3493 3494 def __ne__(self, element): 3495 return _pywrapcp.IntVarElement___ne__(self, element) 3496 __swig_destroy__ = _pywrapcp.delete_IntVarElement 3497 3498# Register IntVarElement in _pywrapcp: 3499_pywrapcp.IntVarElement_swigregister(IntVarElement) 3500class IntervalVarElement(AssignmentElement): 3501 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3502 3503 def __init__(self, *args, **kwargs): 3504 raise AttributeError("No constructor defined") 3505 __repr__ = _swig_repr 3506 3507 def Var(self): 3508 return _pywrapcp.IntervalVarElement_Var(self) 3509 3510 def StartMin(self): 3511 return _pywrapcp.IntervalVarElement_StartMin(self) 3512 3513 def StartMax(self): 3514 return _pywrapcp.IntervalVarElement_StartMax(self) 3515 3516 def StartValue(self): 3517 return _pywrapcp.IntervalVarElement_StartValue(self) 3518 3519 def DurationMin(self): 3520 return _pywrapcp.IntervalVarElement_DurationMin(self) 3521 3522 def DurationMax(self): 3523 return _pywrapcp.IntervalVarElement_DurationMax(self) 3524 3525 def DurationValue(self): 3526 return _pywrapcp.IntervalVarElement_DurationValue(self) 3527 3528 def EndMin(self): 3529 return _pywrapcp.IntervalVarElement_EndMin(self) 3530 3531 def EndMax(self): 3532 return _pywrapcp.IntervalVarElement_EndMax(self) 3533 3534 def EndValue(self): 3535 return _pywrapcp.IntervalVarElement_EndValue(self) 3536 3537 def PerformedMin(self): 3538 return _pywrapcp.IntervalVarElement_PerformedMin(self) 3539 3540 def PerformedMax(self): 3541 return _pywrapcp.IntervalVarElement_PerformedMax(self) 3542 3543 def PerformedValue(self): 3544 return _pywrapcp.IntervalVarElement_PerformedValue(self) 3545 3546 def SetStartMin(self, m): 3547 return _pywrapcp.IntervalVarElement_SetStartMin(self, m) 3548 3549 def SetStartMax(self, m): 3550 return _pywrapcp.IntervalVarElement_SetStartMax(self, m) 3551 3552 def SetStartRange(self, mi, ma): 3553 return _pywrapcp.IntervalVarElement_SetStartRange(self, mi, ma) 3554 3555 def SetStartValue(self, v): 3556 return _pywrapcp.IntervalVarElement_SetStartValue(self, v) 3557 3558 def SetDurationMin(self, m): 3559 return _pywrapcp.IntervalVarElement_SetDurationMin(self, m) 3560 3561 def SetDurationMax(self, m): 3562 return _pywrapcp.IntervalVarElement_SetDurationMax(self, m) 3563 3564 def SetDurationRange(self, mi, ma): 3565 return _pywrapcp.IntervalVarElement_SetDurationRange(self, mi, ma) 3566 3567 def SetDurationValue(self, v): 3568 return _pywrapcp.IntervalVarElement_SetDurationValue(self, v) 3569 3570 def SetEndMin(self, m): 3571 return _pywrapcp.IntervalVarElement_SetEndMin(self, m) 3572 3573 def SetEndMax(self, m): 3574 return _pywrapcp.IntervalVarElement_SetEndMax(self, m) 3575 3576 def SetEndRange(self, mi, ma): 3577 return _pywrapcp.IntervalVarElement_SetEndRange(self, mi, ma) 3578 3579 def SetEndValue(self, v): 3580 return _pywrapcp.IntervalVarElement_SetEndValue(self, v) 3581 3582 def SetPerformedMin(self, m): 3583 return _pywrapcp.IntervalVarElement_SetPerformedMin(self, m) 3584 3585 def SetPerformedMax(self, m): 3586 return _pywrapcp.IntervalVarElement_SetPerformedMax(self, m) 3587 3588 def SetPerformedRange(self, mi, ma): 3589 return _pywrapcp.IntervalVarElement_SetPerformedRange(self, mi, ma) 3590 3591 def SetPerformedValue(self, v): 3592 return _pywrapcp.IntervalVarElement_SetPerformedValue(self, v) 3593 3594 def __eq__(self, element): 3595 return _pywrapcp.IntervalVarElement___eq__(self, element) 3596 3597 def __ne__(self, element): 3598 return _pywrapcp.IntervalVarElement___ne__(self, element) 3599 __swig_destroy__ = _pywrapcp.delete_IntervalVarElement 3600 3601# Register IntervalVarElement in _pywrapcp: 3602_pywrapcp.IntervalVarElement_swigregister(IntervalVarElement) 3603class SequenceVarElement(AssignmentElement): 3604 r""" 3605 The SequenceVarElement stores a partial representation of ranked 3606 interval variables in the underlying sequence variable. 3607 This representation consists of three vectors: 3608 - the forward sequence. That is the list of interval variables 3609 ranked first in the sequence. The first element of the backward 3610 sequence is the first interval in the sequence variable. 3611 - the backward sequence. That is the list of interval variables 3612 ranked last in the sequence. The first element of the backward 3613 sequence is the last interval in the sequence variable. 3614 - The list of unperformed interval variables. 3615 Furthermore, if all performed variables are ranked, then by 3616 convention, the forward_sequence will contain all such variables 3617 and the backward_sequence will be empty. 3618 """ 3619 3620 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3621 3622 def __init__(self, *args, **kwargs): 3623 raise AttributeError("No constructor defined") 3624 __repr__ = _swig_repr 3625 3626 def Var(self): 3627 return _pywrapcp.SequenceVarElement_Var(self) 3628 3629 def ForwardSequence(self): 3630 return _pywrapcp.SequenceVarElement_ForwardSequence(self) 3631 3632 def BackwardSequence(self): 3633 return _pywrapcp.SequenceVarElement_BackwardSequence(self) 3634 3635 def Unperformed(self): 3636 return _pywrapcp.SequenceVarElement_Unperformed(self) 3637 3638 def SetSequence(self, forward_sequence, backward_sequence, unperformed): 3639 return _pywrapcp.SequenceVarElement_SetSequence(self, forward_sequence, backward_sequence, unperformed) 3640 3641 def SetForwardSequence(self, forward_sequence): 3642 return _pywrapcp.SequenceVarElement_SetForwardSequence(self, forward_sequence) 3643 3644 def SetBackwardSequence(self, backward_sequence): 3645 return _pywrapcp.SequenceVarElement_SetBackwardSequence(self, backward_sequence) 3646 3647 def SetUnperformed(self, unperformed): 3648 return _pywrapcp.SequenceVarElement_SetUnperformed(self, unperformed) 3649 3650 def __eq__(self, element): 3651 return _pywrapcp.SequenceVarElement___eq__(self, element) 3652 3653 def __ne__(self, element): 3654 return _pywrapcp.SequenceVarElement___ne__(self, element) 3655 __swig_destroy__ = _pywrapcp.delete_SequenceVarElement 3656 3657# Register SequenceVarElement in _pywrapcp: 3658_pywrapcp.SequenceVarElement_swigregister(SequenceVarElement) 3659class Assignment(PropagationBaseObject): 3660 r""" 3661 An Assignment is a variable -> domains mapping, used 3662 to report solutions to the user. 3663 """ 3664 3665 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3666 3667 def __init__(self, *args, **kwargs): 3668 raise AttributeError("No constructor defined") 3669 __repr__ = _swig_repr 3670 3671 def Clear(self): 3672 return _pywrapcp.Assignment_Clear(self) 3673 3674 def Empty(self): 3675 return _pywrapcp.Assignment_Empty(self) 3676 3677 def Size(self): 3678 return _pywrapcp.Assignment_Size(self) 3679 3680 def NumIntVars(self): 3681 return _pywrapcp.Assignment_NumIntVars(self) 3682 3683 def NumIntervalVars(self): 3684 return _pywrapcp.Assignment_NumIntervalVars(self) 3685 3686 def NumSequenceVars(self): 3687 return _pywrapcp.Assignment_NumSequenceVars(self) 3688 3689 def Store(self): 3690 return _pywrapcp.Assignment_Store(self) 3691 3692 def Restore(self): 3693 return _pywrapcp.Assignment_Restore(self) 3694 3695 def Load(self, *args): 3696 r""" 3697 Loads an assignment from a file; does not add variables to the 3698 assignment (only the variables contained in the assignment are modified). 3699 """ 3700 return _pywrapcp.Assignment_Load(self, *args) 3701 3702 def Save(self, *args): 3703 r"""Saves the assignment to a file.""" 3704 return _pywrapcp.Assignment_Save(self, *args) 3705 3706 def AddObjective(self, v): 3707 return _pywrapcp.Assignment_AddObjective(self, v) 3708 3709 def Objective(self): 3710 return _pywrapcp.Assignment_Objective(self) 3711 3712 def HasObjective(self): 3713 return _pywrapcp.Assignment_HasObjective(self) 3714 3715 def ObjectiveMin(self): 3716 return _pywrapcp.Assignment_ObjectiveMin(self) 3717 3718 def ObjectiveMax(self): 3719 return _pywrapcp.Assignment_ObjectiveMax(self) 3720 3721 def ObjectiveValue(self): 3722 return _pywrapcp.Assignment_ObjectiveValue(self) 3723 3724 def ObjectiveBound(self): 3725 return _pywrapcp.Assignment_ObjectiveBound(self) 3726 3727 def SetObjectiveMin(self, m): 3728 return _pywrapcp.Assignment_SetObjectiveMin(self, m) 3729 3730 def SetObjectiveMax(self, m): 3731 return _pywrapcp.Assignment_SetObjectiveMax(self, m) 3732 3733 def SetObjectiveValue(self, value): 3734 return _pywrapcp.Assignment_SetObjectiveValue(self, value) 3735 3736 def SetObjectiveRange(self, l, u): 3737 return _pywrapcp.Assignment_SetObjectiveRange(self, l, u) 3738 3739 def Min(self, var): 3740 return _pywrapcp.Assignment_Min(self, var) 3741 3742 def Max(self, var): 3743 return _pywrapcp.Assignment_Max(self, var) 3744 3745 def Value(self, var): 3746 return _pywrapcp.Assignment_Value(self, var) 3747 3748 def Bound(self, var): 3749 return _pywrapcp.Assignment_Bound(self, var) 3750 3751 def SetMin(self, var, m): 3752 return _pywrapcp.Assignment_SetMin(self, var, m) 3753 3754 def SetMax(self, var, m): 3755 return _pywrapcp.Assignment_SetMax(self, var, m) 3756 3757 def SetRange(self, var, l, u): 3758 return _pywrapcp.Assignment_SetRange(self, var, l, u) 3759 3760 def SetValue(self, var, value): 3761 return _pywrapcp.Assignment_SetValue(self, var, value) 3762 3763 def StartMin(self, var): 3764 return _pywrapcp.Assignment_StartMin(self, var) 3765 3766 def StartMax(self, var): 3767 return _pywrapcp.Assignment_StartMax(self, var) 3768 3769 def StartValue(self, var): 3770 return _pywrapcp.Assignment_StartValue(self, var) 3771 3772 def DurationMin(self, var): 3773 return _pywrapcp.Assignment_DurationMin(self, var) 3774 3775 def DurationMax(self, var): 3776 return _pywrapcp.Assignment_DurationMax(self, var) 3777 3778 def DurationValue(self, var): 3779 return _pywrapcp.Assignment_DurationValue(self, var) 3780 3781 def EndMin(self, var): 3782 return _pywrapcp.Assignment_EndMin(self, var) 3783 3784 def EndMax(self, var): 3785 return _pywrapcp.Assignment_EndMax(self, var) 3786 3787 def EndValue(self, var): 3788 return _pywrapcp.Assignment_EndValue(self, var) 3789 3790 def PerformedMin(self, var): 3791 return _pywrapcp.Assignment_PerformedMin(self, var) 3792 3793 def PerformedMax(self, var): 3794 return _pywrapcp.Assignment_PerformedMax(self, var) 3795 3796 def PerformedValue(self, var): 3797 return _pywrapcp.Assignment_PerformedValue(self, var) 3798 3799 def SetStartMin(self, var, m): 3800 return _pywrapcp.Assignment_SetStartMin(self, var, m) 3801 3802 def SetStartMax(self, var, m): 3803 return _pywrapcp.Assignment_SetStartMax(self, var, m) 3804 3805 def SetStartRange(self, var, mi, ma): 3806 return _pywrapcp.Assignment_SetStartRange(self, var, mi, ma) 3807 3808 def SetStartValue(self, var, value): 3809 return _pywrapcp.Assignment_SetStartValue(self, var, value) 3810 3811 def SetDurationMin(self, var, m): 3812 return _pywrapcp.Assignment_SetDurationMin(self, var, m) 3813 3814 def SetDurationMax(self, var, m): 3815 return _pywrapcp.Assignment_SetDurationMax(self, var, m) 3816 3817 def SetDurationRange(self, var, mi, ma): 3818 return _pywrapcp.Assignment_SetDurationRange(self, var, mi, ma) 3819 3820 def SetDurationValue(self, var, value): 3821 return _pywrapcp.Assignment_SetDurationValue(self, var, value) 3822 3823 def SetEndMin(self, var, m): 3824 return _pywrapcp.Assignment_SetEndMin(self, var, m) 3825 3826 def SetEndMax(self, var, m): 3827 return _pywrapcp.Assignment_SetEndMax(self, var, m) 3828 3829 def SetEndRange(self, var, mi, ma): 3830 return _pywrapcp.Assignment_SetEndRange(self, var, mi, ma) 3831 3832 def SetEndValue(self, var, value): 3833 return _pywrapcp.Assignment_SetEndValue(self, var, value) 3834 3835 def SetPerformedMin(self, var, m): 3836 return _pywrapcp.Assignment_SetPerformedMin(self, var, m) 3837 3838 def SetPerformedMax(self, var, m): 3839 return _pywrapcp.Assignment_SetPerformedMax(self, var, m) 3840 3841 def SetPerformedRange(self, var, mi, ma): 3842 return _pywrapcp.Assignment_SetPerformedRange(self, var, mi, ma) 3843 3844 def SetPerformedValue(self, var, value): 3845 return _pywrapcp.Assignment_SetPerformedValue(self, var, value) 3846 3847 def Add(self, *args): 3848 return _pywrapcp.Assignment_Add(self, *args) 3849 3850 def ForwardSequence(self, var): 3851 return _pywrapcp.Assignment_ForwardSequence(self, var) 3852 3853 def BackwardSequence(self, var): 3854 return _pywrapcp.Assignment_BackwardSequence(self, var) 3855 3856 def Unperformed(self, var): 3857 return _pywrapcp.Assignment_Unperformed(self, var) 3858 3859 def SetSequence(self, var, forward_sequence, backward_sequence, unperformed): 3860 return _pywrapcp.Assignment_SetSequence(self, var, forward_sequence, backward_sequence, unperformed) 3861 3862 def SetForwardSequence(self, var, forward_sequence): 3863 return _pywrapcp.Assignment_SetForwardSequence(self, var, forward_sequence) 3864 3865 def SetBackwardSequence(self, var, backward_sequence): 3866 return _pywrapcp.Assignment_SetBackwardSequence(self, var, backward_sequence) 3867 3868 def SetUnperformed(self, var, unperformed): 3869 return _pywrapcp.Assignment_SetUnperformed(self, var, unperformed) 3870 3871 def Activate(self, *args): 3872 return _pywrapcp.Assignment_Activate(self, *args) 3873 3874 def Deactivate(self, *args): 3875 return _pywrapcp.Assignment_Deactivate(self, *args) 3876 3877 def Activated(self, *args): 3878 return _pywrapcp.Assignment_Activated(self, *args) 3879 3880 def DebugString(self): 3881 return _pywrapcp.Assignment_DebugString(self) 3882 3883 def IntVarContainer(self): 3884 return _pywrapcp.Assignment_IntVarContainer(self) 3885 3886 def MutableIntVarContainer(self): 3887 return _pywrapcp.Assignment_MutableIntVarContainer(self) 3888 3889 def IntervalVarContainer(self): 3890 return _pywrapcp.Assignment_IntervalVarContainer(self) 3891 3892 def MutableIntervalVarContainer(self): 3893 return _pywrapcp.Assignment_MutableIntervalVarContainer(self) 3894 3895 def SequenceVarContainer(self): 3896 return _pywrapcp.Assignment_SequenceVarContainer(self) 3897 3898 def MutableSequenceVarContainer(self): 3899 return _pywrapcp.Assignment_MutableSequenceVarContainer(self) 3900 3901 def __eq__(self, assignment): 3902 return _pywrapcp.Assignment___eq__(self, assignment) 3903 3904 def __ne__(self, assignment): 3905 return _pywrapcp.Assignment___ne__(self, assignment) 3906 3907# Register Assignment in _pywrapcp: 3908_pywrapcp.Assignment_swigregister(Assignment) 3909 3910def __lshift__(*args): 3911 return _pywrapcp.__lshift__(*args) 3912class Pack(Constraint): 3913 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3914 3915 def __init__(self, *args, **kwargs): 3916 raise AttributeError("No constructor defined") 3917 __repr__ = _swig_repr 3918 3919 def AddWeightedSumLessOrEqualConstantDimension(self, *args): 3920 r""" 3921 *Overload 1:* 3922 Dimensions are additional constraints than can restrict what is 3923 possible with the pack constraint. It can be used to set capacity 3924 limits, to count objects per bin, to compute unassigned 3925 penalties... 3926 This dimension imposes that for all bins b, the weighted sum 3927 (weights[i]) of all objects i assigned to 'b' is less or equal 3928 'bounds[b]'. 3929 3930 | 3931 3932 *Overload 2:* 3933 This dimension imposes that for all bins b, the weighted sum 3934 (weights->Run(i)) of all objects i assigned to 'b' is less or 3935 equal to 'bounds[b]'. Ownership of the callback is transferred to 3936 the pack constraint. 3937 3938 | 3939 3940 *Overload 3:* 3941 This dimension imposes that for all bins b, the weighted sum 3942 (weights->Run(i, b) of all objects i assigned to 'b' is less or 3943 equal to 'bounds[b]'. Ownership of the callback is transferred to 3944 the pack constraint. 3945 """ 3946 return _pywrapcp.Pack_AddWeightedSumLessOrEqualConstantDimension(self, *args) 3947 3948 def AddWeightedSumEqualVarDimension(self, *args): 3949 r""" 3950 *Overload 1:* 3951 This dimension imposes that for all bins b, the weighted sum 3952 (weights[i]) of all objects i assigned to 'b' is equal to loads[b]. 3953 3954 | 3955 3956 *Overload 2:* 3957 This dimension imposes that for all bins b, the weighted sum 3958 (weights->Run(i, b)) of all objects i assigned to 'b' is equal to 3959 loads[b]. 3960 """ 3961 return _pywrapcp.Pack_AddWeightedSumEqualVarDimension(self, *args) 3962 3963 def AddSumVariableWeightsLessOrEqualConstantDimension(self, usage, capacity): 3964 r""" 3965 This dimension imposes: 3966 forall b in bins, 3967 sum (i in items: usage[i] * is_assigned(i, b)) <= capacity[b] 3968 where is_assigned(i, b) is true if and only if item i is assigned 3969 to the bin b. 3970 3971 This can be used to model shapes of items by linking variables of 3972 the same item on parallel dimensions with an allowed assignment 3973 constraint. 3974 """ 3975 return _pywrapcp.Pack_AddSumVariableWeightsLessOrEqualConstantDimension(self, usage, capacity) 3976 3977 def AddWeightedSumOfAssignedDimension(self, weights, cost_var): 3978 r""" 3979 This dimension enforces that cost_var == sum of weights[i] for 3980 all objects 'i' assigned to a bin. 3981 """ 3982 return _pywrapcp.Pack_AddWeightedSumOfAssignedDimension(self, weights, cost_var) 3983 3984 def AddCountUsedBinDimension(self, count_var): 3985 r""" 3986 This dimension links 'count_var' to the actual number of bins used in the 3987 pack. 3988 """ 3989 return _pywrapcp.Pack_AddCountUsedBinDimension(self, count_var) 3990 3991 def AddCountAssignedItemsDimension(self, count_var): 3992 r""" 3993 This dimension links 'count_var' to the actual number of items 3994 assigned to a bin in the pack. 3995 """ 3996 return _pywrapcp.Pack_AddCountAssignedItemsDimension(self, count_var) 3997 3998 def Post(self): 3999 return _pywrapcp.Pack_Post(self) 4000 4001 def InitialPropagateWrapper(self): 4002 return _pywrapcp.Pack_InitialPropagateWrapper(self) 4003 4004 def DebugString(self): 4005 return _pywrapcp.Pack_DebugString(self) 4006 4007# Register Pack in _pywrapcp: 4008_pywrapcp.Pack_swigregister(Pack) 4009class DisjunctiveConstraint(Constraint): 4010 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4011 4012 def __init__(self, *args, **kwargs): 4013 raise AttributeError("No constructor defined - class is abstract") 4014 __repr__ = _swig_repr 4015 4016 def SequenceVar(self): 4017 r"""Creates a sequence variable from the constraint.""" 4018 return _pywrapcp.DisjunctiveConstraint_SequenceVar(self) 4019 4020 def SetTransitionTime(self, transition_time): 4021 r""" 4022 Add a transition time between intervals. It forces the distance between 4023 the end of interval a and start of interval b that follows it to be at 4024 least transition_time(a, b). This function must always return 4025 a positive or null value. 4026 """ 4027 return _pywrapcp.DisjunctiveConstraint_SetTransitionTime(self, transition_time) 4028 4029 def TransitionTime(self, before_index, after_index): 4030 return _pywrapcp.DisjunctiveConstraint_TransitionTime(self, before_index, after_index) 4031 4032# Register DisjunctiveConstraint in _pywrapcp: 4033_pywrapcp.DisjunctiveConstraint_swigregister(DisjunctiveConstraint) 4034class RevInteger(object): 4035 r""" 4036 This class adds reversibility to a POD type. 4037 It contains the stamp optimization. i.e. the SaveValue call is done 4038 only once per node of the search tree. Please note that actual 4039 stamps always starts at 1, thus an initial value of 0 will always 4040 trigger the first SaveValue. 4041 """ 4042 4043 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4044 __repr__ = _swig_repr 4045 4046 def __init__(self, val): 4047 _pywrapcp.RevInteger_swiginit(self, _pywrapcp.new_RevInteger(val)) 4048 4049 def Value(self): 4050 return _pywrapcp.RevInteger_Value(self) 4051 4052 def SetValue(self, s, val): 4053 return _pywrapcp.RevInteger_SetValue(self, s, val) 4054 __swig_destroy__ = _pywrapcp.delete_RevInteger 4055 4056# Register RevInteger in _pywrapcp: 4057_pywrapcp.RevInteger_swigregister(RevInteger) 4058class NumericalRevInteger(RevInteger): 4059 r"""Subclass of Rev<T> which adds numerical operations.""" 4060 4061 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4062 __repr__ = _swig_repr 4063 4064 def __init__(self, val): 4065 _pywrapcp.NumericalRevInteger_swiginit(self, _pywrapcp.new_NumericalRevInteger(val)) 4066 4067 def Add(self, s, to_add): 4068 return _pywrapcp.NumericalRevInteger_Add(self, s, to_add) 4069 4070 def Incr(self, s): 4071 return _pywrapcp.NumericalRevInteger_Incr(self, s) 4072 4073 def Decr(self, s): 4074 return _pywrapcp.NumericalRevInteger_Decr(self, s) 4075 __swig_destroy__ = _pywrapcp.delete_NumericalRevInteger 4076 4077# Register NumericalRevInteger in _pywrapcp: 4078_pywrapcp.NumericalRevInteger_swigregister(NumericalRevInteger) 4079class RevBool(object): 4080 r""" 4081 This class adds reversibility to a POD type. 4082 It contains the stamp optimization. i.e. the SaveValue call is done 4083 only once per node of the search tree. Please note that actual 4084 stamps always starts at 1, thus an initial value of 0 will always 4085 trigger the first SaveValue. 4086 """ 4087 4088 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4089 __repr__ = _swig_repr 4090 4091 def __init__(self, val): 4092 _pywrapcp.RevBool_swiginit(self, _pywrapcp.new_RevBool(val)) 4093 4094 def Value(self): 4095 return _pywrapcp.RevBool_Value(self) 4096 4097 def SetValue(self, s, val): 4098 return _pywrapcp.RevBool_SetValue(self, s, val) 4099 __swig_destroy__ = _pywrapcp.delete_RevBool 4100 4101# Register RevBool in _pywrapcp: 4102_pywrapcp.RevBool_swigregister(RevBool) 4103class IntVarContainer(object): 4104 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4105 4106 def __init__(self, *args, **kwargs): 4107 raise AttributeError("No constructor defined") 4108 __repr__ = _swig_repr 4109 4110 def Contains(self, var): 4111 return _pywrapcp.IntVarContainer_Contains(self, var) 4112 4113 def Element(self, index): 4114 return _pywrapcp.IntVarContainer_Element(self, index) 4115 4116 def Size(self): 4117 return _pywrapcp.IntVarContainer_Size(self) 4118 4119 def Store(self): 4120 return _pywrapcp.IntVarContainer_Store(self) 4121 4122 def Restore(self): 4123 return _pywrapcp.IntVarContainer_Restore(self) 4124 4125 def __eq__(self, container): 4126 r""" 4127 Returns true if this and 'container' both represent the same V* -> E map. 4128 Runs in linear time; requires that the == operator on the type E is well 4129 defined. 4130 """ 4131 return _pywrapcp.IntVarContainer___eq__(self, container) 4132 4133 def __ne__(self, container): 4134 return _pywrapcp.IntVarContainer___ne__(self, container) 4135 __swig_destroy__ = _pywrapcp.delete_IntVarContainer 4136 4137# Register IntVarContainer in _pywrapcp: 4138_pywrapcp.IntVarContainer_swigregister(IntVarContainer) 4139class IntervalVarContainer(object): 4140 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4141 4142 def __init__(self, *args, **kwargs): 4143 raise AttributeError("No constructor defined") 4144 __repr__ = _swig_repr 4145 4146 def Contains(self, var): 4147 return _pywrapcp.IntervalVarContainer_Contains(self, var) 4148 4149 def Element(self, index): 4150 return _pywrapcp.IntervalVarContainer_Element(self, index) 4151 4152 def Size(self): 4153 return _pywrapcp.IntervalVarContainer_Size(self) 4154 4155 def Store(self): 4156 return _pywrapcp.IntervalVarContainer_Store(self) 4157 4158 def Restore(self): 4159 return _pywrapcp.IntervalVarContainer_Restore(self) 4160 4161 def __eq__(self, container): 4162 r""" 4163 Returns true if this and 'container' both represent the same V* -> E map. 4164 Runs in linear time; requires that the == operator on the type E is well 4165 defined. 4166 """ 4167 return _pywrapcp.IntervalVarContainer___eq__(self, container) 4168 4169 def __ne__(self, container): 4170 return _pywrapcp.IntervalVarContainer___ne__(self, container) 4171 __swig_destroy__ = _pywrapcp.delete_IntervalVarContainer 4172 4173# Register IntervalVarContainer in _pywrapcp: 4174_pywrapcp.IntervalVarContainer_swigregister(IntervalVarContainer) 4175class SequenceVarContainer(object): 4176 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4177 4178 def __init__(self, *args, **kwargs): 4179 raise AttributeError("No constructor defined") 4180 __repr__ = _swig_repr 4181 4182 def Contains(self, var): 4183 return _pywrapcp.SequenceVarContainer_Contains(self, var) 4184 4185 def Element(self, index): 4186 return _pywrapcp.SequenceVarContainer_Element(self, index) 4187 4188 def Size(self): 4189 return _pywrapcp.SequenceVarContainer_Size(self) 4190 4191 def Store(self): 4192 return _pywrapcp.SequenceVarContainer_Store(self) 4193 4194 def Restore(self): 4195 return _pywrapcp.SequenceVarContainer_Restore(self) 4196 4197 def __eq__(self, container): 4198 r""" 4199 Returns true if this and 'container' both represent the same V* -> E map. 4200 Runs in linear time; requires that the == operator on the type E is well 4201 defined. 4202 """ 4203 return _pywrapcp.SequenceVarContainer___eq__(self, container) 4204 4205 def __ne__(self, container): 4206 return _pywrapcp.SequenceVarContainer___ne__(self, container) 4207 __swig_destroy__ = _pywrapcp.delete_SequenceVarContainer 4208 4209# Register SequenceVarContainer in _pywrapcp: 4210_pywrapcp.SequenceVarContainer_swigregister(SequenceVarContainer) 4211class LocalSearchOperator(BaseObject): 4212 r""" 4213 The base class for all local search operators. 4214 4215 A local search operator is an object that defines the neighborhood of a 4216 solution. In other words, a neighborhood is the set of solutions which can 4217 be reached from a given solution using an operator. 4218 4219 The behavior of the LocalSearchOperator class is similar to iterators. 4220 The operator is synchronized with an assignment (gives the 4221 current values of the variables); this is done in the Start() method. 4222 4223 Then one can iterate over the neighbors using the MakeNextNeighbor method. 4224 This method returns an assignment which represents the incremental changes 4225 to the current solution. It also returns a second assignment representing 4226 the changes to the last solution defined by the neighborhood operator; this 4227 assignment is empty if the neighborhood operator cannot track this 4228 information. 4229 """ 4230 4231 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4232 4233 def __init__(self, *args, **kwargs): 4234 raise AttributeError("No constructor defined - class is abstract") 4235 __repr__ = _swig_repr 4236 4237 def NextNeighbor(self, delta, deltadelta): 4238 return _pywrapcp.LocalSearchOperator_NextNeighbor(self, delta, deltadelta) 4239 4240 def Start(self, assignment): 4241 return _pywrapcp.LocalSearchOperator_Start(self, assignment) 4242 def __disown__(self): 4243 self.this.disown() 4244 _pywrapcp.disown_LocalSearchOperator(self) 4245 return weakref.proxy(self) 4246 4247# Register LocalSearchOperator in _pywrapcp: 4248_pywrapcp.LocalSearchOperator_swigregister(LocalSearchOperator) 4249class IntVarLocalSearchOperator(LocalSearchOperator): 4250 r""" 4251 Specialization of LocalSearchOperator built from an array of IntVars 4252 which specifies the scope of the operator. 4253 This class also takes care of storing current variable values in Start(), 4254 keeps track of changes done by the operator and builds the delta. 4255 The Deactivate() method can be used to perform Large Neighborhood Search. 4256 """ 4257 4258 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4259 __repr__ = _swig_repr 4260 4261 def __init__(self, vars, keep_inverse_values=False): 4262 if self.__class__ == IntVarLocalSearchOperator: 4263 _self = None 4264 else: 4265 _self = self 4266 _pywrapcp.IntVarLocalSearchOperator_swiginit(self, _pywrapcp.new_IntVarLocalSearchOperator(_self, vars, keep_inverse_values)) 4267 __swig_destroy__ = _pywrapcp.delete_IntVarLocalSearchOperator 4268 4269 def Start(self, assignment): 4270 r""" 4271 This method should not be overridden. Override OnStart() instead which is 4272 called before exiting this method. 4273 """ 4274 return _pywrapcp.IntVarLocalSearchOperator_Start(self, assignment) 4275 4276 def IsIncremental(self): 4277 return _pywrapcp.IntVarLocalSearchOperator_IsIncremental(self) 4278 4279 def Size(self): 4280 return _pywrapcp.IntVarLocalSearchOperator_Size(self) 4281 4282 def Value(self, index): 4283 r""" 4284 Returns the value in the current assignment of the variable of given 4285 index. 4286 """ 4287 return _pywrapcp.IntVarLocalSearchOperator_Value(self, index) 4288 4289 def Var(self, index): 4290 r"""Returns the variable of given index.""" 4291 return _pywrapcp.IntVarLocalSearchOperator_Var(self, index) 4292 4293 def OldValue(self, index): 4294 return _pywrapcp.IntVarLocalSearchOperator_OldValue(self, index) 4295 4296 def PrevValue(self, index): 4297 return _pywrapcp.IntVarLocalSearchOperator_PrevValue(self, index) 4298 4299 def SetValue(self, index, value): 4300 return _pywrapcp.IntVarLocalSearchOperator_SetValue(self, index, value) 4301 4302 def Activated(self, index): 4303 return _pywrapcp.IntVarLocalSearchOperator_Activated(self, index) 4304 4305 def Activate(self, index): 4306 return _pywrapcp.IntVarLocalSearchOperator_Activate(self, index) 4307 4308 def Deactivate(self, index): 4309 return _pywrapcp.IntVarLocalSearchOperator_Deactivate(self, index) 4310 4311 def AddVars(self, vars): 4312 return _pywrapcp.IntVarLocalSearchOperator_AddVars(self, vars) 4313 4314 def OnStart(self): 4315 r""" 4316 Called by Start() after synchronizing the operator with the current 4317 assignment. Should be overridden instead of Start() to avoid calling 4318 IntVarLocalSearchOperator::Start explicitly. 4319 """ 4320 return _pywrapcp.IntVarLocalSearchOperator_OnStart(self) 4321 4322 def NextNeighbor(self, delta, deltadelta): 4323 r""" 4324 OnStart() should really be protected, but then SWIG doesn't see it. So we 4325 make it public, but only subclasses should access to it (to override it). 4326 Redefines MakeNextNeighbor to export a simpler interface. The calls to 4327 ApplyChanges() and RevertChanges() are factored in this method, hiding 4328 both delta and deltadelta from subclasses which only need to override 4329 MakeOneNeighbor(). 4330 Therefore this method should not be overridden. Override MakeOneNeighbor() 4331 instead. 4332 """ 4333 return _pywrapcp.IntVarLocalSearchOperator_NextNeighbor(self, delta, deltadelta) 4334 4335 def OneNeighbor(self): 4336 r""" 4337 Creates a new neighbor. It returns false when the neighborhood is 4338 completely explored. 4339 MakeNextNeighbor() in a subclass of IntVarLocalSearchOperator. 4340 """ 4341 return _pywrapcp.IntVarLocalSearchOperator_OneNeighbor(self) 4342 def __disown__(self): 4343 self.this.disown() 4344 _pywrapcp.disown_IntVarLocalSearchOperator(self) 4345 return weakref.proxy(self) 4346 4347# Register IntVarLocalSearchOperator in _pywrapcp: 4348_pywrapcp.IntVarLocalSearchOperator_swigregister(IntVarLocalSearchOperator) 4349class BaseLns(IntVarLocalSearchOperator): 4350 r""" 4351 This is the base class for building an Lns operator. An Lns fragment is a 4352 collection of variables which will be relaxed. Fragments are built with 4353 NextFragment(), which returns false if there are no more fragments to build. 4354 Optionally one can override InitFragments, which is called from 4355 LocalSearchOperator::Start to initialize fragment data. 4356 4357 Here's a sample relaxing one variable at a time: 4358 4359 class OneVarLns : public BaseLns { 4360 public: 4361 OneVarLns(const std::vector<IntVar*>& vars) : BaseLns(vars), index_(0) {} 4362 virtual ~OneVarLns() {} 4363 virtual void InitFragments() { index_ = 0; } 4364 virtual bool NextFragment() { 4365 const int size = Size(); 4366 if (index_ < size) { 4367 AppendToFragment(index_); 4368 ++index_; 4369 return true; 4370 } else { 4371 return false; 4372 } 4373 } 4374 4375 private: 4376 int index_; 4377 }; 4378 """ 4379 4380 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4381 __repr__ = _swig_repr 4382 4383 def __init__(self, vars): 4384 if self.__class__ == BaseLns: 4385 _self = None 4386 else: 4387 _self = self 4388 _pywrapcp.BaseLns_swiginit(self, _pywrapcp.new_BaseLns(_self, vars)) 4389 __swig_destroy__ = _pywrapcp.delete_BaseLns 4390 4391 def InitFragments(self): 4392 return _pywrapcp.BaseLns_InitFragments(self) 4393 4394 def NextFragment(self): 4395 return _pywrapcp.BaseLns_NextFragment(self) 4396 4397 def AppendToFragment(self, index): 4398 return _pywrapcp.BaseLns_AppendToFragment(self, index) 4399 4400 def FragmentSize(self): 4401 return _pywrapcp.BaseLns_FragmentSize(self) 4402 4403 def __getitem__(self, index): 4404 return _pywrapcp.BaseLns___getitem__(self, index) 4405 4406 def __len__(self): 4407 return _pywrapcp.BaseLns___len__(self) 4408 def __disown__(self): 4409 self.this.disown() 4410 _pywrapcp.disown_BaseLns(self) 4411 return weakref.proxy(self) 4412 4413# Register BaseLns in _pywrapcp: 4414_pywrapcp.BaseLns_swigregister(BaseLns) 4415class ChangeValue(IntVarLocalSearchOperator): 4416 r""" 4417 Defines operators which change the value of variables; 4418 each neighbor corresponds to *one* modified variable. 4419 Sub-classes have to define ModifyValue which determines what the new 4420 variable value is going to be (given the current value and the variable). 4421 """ 4422 4423 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4424 __repr__ = _swig_repr 4425 4426 def __init__(self, vars): 4427 if self.__class__ == ChangeValue: 4428 _self = None 4429 else: 4430 _self = self 4431 _pywrapcp.ChangeValue_swiginit(self, _pywrapcp.new_ChangeValue(_self, vars)) 4432 __swig_destroy__ = _pywrapcp.delete_ChangeValue 4433 4434 def ModifyValue(self, index, value): 4435 return _pywrapcp.ChangeValue_ModifyValue(self, index, value) 4436 4437 def OneNeighbor(self): 4438 r"""This method should not be overridden. Override ModifyValue() instead.""" 4439 return _pywrapcp.ChangeValue_OneNeighbor(self) 4440 def __disown__(self): 4441 self.this.disown() 4442 _pywrapcp.disown_ChangeValue(self) 4443 return weakref.proxy(self) 4444 4445# Register ChangeValue in _pywrapcp: 4446_pywrapcp.ChangeValue_swigregister(ChangeValue) 4447class LocalSearchFilter(BaseObject): 4448 r""" 4449 Local Search Filters are used for fast neighbor pruning. 4450 Filtering a move is done in several phases: 4451 - in the Relax phase, filters determine which parts of their internals 4452 will be changed by the candidate, and modify intermediary State 4453 - in the Accept phase, filters check that the candidate is feasible, 4454 - if the Accept phase succeeds, the solver may decide to trigger a 4455 Synchronize phase that makes filters change their internal representation 4456 to the last candidate, 4457 - otherwise (Accept fails or the solver does not want to synchronize), 4458 a Revert phase makes filters erase any intermediary State generated by the 4459 Relax and Accept phases. 4460 A given filter has phases called with the following pattern: 4461 (Relax.Accept.Synchronize | Relax.Accept.Revert | Relax.Revert)*. 4462 Filters's Revert() is always called in the reverse order their Accept() was 4463 called, to allow late filters to use state done/undone by early filters' 4464 Accept()/Revert(). 4465 """ 4466 4467 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4468 4469 def __init__(self, *args, **kwargs): 4470 raise AttributeError("No constructor defined - class is abstract") 4471 __repr__ = _swig_repr 4472 4473 def Accept(self, delta, deltadelta, objective_min, objective_max): 4474 r""" 4475 Accepts a "delta" given the assignment with which the filter has been 4476 synchronized; the delta holds the variables which have been modified and 4477 their new value. 4478 If the filter represents a part of the global objective, its contribution 4479 must be between objective_min and objective_max. 4480 Sample: supposing one wants to maintain a[0,1] + b[0,1] <= 1, 4481 for the assignment (a,1), (b,0), the delta (b,1) will be rejected 4482 but the delta (a,0) will be accepted. 4483 TODO(user): Remove arguments when there are no more need for those. 4484 """ 4485 return _pywrapcp.LocalSearchFilter_Accept(self, delta, deltadelta, objective_min, objective_max) 4486 4487 def IsIncremental(self): 4488 return _pywrapcp.LocalSearchFilter_IsIncremental(self) 4489 4490 def Synchronize(self, assignment, delta): 4491 r""" 4492 Synchronizes the filter with the current solution, delta being the 4493 difference with the solution passed to the previous call to Synchronize() 4494 or IncrementalSynchronize(). 'delta' can be used to incrementally 4495 synchronizing the filter with the new solution by only considering the 4496 changes in delta. 4497 """ 4498 return _pywrapcp.LocalSearchFilter_Synchronize(self, assignment, delta) 4499 __swig_destroy__ = _pywrapcp.delete_LocalSearchFilter 4500 4501# Register LocalSearchFilter in _pywrapcp: 4502_pywrapcp.LocalSearchFilter_swigregister(LocalSearchFilter) 4503class LocalSearchFilterManager(BaseObject): 4504 r""" 4505 Filter manager: when a move is made, filters are executed to decide whether 4506 the solution is feasible and compute parts of the new cost. This class 4507 schedules filter execution and composes costs as a sum. 4508 """ 4509 4510 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4511 __repr__ = _swig_repr 4512 4513 def DebugString(self): 4514 return _pywrapcp.LocalSearchFilterManager_DebugString(self) 4515 4516 def __init__(self, *args): 4517 _pywrapcp.LocalSearchFilterManager_swiginit(self, _pywrapcp.new_LocalSearchFilterManager(*args)) 4518 4519 def Accept(self, monitor, delta, deltadelta, objective_min, objective_max): 4520 r""" 4521 Returns true iff all filters return true, and the sum of their accepted 4522 objectives is between objective_min and objective_max. 4523 The monitor has its Begin/EndFiltering events triggered. 4524 """ 4525 return _pywrapcp.LocalSearchFilterManager_Accept(self, monitor, delta, deltadelta, objective_min, objective_max) 4526 4527 def Synchronize(self, assignment, delta): 4528 r"""Synchronizes all filters to assignment.""" 4529 return _pywrapcp.LocalSearchFilterManager_Synchronize(self, assignment, delta) 4530 __swig_destroy__ = _pywrapcp.delete_LocalSearchFilterManager 4531 4532# Register LocalSearchFilterManager in _pywrapcp: 4533_pywrapcp.LocalSearchFilterManager_swigregister(LocalSearchFilterManager) 4534class IntVarLocalSearchFilter(LocalSearchFilter): 4535 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4536 __repr__ = _swig_repr 4537 4538 def __init__(self, vars): 4539 if self.__class__ == IntVarLocalSearchFilter: 4540 _self = None 4541 else: 4542 _self = self 4543 _pywrapcp.IntVarLocalSearchFilter_swiginit(self, _pywrapcp.new_IntVarLocalSearchFilter(_self, vars)) 4544 __swig_destroy__ = _pywrapcp.delete_IntVarLocalSearchFilter 4545 4546 def Synchronize(self, assignment, delta): 4547 r""" 4548 This method should not be overridden. Override OnSynchronize() instead 4549 which is called before exiting this method. 4550 """ 4551 return _pywrapcp.IntVarLocalSearchFilter_Synchronize(self, assignment, delta) 4552 4553 def Size(self): 4554 return _pywrapcp.IntVarLocalSearchFilter_Size(self) 4555 4556 def Value(self, index): 4557 return _pywrapcp.IntVarLocalSearchFilter_Value(self, index) 4558 4559 def IndexFromVar(self, var): 4560 return _pywrapcp.IntVarLocalSearchFilter_IndexFromVar(self, var) 4561 def __disown__(self): 4562 self.this.disown() 4563 _pywrapcp.disown_IntVarLocalSearchFilter(self) 4564 return weakref.proxy(self) 4565 4566# Register IntVarLocalSearchFilter in _pywrapcp: 4567_pywrapcp.IntVarLocalSearchFilter_swigregister(IntVarLocalSearchFilter) 4568class BooleanVar(IntVar): 4569 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4570 4571 def __init__(self, *args, **kwargs): 4572 raise AttributeError("No constructor defined - class is abstract") 4573 __repr__ = _swig_repr 4574 4575 def Min(self): 4576 return _pywrapcp.BooleanVar_Min(self) 4577 4578 def SetMin(self, m): 4579 return _pywrapcp.BooleanVar_SetMin(self, m) 4580 4581 def Max(self): 4582 return _pywrapcp.BooleanVar_Max(self) 4583 4584 def SetMax(self, m): 4585 return _pywrapcp.BooleanVar_SetMax(self, m) 4586 4587 def SetRange(self, mi, ma): 4588 return _pywrapcp.BooleanVar_SetRange(self, mi, ma) 4589 4590 def Bound(self): 4591 return _pywrapcp.BooleanVar_Bound(self) 4592 4593 def Value(self): 4594 return _pywrapcp.BooleanVar_Value(self) 4595 4596 def RemoveValue(self, v): 4597 return _pywrapcp.BooleanVar_RemoveValue(self, v) 4598 4599 def RemoveInterval(self, l, u): 4600 return _pywrapcp.BooleanVar_RemoveInterval(self, l, u) 4601 4602 def WhenBound(self, d): 4603 return _pywrapcp.BooleanVar_WhenBound(self, d) 4604 4605 def WhenRange(self, d): 4606 return _pywrapcp.BooleanVar_WhenRange(self, d) 4607 4608 def WhenDomain(self, d): 4609 return _pywrapcp.BooleanVar_WhenDomain(self, d) 4610 4611 def Size(self): 4612 return _pywrapcp.BooleanVar_Size(self) 4613 4614 def Contains(self, v): 4615 return _pywrapcp.BooleanVar_Contains(self, v) 4616 4617 def HoleIteratorAux(self, reversible): 4618 return _pywrapcp.BooleanVar_HoleIteratorAux(self, reversible) 4619 4620 def DomainIteratorAux(self, reversible): 4621 return _pywrapcp.BooleanVar_DomainIteratorAux(self, reversible) 4622 4623 def DebugString(self): 4624 return _pywrapcp.BooleanVar_DebugString(self) 4625 4626# Register BooleanVar in _pywrapcp: 4627_pywrapcp.BooleanVar_swigregister(BooleanVar) 4628 4629class PyDecision(Decision): 4630 def ApplyWrapper(self, solver): 4631 try: 4632 self.Apply(solver) 4633 except Exception as e: 4634 if 'CP Solver fail' in str(e): 4635 solver.ShouldFail() 4636 else: 4637 raise 4638 4639 def RefuteWrapper(self, solver): 4640 try: 4641 self.Refute(solver) 4642 except Exception as e: 4643 if 'CP Solver fail' in str(e): 4644 solver.ShouldFail() 4645 else: 4646 raise 4647 4648 def DebugString(self): 4649 return "PyDecision" 4650 4651 4652class PyDecisionBuilder(DecisionBuilder): 4653 def NextWrapper(self, solver): 4654 try: 4655 return self.Next(solver) 4656 except Exception as e: 4657 if 'CP Solver fail' in str(e): 4658 return solver.FailDecision() 4659 else: 4660 raise 4661 4662 def DebugString(self): 4663 return "PyDecisionBuilder" 4664 4665 4666class PyDemon(Demon): 4667 def RunWrapper(self, solver): 4668 try: 4669 self.Run(solver) 4670 except Exception as e: 4671 if 'CP Solver fail' in str(e): 4672 solver.ShouldFail() 4673 else: 4674 raise 4675 4676 def DebugString(self): 4677 return "PyDemon" 4678 4679 4680class PyConstraintDemon(PyDemon): 4681 def __init__(self, ct, method, delayed, *args): 4682 super().__init__() 4683 self.__constraint = ct 4684 self.__method = method 4685 self.__delayed = delayed 4686 self.__args = args 4687 4688 def Run(self, solver): 4689 self.__method(self.__constraint, *self.__args) 4690 4691 def Priority(self): 4692 return Solver.DELAYED_PRIORITY if self.__delayed else Solver.NORMAL_PRIORITY 4693 4694 def DebugString(self): 4695 return 'PyConstraintDemon' 4696 4697 4698class PyConstraint(Constraint): 4699 def __init__(self, solver): 4700 super().__init__(solver) 4701 self.__demons = [] 4702 4703 def Demon(self, method, *args): 4704 demon = PyConstraintDemon(self, method, False, *args) 4705 self.__demons.append(demon) 4706 return demon 4707 4708 def DelayedDemon(self, method, *args): 4709 demon = PyConstraintDemon(self, method, True, *args) 4710 self.__demons.append(demon) 4711 return demon 4712 4713 def InitialPropagateDemon(self): 4714 return self.solver().ConstraintInitialPropagateCallback(self) 4715 4716 def DelayedInitialPropagateDemon(self): 4717 return self.solver().DelayedConstraintInitialPropagateCallback(self) 4718 4719 def InitialPropagateWrapper(self): 4720 try: 4721 self.InitialPropagate() 4722 except Exception as e: 4723 if 'CP Solver fail' in str(e): 4724 self.solver().ShouldFail() 4725 else: 4726 raise 4727 4728 def DebugString(self): 4729 return "PyConstraint" 4730 4731class RoutingIndexManager(object): 4732 r""" 4733 Manager for any NodeIndex <-> variable index conversion. 4734 The routing solver uses variable indices internally and through 4735 its API. 4736 These variable indices are tricky to manage directly because one Node can 4737 correspond to a multitude of variables, depending on the number of times 4738 they appear in the model, and if they're used as start and/or end points. 4739 This class aims to simplify variable index usage, allowing users to use 4740 NodeIndex instead. 4741 4742 Usage: 4743 4744 .. code-block:: c++ 4745 4746 auto starts_ends = ...; /// These are NodeIndex. 4747 RoutingIndexManager manager(10, 4, starts_ends); // 10 nodes, 4 vehicles. 4748 RoutingModel model(manager); 4749 4750 Then, use 'manager.NodeToIndex(node)' whenever model requires a variable 4751 index. 4752 4753 Note: the mapping between node indices and variables indices is subject to 4754 change so no assumption should be made on it. The only guarantee is that 4755 indices range between 0 and n-1, where n = number of vehicles * 2 (for start 4756 and end nodes) + number of non-start or end nodes. 4757 """ 4758 4759 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4760 __repr__ = _swig_repr 4761 4762 def __init__(self, *args): 4763 r""" 4764 *Overload 1:* 4765 Creates a NodeIndex to variable index mapping for a problem 4766 containing 'num_nodes', 'num_vehicles' and the given starts and ends for 4767 each vehicle. If used, any start/end arrays have to have exactly 4768 'num_vehicles' elements. 4769 :type num_nodes: int 4770 :param num_nodes: Number of nodes in the problem. 4771 :type num_vehicles: int 4772 :param num_vehicles: Number of vehicles in the problem. 4773 :type depot: operations_research::RoutingIndexManager::NodeIndex 4774 :param depot: 'start' and 'end' 4775 NodeIndex for all vehicles. 4776 4777 | 4778 4779 *Overload 2:* 4780 Creates a NodeIndex to variable index mapping. 4781 :type num_nodes: int 4782 :param num_nodes: Number of nodes in the problem. 4783 :type num_vehicles: int 4784 :param num_vehicles: Number of vehicles in the problem. 4785 :type starts: std::vector< operations_research::RoutingIndexManager::NodeIndex > 4786 :param starts: Array containing the start NodeIndex for each vehicle. 4787 :type ends: std::vector< operations_research::RoutingIndexManager::NodeIndex > 4788 :param ends: Array containing the end NodeIndex for each vehicle. 4789 Notes: **starts** and **ends** arrays must have **exactly** 'num_vehicles' 4790 elements. 4791 """ 4792 _pywrapcp.RoutingIndexManager_swiginit(self, _pywrapcp.new_RoutingIndexManager(*args)) 4793 4794 def GetNumberOfNodes(self): 4795 return _pywrapcp.RoutingIndexManager_GetNumberOfNodes(self) 4796 4797 def GetNumberOfVehicles(self): 4798 return _pywrapcp.RoutingIndexManager_GetNumberOfVehicles(self) 4799 4800 def GetNumberOfIndices(self): 4801 return _pywrapcp.RoutingIndexManager_GetNumberOfIndices(self) 4802 4803 def GetStartIndex(self, vehicle): 4804 return _pywrapcp.RoutingIndexManager_GetStartIndex(self, vehicle) 4805 4806 def GetEndIndex(self, vehicle): 4807 return _pywrapcp.RoutingIndexManager_GetEndIndex(self, vehicle) 4808 4809 def NodeToIndex(self, node): 4810 return _pywrapcp.RoutingIndexManager_NodeToIndex(self, node) 4811 4812 def IndexToNode(self, index): 4813 return _pywrapcp.RoutingIndexManager_IndexToNode(self, index) 4814 __swig_destroy__ = _pywrapcp.delete_RoutingIndexManager 4815 4816# Register RoutingIndexManager in _pywrapcp: 4817_pywrapcp.RoutingIndexManager_swigregister(RoutingIndexManager) 4818 4819def DefaultRoutingModelParameters(): 4820 return _pywrapcp.DefaultRoutingModelParameters() 4821 4822def DefaultRoutingSearchParameters(): 4823 return _pywrapcp.DefaultRoutingSearchParameters() 4824 4825def FindErrorInRoutingSearchParameters(search_parameters): 4826 r""" 4827 Returns an empty std::string if the routing search parameters are valid, and 4828 a non-empty, human readable error description if they're not. 4829 """ 4830 return _pywrapcp.FindErrorInRoutingSearchParameters(search_parameters) 4831BOOL_UNSPECIFIED = _pywrapcp.BOOL_UNSPECIFIED 4832BOOL_FALSE = _pywrapcp.BOOL_FALSE 4833BOOL_TRUE = _pywrapcp.BOOL_TRUE 4834class FirstSolutionStrategy(object): 4835 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4836 __repr__ = _swig_repr 4837 4838 def __init__(self): 4839 _pywrapcp.FirstSolutionStrategy_swiginit(self, _pywrapcp.new_FirstSolutionStrategy()) 4840 __swig_destroy__ = _pywrapcp.delete_FirstSolutionStrategy 4841 4842# Register FirstSolutionStrategy in _pywrapcp: 4843_pywrapcp.FirstSolutionStrategy_swigregister(FirstSolutionStrategy) 4844class LocalSearchMetaheuristic(object): 4845 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4846 __repr__ = _swig_repr 4847 4848 def __init__(self): 4849 _pywrapcp.LocalSearchMetaheuristic_swiginit(self, _pywrapcp.new_LocalSearchMetaheuristic()) 4850 __swig_destroy__ = _pywrapcp.delete_LocalSearchMetaheuristic 4851 4852# Register LocalSearchMetaheuristic in _pywrapcp: 4853_pywrapcp.LocalSearchMetaheuristic_swigregister(LocalSearchMetaheuristic) 4854class RoutingSearchStatus(object): 4855 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4856 __repr__ = _swig_repr 4857 4858 def __init__(self): 4859 _pywrapcp.RoutingSearchStatus_swiginit(self, _pywrapcp.new_RoutingSearchStatus()) 4860 __swig_destroy__ = _pywrapcp.delete_RoutingSearchStatus 4861 4862# Register RoutingSearchStatus in _pywrapcp: 4863_pywrapcp.RoutingSearchStatus_swigregister(RoutingSearchStatus) 4864class PathsMetadata(object): 4865 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4866 __repr__ = _swig_repr 4867 4868 def __init__(self, manager): 4869 _pywrapcp.PathsMetadata_swiginit(self, _pywrapcp.new_PathsMetadata(manager)) 4870 4871 def IsStart(self, node): 4872 return _pywrapcp.PathsMetadata_IsStart(self, node) 4873 4874 def IsEnd(self, node): 4875 return _pywrapcp.PathsMetadata_IsEnd(self, node) 4876 4877 def GetPath(self, start_or_end_node): 4878 return _pywrapcp.PathsMetadata_GetPath(self, start_or_end_node) 4879 4880 def NumPaths(self): 4881 return _pywrapcp.PathsMetadata_NumPaths(self) 4882 4883 def Paths(self): 4884 return _pywrapcp.PathsMetadata_Paths(self) 4885 4886 def Starts(self): 4887 return _pywrapcp.PathsMetadata_Starts(self) 4888 4889 def Start(self, path): 4890 return _pywrapcp.PathsMetadata_Start(self, path) 4891 4892 def End(self, path): 4893 return _pywrapcp.PathsMetadata_End(self, path) 4894 4895 def Ends(self): 4896 return _pywrapcp.PathsMetadata_Ends(self) 4897 __swig_destroy__ = _pywrapcp.delete_PathsMetadata 4898 4899# Register PathsMetadata in _pywrapcp: 4900_pywrapcp.PathsMetadata_swigregister(PathsMetadata) 4901class RoutingSearchStats(object): 4902 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4903 __repr__ = _swig_repr 4904 num_cp_sat_calls_in_lp_scheduling = property(_pywrapcp.RoutingSearchStats_num_cp_sat_calls_in_lp_scheduling_get, _pywrapcp.RoutingSearchStats_num_cp_sat_calls_in_lp_scheduling_set) 4905 num_glop_calls_in_lp_scheduling = property(_pywrapcp.RoutingSearchStats_num_glop_calls_in_lp_scheduling_get, _pywrapcp.RoutingSearchStats_num_glop_calls_in_lp_scheduling_set) 4906 num_min_cost_flow_calls = property(_pywrapcp.RoutingSearchStats_num_min_cost_flow_calls_get, _pywrapcp.RoutingSearchStats_num_min_cost_flow_calls_set) 4907 num_cp_sat_calls_in_routing = property(_pywrapcp.RoutingSearchStats_num_cp_sat_calls_in_routing_get, _pywrapcp.RoutingSearchStats_num_cp_sat_calls_in_routing_set) 4908 num_generalized_cp_sat_calls_in_routing = property(_pywrapcp.RoutingSearchStats_num_generalized_cp_sat_calls_in_routing_get, _pywrapcp.RoutingSearchStats_num_generalized_cp_sat_calls_in_routing_set) 4909 4910 def __init__(self): 4911 _pywrapcp.RoutingSearchStats_swiginit(self, _pywrapcp.new_RoutingSearchStats()) 4912 __swig_destroy__ = _pywrapcp.delete_RoutingSearchStats 4913 4914# Register RoutingSearchStats in _pywrapcp: 4915_pywrapcp.RoutingSearchStats_swigregister(RoutingSearchStats) 4916class RoutingModel(object): 4917 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4918 __repr__ = _swig_repr 4919 PICKUP_AND_DELIVERY_NO_ORDER = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_NO_ORDER 4920 r"""Any precedence is accepted.""" 4921 PICKUP_AND_DELIVERY_LIFO = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_LIFO 4922 r"""Deliveries must be performed in reverse order of pickups.""" 4923 PICKUP_AND_DELIVERY_FIFO = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_FIFO 4924 r"""Deliveries must be performed in the same order as pickups.""" 4925 4926 def __init__(self, *args): 4927 r""" 4928 Constructor taking an index manager. The version which does not take 4929 RoutingModelParameters is equivalent to passing 4930 DefaultRoutingModelParameters(). 4931 """ 4932 _pywrapcp.RoutingModel_swiginit(self, _pywrapcp.new_RoutingModel(*args)) 4933 __swig_destroy__ = _pywrapcp.delete_RoutingModel 4934 kTransitEvaluatorSignUnknown = _pywrapcp.RoutingModel_kTransitEvaluatorSignUnknown 4935 kTransitEvaluatorSignPositiveOrZero = _pywrapcp.RoutingModel_kTransitEvaluatorSignPositiveOrZero 4936 kTransitEvaluatorSignNegativeOrZero = _pywrapcp.RoutingModel_kTransitEvaluatorSignNegativeOrZero 4937 4938 def RegisterUnaryTransitVector(self, values): 4939 r""" 4940 Registers 'callback' and returns its index. 4941 The sign parameter allows to notify the solver that the callback only 4942 return values of the given sign. This can help the solver, but passing 4943 an incorrect sign may crash in non-opt compilation mode, and yield 4944 incorrect results in opt. 4945 """ 4946 return _pywrapcp.RoutingModel_RegisterUnaryTransitVector(self, values) 4947 4948 def RegisterUnaryTransitCallback(self, *args): 4949 return _pywrapcp.RoutingModel_RegisterUnaryTransitCallback(self, *args) 4950 4951 def RegisterTransitMatrix(self, values): 4952 return _pywrapcp.RoutingModel_RegisterTransitMatrix(self, values) 4953 4954 def RegisterTransitCallback(self, *args): 4955 return _pywrapcp.RoutingModel_RegisterTransitCallback(self, *args) 4956 4957 def RegisterCumulDependentTransitCallback(self, callback): 4958 return _pywrapcp.RoutingModel_RegisterCumulDependentTransitCallback(self, callback) 4959 4960 def TransitCallback(self, callback_index): 4961 return _pywrapcp.RoutingModel_TransitCallback(self, callback_index) 4962 4963 def UnaryTransitCallbackOrNull(self, callback_index): 4964 return _pywrapcp.RoutingModel_UnaryTransitCallbackOrNull(self, callback_index) 4965 4966 def CumulDependentTransitCallback(self, callback_index): 4967 return _pywrapcp.RoutingModel_CumulDependentTransitCallback(self, callback_index) 4968 4969 def AddDimension(self, evaluator_index, slack_max, capacity, fix_start_cumul_to_zero, name): 4970 r""" 4971 Model creation 4972 Methods to add dimensions to routes; dimensions represent quantities 4973 accumulated at nodes along the routes. They represent quantities such as 4974 weights or volumes carried along the route, or distance or times. 4975 Quantities at a node are represented by "cumul" variables and the increase 4976 or decrease of quantities between nodes are represented by "transit" 4977 variables. These variables are linked as follows: 4978 if j == next(i), cumul(j) = cumul(i) + transit(i, j) + slack(i) 4979 where slack is a positive slack variable (can represent waiting times for 4980 a time dimension). 4981 Setting the value of fix_start_cumul_to_zero to true will force the 4982 "cumul" variable of the start node of all vehicles to be equal to 0. 4983 Creates a dimension where the transit variable is constrained to be 4984 equal to evaluator(i, next(i)); 'slack_max' is the upper bound of the 4985 slack variable and 'capacity' is the upper bound of the cumul variables. 4986 'name' is the name used to reference the dimension; this name is used to 4987 get cumul and transit variables from the routing model. 4988 Returns false if a dimension with the same name has already been created 4989 (and doesn't create the new dimension). 4990 Takes ownership of the callback 'evaluator'. 4991 """ 4992 return _pywrapcp.RoutingModel_AddDimension(self, evaluator_index, slack_max, capacity, fix_start_cumul_to_zero, name) 4993 4994 def AddDimensionWithVehicleTransits(self, evaluator_indices, slack_max, capacity, fix_start_cumul_to_zero, name): 4995 return _pywrapcp.RoutingModel_AddDimensionWithVehicleTransits(self, evaluator_indices, slack_max, capacity, fix_start_cumul_to_zero, name) 4996 4997 def AddDimensionWithVehicleCapacity(self, evaluator_index, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name): 4998 return _pywrapcp.RoutingModel_AddDimensionWithVehicleCapacity(self, evaluator_index, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name) 4999 5000 def AddDimensionWithVehicleTransitAndCapacity(self, evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name): 5001 return _pywrapcp.RoutingModel_AddDimensionWithVehicleTransitAndCapacity(self, evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name) 5002 5003 def AddDimensionWithCumulDependentVehicleTransitAndCapacity(self, fixed_evaluator_indices, cumul_dependent_evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name): 5004 r""" 5005 Creates a dimension where the transit variable on arc i->j is the sum of: 5006 - A "fixed" transit value, obtained from the fixed_evaluator_index for 5007 this vehicle, referencing evaluators in transit_evaluators_, and 5008 - A FloatSlopePiecewiseLinearFunction of the cumul of node i, obtained 5009 from the cumul_dependent_evaluator_index of this vehicle, pointing to 5010 an evaluator in cumul_dependent_transit_evaluators_. 5011 """ 5012 return _pywrapcp.RoutingModel_AddDimensionWithCumulDependentVehicleTransitAndCapacity(self, fixed_evaluator_indices, cumul_dependent_evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name) 5013 5014 def AddConstantDimensionWithSlack(self, value, capacity, slack_max, fix_start_cumul_to_zero, name): 5015 r""" 5016 Creates a dimension where the transit variable is constrained to be 5017 equal to 'value'; 'capacity' is the upper bound of the cumul variables. 5018 'name' is the name used to reference the dimension; this name is used to 5019 get cumul and transit variables from the routing model. 5020 Returns a pair consisting of an index to the registered unary transit 5021 callback and a bool denoting whether the dimension has been created. 5022 It is false if a dimension with the same name has already been created 5023 (and doesn't create the new dimension but still register a new callback). 5024 """ 5025 return _pywrapcp.RoutingModel_AddConstantDimensionWithSlack(self, value, capacity, slack_max, fix_start_cumul_to_zero, name) 5026 5027 def AddConstantDimension(self, value, capacity, fix_start_cumul_to_zero, name): 5028 return _pywrapcp.RoutingModel_AddConstantDimension(self, value, capacity, fix_start_cumul_to_zero, name) 5029 5030 def AddVectorDimension(self, values, capacity, fix_start_cumul_to_zero, name): 5031 r""" 5032 Creates a dimension where the transit variable is constrained to be 5033 equal to 'values[i]' for node i; 'capacity' is the upper bound of 5034 the cumul variables. 'name' is the name used to reference the dimension; 5035 this name is used to get cumul and transit variables from the routing 5036 model. 5037 Returns a pair consisting of an index to the registered unary transit 5038 callback and a bool denoting whether the dimension has been created. 5039 It is false if a dimension with the same name has already been created 5040 (and doesn't create the new dimension but still register a new callback). 5041 """ 5042 return _pywrapcp.RoutingModel_AddVectorDimension(self, values, capacity, fix_start_cumul_to_zero, name) 5043 5044 def AddMatrixDimension(self, values, capacity, fix_start_cumul_to_zero, name): 5045 r""" 5046 Creates a dimension where the transit variable is constrained to be 5047 equal to 'values[i][next(i)]' for node i; 'capacity' is the upper bound of 5048 the cumul variables. 'name' is the name used to reference the dimension; 5049 this name is used to get cumul and transit variables from the routing 5050 model. 5051 Returns a pair consisting of an index to the registered transit callback 5052 and a bool denoting whether the dimension has been created. 5053 It is false if a dimension with the same name has already been created 5054 (and doesn't create the new dimension but still register a new callback). 5055 """ 5056 return _pywrapcp.RoutingModel_AddMatrixDimension(self, values, capacity, fix_start_cumul_to_zero, name) 5057 5058 def GetAllDimensionNames(self): 5059 r"""Outputs the names of all dimensions added to the routing engine.""" 5060 return _pywrapcp.RoutingModel_GetAllDimensionNames(self) 5061 5062 def GetDimensions(self): 5063 r"""Returns all dimensions of the model.""" 5064 return _pywrapcp.RoutingModel_GetDimensions(self) 5065 5066 def GetDimensionsWithSoftOrSpanCosts(self): 5067 r"""Returns dimensions with soft or vehicle span costs.""" 5068 return _pywrapcp.RoutingModel_GetDimensionsWithSoftOrSpanCosts(self) 5069 5070 def GetUnaryDimensions(self): 5071 r"""Returns dimensions for which all transit evaluators are unary.""" 5072 return _pywrapcp.RoutingModel_GetUnaryDimensions(self) 5073 5074 def GetDimensionsWithGlobalCumulOptimizers(self): 5075 r"""Returns the dimensions which have [global|local]_dimension_optimizers_.""" 5076 return _pywrapcp.RoutingModel_GetDimensionsWithGlobalCumulOptimizers(self) 5077 5078 def GetDimensionsWithLocalCumulOptimizers(self): 5079 return _pywrapcp.RoutingModel_GetDimensionsWithLocalCumulOptimizers(self) 5080 5081 def HasGlobalCumulOptimizer(self, dimension): 5082 r"""Returns whether the given dimension has global/local cumul optimizers.""" 5083 return _pywrapcp.RoutingModel_HasGlobalCumulOptimizer(self, dimension) 5084 5085 def HasLocalCumulOptimizer(self, dimension): 5086 return _pywrapcp.RoutingModel_HasLocalCumulOptimizer(self, dimension) 5087 5088 def GetMutableGlobalCumulLPOptimizer(self, dimension): 5089 r""" 5090 Returns the global/local dimension cumul optimizer for a given dimension, 5091 or nullptr if there is none. 5092 """ 5093 return _pywrapcp.RoutingModel_GetMutableGlobalCumulLPOptimizer(self, dimension) 5094 5095 def GetMutableGlobalCumulMPOptimizer(self, dimension): 5096 return _pywrapcp.RoutingModel_GetMutableGlobalCumulMPOptimizer(self, dimension) 5097 5098 def GetMutableLocalCumulLPOptimizer(self, dimension): 5099 return _pywrapcp.RoutingModel_GetMutableLocalCumulLPOptimizer(self, dimension) 5100 5101 def GetMutableLocalCumulMPOptimizer(self, dimension): 5102 return _pywrapcp.RoutingModel_GetMutableLocalCumulMPOptimizer(self, dimension) 5103 5104 def HasDimension(self, dimension_name): 5105 r"""Returns true if a dimension exists for a given dimension name.""" 5106 return _pywrapcp.RoutingModel_HasDimension(self, dimension_name) 5107 5108 def GetDimensionOrDie(self, dimension_name): 5109 r"""Returns a dimension from its name. Dies if the dimension does not exist.""" 5110 return _pywrapcp.RoutingModel_GetDimensionOrDie(self, dimension_name) 5111 5112 def GetMutableDimension(self, dimension_name): 5113 r""" 5114 Returns a dimension from its name. Returns nullptr if the dimension does 5115 not exist. 5116 """ 5117 return _pywrapcp.RoutingModel_GetMutableDimension(self, dimension_name) 5118 5119 def SetPrimaryConstrainedDimension(self, dimension_name): 5120 r""" 5121 Set the given dimension as "primary constrained". As of August 2013, this 5122 is only used by ArcIsMoreConstrainedThanArc(). 5123 "dimension" must be the name of an existing dimension, or be empty, in 5124 which case there will not be a primary dimension after this call. 5125 """ 5126 return _pywrapcp.RoutingModel_SetPrimaryConstrainedDimension(self, dimension_name) 5127 5128 def GetPrimaryConstrainedDimension(self): 5129 r"""Get the primary constrained dimension, or an empty string if it is unset.""" 5130 return _pywrapcp.RoutingModel_GetPrimaryConstrainedDimension(self) 5131 5132 def GetResourceGroup(self, rg_index): 5133 return _pywrapcp.RoutingModel_GetResourceGroup(self, rg_index) 5134 5135 def GetDimensionResourceGroupIndices(self, dimension): 5136 r""" 5137 Returns the indices of resource groups for this dimension. This method can 5138 only be called after the model has been closed. 5139 """ 5140 return _pywrapcp.RoutingModel_GetDimensionResourceGroupIndices(self, dimension) 5141 5142 def GetDimensionResourceGroupIndex(self, dimension): 5143 r""" 5144 Returns the index of the resource group attached to the dimension. 5145 DCHECKS that there's exactly one resource group for this dimension. 5146 """ 5147 return _pywrapcp.RoutingModel_GetDimensionResourceGroupIndex(self, dimension) 5148 PENALIZE_ONCE = _pywrapcp.RoutingModel_PENALIZE_ONCE 5149 PENALIZE_PER_INACTIVE = _pywrapcp.RoutingModel_PENALIZE_PER_INACTIVE 5150 5151 def AddDisjunction(self, *args): 5152 r""" 5153 Adds a disjunction constraint on the indices. 5154 Exactly 'max_cardinality' of the indices are active. 5155 5156 If a penalty is given, at most 'max_cardinality' of the indices can be 5157 active, and if less are active, 'penalty' is payed per inactive index if 5158 the penalty cost is set to `PENALIZE_PER_INACTIVE`. 5159 This is equivalent to adding the constraint: 5160 p + Sum(i)active[i] == max_cardinality 5161 where p is an integer variable. 5162 If the penalty cost is set to `PENALIZE_ONCE`, then 'penalty' is payed 5163 once if there are less than `max_cardinality` of the indices active. 5164 This is equivalent to adding the constraint: 5165 p == (Sum(i)active[i] != max_cardinality) 5166 where p is a boolean variable. 5167 The following cost is added to the cost function: p * penalty. 5168 :type penalty: int, in, optional 5169 :param penalty: must be positive to make the disjunction optional; a 5170 negative penalty will force 'max_cardinality' indices of the disjunction 5171 to be performed, and therefore p == 0. 5172 Note: passing a vector with a single index will model an optional index 5173 with a penalty cost if it is not visited. 5174 Warning: Start and end indices of any vehicle cannot be part of a 5175 disjunction. 5176 """ 5177 return _pywrapcp.RoutingModel_AddDisjunction(self, *args) 5178 5179 def GetDisjunctionIndices(self, index): 5180 r"""Returns the indices of the disjunctions to which an index belongs.""" 5181 return _pywrapcp.RoutingModel_GetDisjunctionIndices(self, index) 5182 5183 def GetDisjunctionPenalty(self, index): 5184 r"""Returns the penalty of the node disjunction of index 'index'.""" 5185 return _pywrapcp.RoutingModel_GetDisjunctionPenalty(self, index) 5186 5187 def GetDisjunctionMaxCardinality(self, index): 5188 r""" 5189 Returns the maximum number of possible active nodes of the node 5190 disjunction of index 'index'. 5191 """ 5192 return _pywrapcp.RoutingModel_GetDisjunctionMaxCardinality(self, index) 5193 5194 def GetDisjunctionPenaltyCostBehavior(self, index): 5195 r""" 5196 Returns the 'PenaltyCostBehavior' used by the disjunction of index 5197 'index'. 5198 """ 5199 return _pywrapcp.RoutingModel_GetDisjunctionPenaltyCostBehavior(self, index) 5200 5201 def GetNumberOfDisjunctions(self): 5202 r"""Returns the number of node disjunctions in the model.""" 5203 return _pywrapcp.RoutingModel_GetNumberOfDisjunctions(self) 5204 5205 def HasMandatoryDisjunctions(self): 5206 r""" 5207 Returns true if the model contains mandatory disjunctions (ones with 5208 kNoPenalty as penalty). 5209 """ 5210 return _pywrapcp.RoutingModel_HasMandatoryDisjunctions(self) 5211 5212 def HasMaxCardinalityConstrainedDisjunctions(self): 5213 r""" 5214 Returns true if the model contains at least one disjunction which is 5215 constrained by its max_cardinality. 5216 """ 5217 return _pywrapcp.RoutingModel_HasMaxCardinalityConstrainedDisjunctions(self) 5218 5219 def GetPerfectBinaryDisjunctions(self): 5220 r""" 5221 Returns the list of all perfect binary disjunctions, as pairs of variable 5222 indices: a disjunction is "perfect" when its variables do not appear in 5223 any other disjunction. Each pair is sorted (lowest variable index first), 5224 and the output vector is also sorted (lowest pairs first). 5225 """ 5226 return _pywrapcp.RoutingModel_GetPerfectBinaryDisjunctions(self) 5227 5228 def IgnoreDisjunctionsAlreadyForcedToZero(self): 5229 r""" 5230 SPECIAL: Makes the solver ignore all the disjunctions whose active 5231 variables are all trivially zero (i.e. Max() == 0), by setting their 5232 max_cardinality to 0. 5233 This can be useful when using the BaseBinaryDisjunctionNeighborhood 5234 operators, in the context of arc-based routing. 5235 """ 5236 return _pywrapcp.RoutingModel_IgnoreDisjunctionsAlreadyForcedToZero(self) 5237 5238 def AddSoftSameVehicleConstraint(self, indices, cost): 5239 r""" 5240 Adds a soft constraint to force a set of variable indices to be on the 5241 same vehicle. If all nodes are not on the same vehicle, each extra vehicle 5242 used adds 'cost' to the cost function. 5243 TODO(user): Extend this to allow nodes/indices to be on the same given 5244 set of vehicle. 5245 """ 5246 return _pywrapcp.RoutingModel_AddSoftSameVehicleConstraint(self, indices, cost) 5247 5248 def GetNumberOfSoftSameVehicleConstraints(self): 5249 r"""Returns the number of soft same vehicle constraints in the model.""" 5250 return _pywrapcp.RoutingModel_GetNumberOfSoftSameVehicleConstraints(self) 5251 5252 def GetSoftSameVehicleIndices(self, index): 5253 r""" 5254 Returns the indices of the nodes in the soft same vehicle constraint of 5255 index 'index'. 5256 """ 5257 return _pywrapcp.RoutingModel_GetSoftSameVehicleIndices(self, index) 5258 5259 def GetSoftSameVehicleCost(self, index): 5260 r"""Returns the cost of the soft same vehicle constraint of index 'index'.""" 5261 return _pywrapcp.RoutingModel_GetSoftSameVehicleCost(self, index) 5262 5263 def SetAllowedVehiclesForIndex(self, vehicles, index): 5264 r""" 5265 Sets the vehicles which can visit a given node. If the node is in a 5266 disjunction, this will not prevent it from being unperformed. 5267 Specifying an empty vector of vehicles has no effect (all vehicles 5268 will be allowed to visit the node). 5269 """ 5270 return _pywrapcp.RoutingModel_SetAllowedVehiclesForIndex(self, vehicles, index) 5271 5272 def IsVehicleAllowedForIndex(self, vehicle, index): 5273 r"""Returns true if a vehicle is allowed to visit a given node.""" 5274 return _pywrapcp.RoutingModel_IsVehicleAllowedForIndex(self, vehicle, index) 5275 5276 def AddPickupAndDelivery(self, pickup, delivery): 5277 r""" 5278 Notifies that index1 and index2 form a pair of nodes which should belong 5279 to the same route. This methods helps the search find better solutions, 5280 especially in the local search phase. 5281 It should be called each time you have an equality constraint linking 5282 the vehicle variables of two node (including for instance pickup and 5283 delivery problems): 5284 Solver* const solver = routing.solver(); 5285 int64_t index1 = manager.NodeToIndex(node1); 5286 int64_t index2 = manager.NodeToIndex(node2); 5287 solver->AddConstraint(solver->MakeEquality( 5288 routing.VehicleVar(index1), 5289 routing.VehicleVar(index2))); 5290 routing.AddPickupAndDelivery(index1, index2); 5291 """ 5292 return _pywrapcp.RoutingModel_AddPickupAndDelivery(self, pickup, delivery) 5293 5294 def AddPickupAndDeliverySets(self, pickup_disjunction, delivery_disjunction): 5295 r""" 5296 Same as AddPickupAndDelivery but notifying that the performed node from 5297 the disjunction of index 'pickup_disjunction' is on the same route as the 5298 performed node from the disjunction of index 'delivery_disjunction'. 5299 """ 5300 return _pywrapcp.RoutingModel_AddPickupAndDeliverySets(self, pickup_disjunction, delivery_disjunction) 5301 5302 def GetPickupPosition(self, node_index): 5303 r"""Returns the pickup and delivery positions where the node is a pickup.""" 5304 return _pywrapcp.RoutingModel_GetPickupPosition(self, node_index) 5305 5306 def GetDeliveryPosition(self, node_index): 5307 r"""Returns the pickup and delivery positions where the node is a delivery.""" 5308 return _pywrapcp.RoutingModel_GetDeliveryPosition(self, node_index) 5309 5310 def IsPickup(self, node_index): 5311 r"""Returns whether the node is a pickup (resp. delivery).""" 5312 return _pywrapcp.RoutingModel_IsPickup(self, node_index) 5313 5314 def IsDelivery(self, node_index): 5315 return _pywrapcp.RoutingModel_IsDelivery(self, node_index) 5316 5317 def SetPickupAndDeliveryPolicyOfAllVehicles(self, policy): 5318 r""" 5319 Sets the Pickup and delivery policy of all vehicles. It is equivalent to 5320 calling SetPickupAndDeliveryPolicyOfVehicle on all vehicles. 5321 """ 5322 return _pywrapcp.RoutingModel_SetPickupAndDeliveryPolicyOfAllVehicles(self, policy) 5323 5324 def SetPickupAndDeliveryPolicyOfVehicle(self, policy, vehicle): 5325 return _pywrapcp.RoutingModel_SetPickupAndDeliveryPolicyOfVehicle(self, policy, vehicle) 5326 5327 def GetPickupAndDeliveryPolicyOfVehicle(self, vehicle): 5328 return _pywrapcp.RoutingModel_GetPickupAndDeliveryPolicyOfVehicle(self, vehicle) 5329 5330 def GetNumOfSingletonNodes(self): 5331 r""" 5332 Returns the number of non-start/end nodes which do not appear in a 5333 pickup/delivery pair. 5334 """ 5335 return _pywrapcp.RoutingModel_GetNumOfSingletonNodes(self) 5336 5337 def GetFirstMatchingPickupDeliverySibling(self, node, is_match): 5338 return _pywrapcp.RoutingModel_GetFirstMatchingPickupDeliverySibling(self, node, is_match) 5339 TYPE_ADDED_TO_VEHICLE = _pywrapcp.RoutingModel_TYPE_ADDED_TO_VEHICLE 5340 r"""When visited, the number of types 'T' on the vehicle increases by one.""" 5341 ADDED_TYPE_REMOVED_FROM_VEHICLE = _pywrapcp.RoutingModel_ADDED_TYPE_REMOVED_FROM_VEHICLE 5342 r""" 5343 When visited, one instance of type 'T' previously added to the route 5344 (TYPE_ADDED_TO_VEHICLE), if any, is removed from the vehicle. 5345 If the type was not previously added to the route or all added instances 5346 have already been removed, this visit has no effect on the types. 5347 """ 5348 TYPE_ON_VEHICLE_UP_TO_VISIT = _pywrapcp.RoutingModel_TYPE_ON_VEHICLE_UP_TO_VISIT 5349 r""" 5350 With the following policy, the visit enforces that type 'T' is 5351 considered on the route from its start until this node is visited. 5352 """ 5353 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED = _pywrapcp.RoutingModel_TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED 5354 r""" 5355 The visit doesn't have an impact on the number of types 'T' on the 5356 route, as it's (virtually) added and removed directly. 5357 This policy can be used for visits which are part of an incompatibility 5358 or requirement set without affecting the type count on the route. 5359 """ 5360 5361 def SetVisitType(self, index, type, type_policy): 5362 return _pywrapcp.RoutingModel_SetVisitType(self, index, type, type_policy) 5363 5364 def GetVisitType(self, index): 5365 return _pywrapcp.RoutingModel_GetVisitType(self, index) 5366 5367 def GetSingleNodesOfType(self, type): 5368 return _pywrapcp.RoutingModel_GetSingleNodesOfType(self, type) 5369 5370 def GetPairIndicesOfType(self, type): 5371 return _pywrapcp.RoutingModel_GetPairIndicesOfType(self, type) 5372 5373 def GetVisitTypePolicy(self, index): 5374 return _pywrapcp.RoutingModel_GetVisitTypePolicy(self, index) 5375 5376 def GetNumberOfVisitTypes(self): 5377 return _pywrapcp.RoutingModel_GetNumberOfVisitTypes(self) 5378 5379 def AddHardTypeIncompatibility(self, type1, type2): 5380 r""" 5381 Incompatibilities: 5382 Two nodes with "hard" incompatible types cannot share the same route at 5383 all, while with a "temporal" incompatibility they can't be on the same 5384 route at the same time. 5385 NOTE: To avoid unnecessary memory reallocations, it is recommended to only 5386 add incompatibilities once all the existing types have been set with 5387 SetVisitType(). 5388 """ 5389 return _pywrapcp.RoutingModel_AddHardTypeIncompatibility(self, type1, type2) 5390 5391 def AddTemporalTypeIncompatibility(self, type1, type2): 5392 return _pywrapcp.RoutingModel_AddTemporalTypeIncompatibility(self, type1, type2) 5393 5394 def GetHardTypeIncompatibilitiesOfType(self, type): 5395 r"""Returns visit types incompatible with a given type.""" 5396 return _pywrapcp.RoutingModel_GetHardTypeIncompatibilitiesOfType(self, type) 5397 5398 def GetTemporalTypeIncompatibilitiesOfType(self, type): 5399 return _pywrapcp.RoutingModel_GetTemporalTypeIncompatibilitiesOfType(self, type) 5400 5401 def HasHardTypeIncompatibilities(self): 5402 r""" 5403 Returns true iff any hard (resp. temporal) type incompatibilities have 5404 been added to the model. 5405 """ 5406 return _pywrapcp.RoutingModel_HasHardTypeIncompatibilities(self) 5407 5408 def HasTemporalTypeIncompatibilities(self): 5409 return _pywrapcp.RoutingModel_HasTemporalTypeIncompatibilities(self) 5410 5411 def AddSameVehicleRequiredTypeAlternatives(self, dependent_type, required_type_alternatives): 5412 r""" 5413 Requirements: 5414 NOTE: As of 2019-04, cycles in the requirement graph are not supported, 5415 and lead to the dependent nodes being skipped if possible (otherwise 5416 the model is considered infeasible). 5417 The following functions specify that "dependent_type" requires at least 5418 one of the types in "required_type_alternatives". 5419 5420 For same-vehicle requirements, a node of dependent type type_D requires at 5421 least one node of type type_R among the required alternatives on the same 5422 route. 5423 NOTE: To avoid unnecessary memory reallocations, it is recommended to only 5424 add requirements once all the existing types have been set with 5425 SetVisitType(). 5426 """ 5427 return _pywrapcp.RoutingModel_AddSameVehicleRequiredTypeAlternatives(self, dependent_type, required_type_alternatives) 5428 5429 def AddRequiredTypeAlternativesWhenAddingType(self, dependent_type, required_type_alternatives): 5430 r""" 5431 If type_D depends on type_R when adding type_D, any node_D of type_D and 5432 VisitTypePolicy TYPE_ADDED_TO_VEHICLE or 5433 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED requires at least one type_R on its 5434 vehicle at the time node_D is visited. 5435 """ 5436 return _pywrapcp.RoutingModel_AddRequiredTypeAlternativesWhenAddingType(self, dependent_type, required_type_alternatives) 5437 5438 def AddRequiredTypeAlternativesWhenRemovingType(self, dependent_type, required_type_alternatives): 5439 r""" 5440 The following requirements apply when visiting dependent nodes that remove 5441 their type from the route, i.e. type_R must be on the vehicle when type_D 5442 of VisitTypePolicy ADDED_TYPE_REMOVED_FROM_VEHICLE, 5443 TYPE_ON_VEHICLE_UP_TO_VISIT or TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED is 5444 visited. 5445 """ 5446 return _pywrapcp.RoutingModel_AddRequiredTypeAlternativesWhenRemovingType(self, dependent_type, required_type_alternatives) 5447 5448 def GetSameVehicleRequiredTypeAlternativesOfType(self, type): 5449 r""" 5450 Returns the set of same-vehicle requirement alternatives for the given 5451 type. 5452 """ 5453 return _pywrapcp.RoutingModel_GetSameVehicleRequiredTypeAlternativesOfType(self, type) 5454 5455 def GetRequiredTypeAlternativesWhenAddingType(self, type): 5456 r"""Returns the set of requirement alternatives when adding the given type.""" 5457 return _pywrapcp.RoutingModel_GetRequiredTypeAlternativesWhenAddingType(self, type) 5458 5459 def GetRequiredTypeAlternativesWhenRemovingType(self, type): 5460 r"""Returns the set of requirement alternatives when removing the given type.""" 5461 return _pywrapcp.RoutingModel_GetRequiredTypeAlternativesWhenRemovingType(self, type) 5462 5463 def HasSameVehicleTypeRequirements(self): 5464 r""" 5465 Returns true iff any same-route (resp. temporal) type requirements have 5466 been added to the model. 5467 """ 5468 return _pywrapcp.RoutingModel_HasSameVehicleTypeRequirements(self) 5469 5470 def HasTemporalTypeRequirements(self): 5471 return _pywrapcp.RoutingModel_HasTemporalTypeRequirements(self) 5472 5473 def HasTypeRegulations(self): 5474 r""" 5475 Returns true iff the model has any incompatibilities or requirements set 5476 on node types. 5477 """ 5478 return _pywrapcp.RoutingModel_HasTypeRegulations(self) 5479 5480 def UnperformedPenalty(self, var_index): 5481 r""" 5482 Get the "unperformed" penalty of a node. This is only well defined if the 5483 node is only part of a single Disjunction, and that disjunction has a 5484 penalty. For forced active nodes returns max int64_t. In all other cases, 5485 this returns 0. 5486 """ 5487 return _pywrapcp.RoutingModel_UnperformedPenalty(self, var_index) 5488 5489 def UnperformedPenaltyOrValue(self, default_value, var_index): 5490 r""" 5491 Same as above except that it returns default_value instead of 0 when 5492 penalty is not well defined (default value is passed as first argument to 5493 simplify the usage of the method in a callback). 5494 """ 5495 return _pywrapcp.RoutingModel_UnperformedPenaltyOrValue(self, default_value, var_index) 5496 5497 def GetDepot(self): 5498 r""" 5499 Returns the variable index of the first starting or ending node of all 5500 routes. If all routes start and end at the same node (single depot), this 5501 is the node returned. 5502 """ 5503 return _pywrapcp.RoutingModel_GetDepot(self) 5504 5505 def SetMaximumNumberOfActiveVehicles(self, max_active_vehicles): 5506 r""" 5507 Constrains the maximum number of active vehicles, aka the number of 5508 vehicles which do not have an empty route. For instance, this can be used 5509 to limit the number of routes in the case where there are fewer drivers 5510 than vehicles and that the fleet of vehicle is heterogeneous. 5511 """ 5512 return _pywrapcp.RoutingModel_SetMaximumNumberOfActiveVehicles(self, max_active_vehicles) 5513 5514 def GetMaximumNumberOfActiveVehicles(self): 5515 r"""Returns the maximum number of active vehicles.""" 5516 return _pywrapcp.RoutingModel_GetMaximumNumberOfActiveVehicles(self) 5517 5518 def SetArcCostEvaluatorOfAllVehicles(self, evaluator_index): 5519 r""" 5520 Sets the cost function of the model such that the cost of a segment of a 5521 route between node 'from' and 'to' is evaluator(from, to), whatever the 5522 route or vehicle performing the route. 5523 """ 5524 return _pywrapcp.RoutingModel_SetArcCostEvaluatorOfAllVehicles(self, evaluator_index) 5525 5526 def SetArcCostEvaluatorOfVehicle(self, evaluator_index, vehicle): 5527 r"""Sets the cost function for a given vehicle route.""" 5528 return _pywrapcp.RoutingModel_SetArcCostEvaluatorOfVehicle(self, evaluator_index, vehicle) 5529 5530 def SetFixedCostOfAllVehicles(self, cost): 5531 r""" 5532 Sets the fixed cost of all vehicle routes. It is equivalent to calling 5533 SetFixedCostOfVehicle on all vehicle routes. 5534 """ 5535 return _pywrapcp.RoutingModel_SetFixedCostOfAllVehicles(self, cost) 5536 5537 def SetFixedCostOfVehicle(self, cost, vehicle): 5538 r"""Sets the fixed cost of one vehicle route.""" 5539 return _pywrapcp.RoutingModel_SetFixedCostOfVehicle(self, cost, vehicle) 5540 5541 def GetFixedCostOfVehicle(self, vehicle): 5542 r""" 5543 Returns the route fixed cost taken into account if the route of the 5544 vehicle is not empty, aka there's at least one node on the route other 5545 than the first and last nodes. 5546 """ 5547 return _pywrapcp.RoutingModel_GetFixedCostOfVehicle(self, vehicle) 5548 5549 def SetPathEnergyCostOfVehicle(self, force, distance, cost_per_unit, vehicle): 5550 return _pywrapcp.RoutingModel_SetPathEnergyCostOfVehicle(self, force, distance, cost_per_unit, vehicle) 5551 5552 def SetPathEnergyCostsOfVehicle(self, force, distance, threshold, cost_per_unit_below_threshold, cost_per_unit_above_threshold, vehicle): 5553 return _pywrapcp.RoutingModel_SetPathEnergyCostsOfVehicle(self, force, distance, threshold, cost_per_unit_below_threshold, cost_per_unit_above_threshold, vehicle) 5554 5555 def SetAmortizedCostFactorsOfAllVehicles(self, linear_cost_factor, quadratic_cost_factor): 5556 r""" 5557 The following methods set the linear and quadratic cost factors of 5558 vehicles (must be positive values). The default value of these parameters 5559 is zero for all vehicles. 5560 5561 When set, the cost_ of the model will contain terms aiming at reducing the 5562 number of vehicles used in the model, by adding the following to the 5563 objective for every vehicle v: 5564 INDICATOR(v used in the model) * 5565 [linear_cost_factor_of_vehicle_[v] 5566 - quadratic_cost_factor_of_vehicle_[v]*(square of length of route v)] 5567 i.e. for every used vehicle, we add the linear factor as fixed cost, and 5568 subtract the square of the route length multiplied by the quadratic 5569 factor. This second term aims at making the routes as dense as possible. 5570 5571 Sets the linear and quadratic cost factor of all vehicles. 5572 """ 5573 return _pywrapcp.RoutingModel_SetAmortizedCostFactorsOfAllVehicles(self, linear_cost_factor, quadratic_cost_factor) 5574 5575 def SetAmortizedCostFactorsOfVehicle(self, linear_cost_factor, quadratic_cost_factor, vehicle): 5576 r"""Sets the linear and quadratic cost factor of the given vehicle.""" 5577 return _pywrapcp.RoutingModel_SetAmortizedCostFactorsOfVehicle(self, linear_cost_factor, quadratic_cost_factor, vehicle) 5578 5579 def GetAmortizedLinearCostFactorOfVehicles(self): 5580 return _pywrapcp.RoutingModel_GetAmortizedLinearCostFactorOfVehicles(self) 5581 5582 def GetAmortizedQuadraticCostFactorOfVehicles(self): 5583 return _pywrapcp.RoutingModel_GetAmortizedQuadraticCostFactorOfVehicles(self) 5584 5585 def GetRouteCost(self, route): 5586 return _pywrapcp.RoutingModel_GetRouteCost(self, route) 5587 5588 def SetVehicleUsedWhenEmpty(self, is_used, vehicle): 5589 return _pywrapcp.RoutingModel_SetVehicleUsedWhenEmpty(self, is_used, vehicle) 5590 5591 def IsVehicleUsedWhenEmpty(self, vehicle): 5592 return _pywrapcp.RoutingModel_IsVehicleUsedWhenEmpty(self, vehicle) 5593 5594 def SetFirstSolutionEvaluator(self, evaluator): 5595 r""" 5596 Gets/sets the evaluator used during the search. Only relevant when 5597 RoutingSearchParameters.first_solution_strategy = EVALUATOR_STRATEGY. 5598 Takes ownership of evaluator. 5599 """ 5600 return _pywrapcp.RoutingModel_SetFirstSolutionEvaluator(self, evaluator) 5601 5602 def SetFirstSolutionHint(self, hint): 5603 r""" 5604 Adds a hint to be used by first solution strategies. The hint assignment 5605 must outlive the search. 5606 As of 2024-12, only used by LOCAL_CHEAPEST_INSERTION and 5607 LOCAL_CHEAPEST_COST_INSERTION. 5608 """ 5609 return _pywrapcp.RoutingModel_SetFirstSolutionHint(self, hint) 5610 5611 def GetFirstSolutionHint(self): 5612 r"""Returns the current hint assignment.""" 5613 return _pywrapcp.RoutingModel_GetFirstSolutionHint(self) 5614 5615 def AddLocalSearchOperator(self, ls_operator): 5616 r""" 5617 Adds a local search operator to the set of operators used to solve the 5618 vehicle routing problem. 5619 """ 5620 return _pywrapcp.RoutingModel_AddLocalSearchOperator(self, ls_operator) 5621 5622 def AddSearchMonitor(self, monitor): 5623 r"""Adds a search monitor to the search used to solve the routing model.""" 5624 return _pywrapcp.RoutingModel_AddSearchMonitor(self, monitor) 5625 5626 def AddEnterSearchCallback(self, callback): 5627 return _pywrapcp.RoutingModel_AddEnterSearchCallback(self, callback) 5628 5629 def AddAtSolutionCallback(self, callback, track_unchecked_neighbors=False): 5630 r""" 5631 Adds a callback called each time a solution is found during the search. 5632 This is a shortcut to creating a monitor to call the callback on 5633 AtSolution() and adding it with AddSearchMonitor. 5634 If track_unchecked_neighbors is true, the callback will also be called on 5635 AcceptUncheckedNeighbor() events, which is useful to grab solutions 5636 obtained when solver_parameters.check_solution_period > 1 (aka fastLS). 5637 """ 5638 return _pywrapcp.RoutingModel_AddAtSolutionCallback(self, callback, track_unchecked_neighbors) 5639 5640 def AddRestoreDimensionValuesResetCallback(self, callback): 5641 return _pywrapcp.RoutingModel_AddRestoreDimensionValuesResetCallback(self, callback) 5642 5643 def AddVariableMinimizedByFinalizer(self, var): 5644 r""" 5645 Adds a variable to minimize in the solution finalizer. The solution 5646 finalizer is called each time a solution is found during the search and 5647 allows to instantiate secondary variables (such as dimension cumul 5648 variables). 5649 """ 5650 return _pywrapcp.RoutingModel_AddVariableMinimizedByFinalizer(self, var) 5651 5652 def AddVariableMaximizedByFinalizer(self, var): 5653 r""" 5654 Adds a variable to maximize in the solution finalizer (see above for 5655 information on the solution finalizer). 5656 """ 5657 return _pywrapcp.RoutingModel_AddVariableMaximizedByFinalizer(self, var) 5658 5659 def AddWeightedVariableMinimizedByFinalizer(self, var, cost): 5660 r""" 5661 Adds a variable to minimize in the solution finalizer, with a weighted 5662 priority: the higher the more priority it has. 5663 """ 5664 return _pywrapcp.RoutingModel_AddWeightedVariableMinimizedByFinalizer(self, var, cost) 5665 5666 def AddWeightedVariableMaximizedByFinalizer(self, var, cost): 5667 r""" 5668 Adds a variable to maximize in the solution finalizer, with a weighted 5669 priority: the higher the more priority it has. 5670 """ 5671 return _pywrapcp.RoutingModel_AddWeightedVariableMaximizedByFinalizer(self, var, cost) 5672 5673 def AddVariableTargetToFinalizer(self, var, target): 5674 r""" 5675 Add a variable to set the closest possible to the target value in the 5676 solution finalizer. 5677 """ 5678 return _pywrapcp.RoutingModel_AddVariableTargetToFinalizer(self, var, target) 5679 5680 def AddWeightedVariableTargetToFinalizer(self, var, target, cost): 5681 r""" 5682 Same as above with a weighted priority: the higher the cost, the more 5683 priority it has to be set close to the target value. 5684 """ 5685 return _pywrapcp.RoutingModel_AddWeightedVariableTargetToFinalizer(self, var, target, cost) 5686 5687 def CloseModel(self): 5688 r""" 5689 Closes the current routing model; after this method is called, no 5690 modification to the model can be done, but RoutesToAssignment becomes 5691 available. Note that CloseModel() is automatically called by Solve() and 5692 other methods that produce solution. 5693 This is equivalent to calling 5694 CloseModelWithParameters(DefaultRoutingSearchParameters()). 5695 """ 5696 return _pywrapcp.RoutingModel_CloseModel(self) 5697 5698 def CloseModelWithParameters(self, search_parameters): 5699 r""" 5700 Same as above taking search parameters (as of 10/2015 some the parameters 5701 have to be set when closing the model). 5702 """ 5703 return _pywrapcp.RoutingModel_CloseModelWithParameters(self, search_parameters) 5704 5705 def Solve(self, assignment=None): 5706 r""" 5707 Solves the current routing model; closes the current model. 5708 This is equivalent to calling 5709 SolveWithParameters(DefaultRoutingSearchParameters()) 5710 or 5711 SolveFromAssignmentWithParameters(assignment, 5712 DefaultRoutingSearchParameters()). 5713 """ 5714 return _pywrapcp.RoutingModel_Solve(self, assignment) 5715 5716 def SolveWithParameters(self, search_parameters, solutions=None): 5717 r""" 5718 Solves the current routing model with the given parameters. If 'solutions' 5719 is specified, it will contain the k best solutions found during the search 5720 (from worst to best, including the one returned by this method), where k 5721 corresponds to the 'number_of_solutions_to_collect' in 5722 'search_parameters'. Note that the Assignment returned by the method and 5723 the ones in solutions are owned by the underlying solver and should not be 5724 deleted. 5725 """ 5726 return _pywrapcp.RoutingModel_SolveWithParameters(self, search_parameters, solutions) 5727 5728 def SolveFromAssignmentWithParameters(self, assignment, search_parameters, solutions=None): 5729 r""" 5730 Same as above, except that if assignment is not null, it will be used as 5731 the initial solution. 5732 """ 5733 return _pywrapcp.RoutingModel_SolveFromAssignmentWithParameters(self, assignment, search_parameters, solutions) 5734 5735 def FastSolveFromAssignmentWithParameters(self, assignment, search_parameters, check_solution_in_cp, touched=None): 5736 r""" 5737 Improves a given assignment using unchecked local search. 5738 If check_solution_in_cp is true the final solution will be checked with 5739 the CP solver. 5740 As of 11/2023, only works with greedy descent. 5741 """ 5742 return _pywrapcp.RoutingModel_FastSolveFromAssignmentWithParameters(self, assignment, search_parameters, check_solution_in_cp, touched) 5743 5744 def SolveFromAssignmentsWithParameters(self, assignments, search_parameters, solutions=None): 5745 r""" 5746 Same as above but will try all assignments in order as first solutions 5747 until one succeeds. 5748 """ 5749 return _pywrapcp.RoutingModel_SolveFromAssignmentsWithParameters(self, assignments, search_parameters, solutions) 5750 5751 def SolveWithIteratedLocalSearch(self, search_parameters): 5752 r""" 5753 Solves the current routing model by using an Iterated Local Search 5754 approach. 5755 """ 5756 return _pywrapcp.RoutingModel_SolveWithIteratedLocalSearch(self, search_parameters) 5757 5758 def SetAssignmentFromOtherModelAssignment(self, target_assignment, source_model, source_assignment): 5759 r""" 5760 Given a "source_model" and its "source_assignment", resets 5761 "target_assignment" with the IntVar variables (nexts_, and vehicle_vars_ 5762 if costs aren't homogeneous across vehicles) of "this" model, with the 5763 values set according to those in "other_assignment". 5764 The objective_element of target_assignment is set to this->cost_. 5765 """ 5766 return _pywrapcp.RoutingModel_SetAssignmentFromOtherModelAssignment(self, target_assignment, source_model, source_assignment) 5767 5768 def GetSubSolverStatistics(self): 5769 r"""Returns detailed search statistics.""" 5770 return _pywrapcp.RoutingModel_GetSubSolverStatistics(self) 5771 5772 def ComputeLowerBound(self): 5773 r""" 5774 Computes a lower bound to the routing problem solving a linear assignment 5775 problem. The routing model must be closed before calling this method. 5776 Note that problems with node disjunction constraints (including optional 5777 nodes) and non-homogenous costs are not supported (the method returns 0 in 5778 these cases). 5779 """ 5780 return _pywrapcp.RoutingModel_ComputeLowerBound(self) 5781 5782 def objective_lower_bound(self): 5783 r""" 5784 Returns the current lower bound found by internal solvers during the 5785 search. 5786 """ 5787 return _pywrapcp.RoutingModel_objective_lower_bound(self) 5788 5789 def status(self): 5790 r"""Returns the current status of the routing model.""" 5791 return _pywrapcp.RoutingModel_status(self) 5792 5793 def search_stats(self): 5794 r"""Returns search statistics.""" 5795 return _pywrapcp.RoutingModel_search_stats(self) 5796 5797 def enable_deep_serialization(self): 5798 r"""Returns the value of the internal enable_deep_serialization_ parameter.""" 5799 return _pywrapcp.RoutingModel_enable_deep_serialization(self) 5800 5801 def ApplyLocks(self, locks): 5802 r""" 5803 Applies a lock chain to the next search. 'locks' represents an ordered 5804 vector of nodes representing a partial route which will be fixed during 5805 the next search; it will constrain next variables such that: 5806 next[locks[i]] == locks[i+1]. 5807 5808 Returns the next variable at the end of the locked chain; this variable is 5809 not locked. An assignment containing the locks can be obtained by calling 5810 PreAssignment(). 5811 """ 5812 return _pywrapcp.RoutingModel_ApplyLocks(self, locks) 5813 5814 def ApplyLocksToAllVehicles(self, locks, close_routes): 5815 r""" 5816 Applies lock chains to all vehicles to the next search, such that locks[p] 5817 is the lock chain for route p. Returns false if the locks do not contain 5818 valid routes; expects that the routes do not contain the depots, 5819 i.e. there are empty vectors in place of empty routes. 5820 If close_routes is set to true, adds the end nodes to the route of each 5821 vehicle and deactivates other nodes. 5822 An assignment containing the locks can be obtained by calling 5823 PreAssignment(). 5824 """ 5825 return _pywrapcp.RoutingModel_ApplyLocksToAllVehicles(self, locks, close_routes) 5826 5827 def PreAssignment(self): 5828 r""" 5829 Returns an assignment used to fix some of the variables of the problem. 5830 In practice, this assignment locks partial routes of the problem. This 5831 can be used in the context of locking the parts of the routes which have 5832 already been driven in online routing problems. 5833 """ 5834 return _pywrapcp.RoutingModel_PreAssignment(self) 5835 5836 def MutablePreAssignment(self): 5837 return _pywrapcp.RoutingModel_MutablePreAssignment(self) 5838 5839 def WriteAssignment(self, file_name): 5840 r""" 5841 Writes the current solution to a file containing an AssignmentProto. 5842 Returns false if the file cannot be opened or if there is no current 5843 solution. 5844 """ 5845 return _pywrapcp.RoutingModel_WriteAssignment(self, file_name) 5846 5847 def ReadAssignment(self, file_name): 5848 r""" 5849 Reads an assignment from a file and returns the current solution. 5850 Returns nullptr if the file cannot be opened or if the assignment is not 5851 valid. 5852 """ 5853 return _pywrapcp.RoutingModel_ReadAssignment(self, file_name) 5854 5855 def RestoreAssignment(self, solution): 5856 r""" 5857 Restores an assignment as a solution in the routing model and returns the 5858 new solution. Returns nullptr if the assignment is not valid. 5859 """ 5860 return _pywrapcp.RoutingModel_RestoreAssignment(self, solution) 5861 5862 def ReadAssignmentFromRoutes(self, routes, ignore_inactive_indices): 5863 r""" 5864 Restores the routes as the current solution. Returns nullptr if the 5865 solution cannot be restored (routes do not contain a valid solution). Note 5866 that calling this method will run the solver to assign values to the 5867 dimension variables; this may take considerable amount of time, especially 5868 when using dimensions with slack. 5869 """ 5870 return _pywrapcp.RoutingModel_ReadAssignmentFromRoutes(self, routes, ignore_inactive_indices) 5871 5872 def RoutesToAssignment(self, routes, ignore_inactive_indices, close_routes, assignment): 5873 r""" 5874 Fills an assignment from a specification of the routes of the 5875 vehicles. The routes are specified as lists of variable indices that 5876 appear on the routes of the vehicles. The indices of the outer vector in 5877 'routes' correspond to vehicles IDs, the inner vector contains the 5878 variable indices on the routes for the given vehicle. The inner vectors 5879 must not contain the start and end indices, as these are determined by the 5880 routing model. Sets the value of NextVars in the assignment, adding the 5881 variables to the assignment if necessary. The method does not touch other 5882 variables in the assignment. The method can only be called after the model 5883 is closed. With ignore_inactive_indices set to false, this method will 5884 fail (return nullptr) in case some of the route contain indices that are 5885 deactivated in the model; when set to true, these indices will be 5886 skipped. Returns true if routes were successfully 5887 loaded. However, such assignment still might not be a valid 5888 solution to the routing problem due to more complex constraints; 5889 it is advisible to call solver()->CheckSolution() afterwards. 5890 """ 5891 return _pywrapcp.RoutingModel_RoutesToAssignment(self, routes, ignore_inactive_indices, close_routes, assignment) 5892 5893 def AssignmentToRoutes(self, assignment, routes): 5894 r""" 5895 Converts the solution in the given assignment to routes for all vehicles. 5896 Expects that assignment contains a valid solution (i.e. routes for all 5897 vehicles end with an end index for that vehicle). 5898 """ 5899 return _pywrapcp.RoutingModel_AssignmentToRoutes(self, assignment, routes) 5900 5901 def CompactAssignment(self, assignment): 5902 r""" 5903 Converts the solution in the given assignment to routes for all vehicles. 5904 If the returned vector is route_indices, route_indices[i][j] is the index 5905 for jth location visited on route i. Note that contrary to 5906 AssignmentToRoutes, the vectors do include start and end locations. 5907 Returns a compacted version of the given assignment, in which all vehicles 5908 with id lower or equal to some N have non-empty routes, and all vehicles 5909 with id greater than N have empty routes. Does not take ownership of the 5910 returned object. 5911 If found, the cost of the compact assignment is the same as in the 5912 original assignment and it preserves the values of 'active' variables. 5913 Returns nullptr if a compact assignment was not found. 5914 This method only works in homogenous mode, and it only swaps equivalent 5915 vehicles (vehicles with the same start and end nodes). When creating the 5916 compact assignment, the empty plan is replaced by the route assigned to 5917 the compatible vehicle with the highest id. Note that with more complex 5918 constraints on vehicle variables, this method might fail even if a compact 5919 solution exists. 5920 This method changes the vehicle and dimension variables as necessary. 5921 While compacting the solution, only basic checks on vehicle variables are 5922 performed; if one of these checks fails no attempts to repair it are made 5923 (instead, the method returns nullptr). 5924 """ 5925 return _pywrapcp.RoutingModel_CompactAssignment(self, assignment) 5926 5927 def CompactAndCheckAssignment(self, assignment): 5928 r""" 5929 Same as CompactAssignment() but also checks the validity of the final 5930 compact solution; if it is not valid, no attempts to repair it are made 5931 (instead, the method returns nullptr). 5932 """ 5933 return _pywrapcp.RoutingModel_CompactAndCheckAssignment(self, assignment) 5934 5935 def AddToAssignment(self, var): 5936 r"""Adds an extra variable to the vehicle routing assignment.""" 5937 return _pywrapcp.RoutingModel_AddToAssignment(self, var) 5938 5939 def AddIntervalToAssignment(self, interval): 5940 return _pywrapcp.RoutingModel_AddIntervalToAssignment(self, interval) 5941 5942 def PackCumulsOfOptimizerDimensionsFromAssignment(self, original_assignment, duration_limit, time_limit_was_reached=None): 5943 r""" 5944 For every dimension in the model with an optimizer in 5945 local/global_dimension_optimizers_, this method tries to pack the cumul 5946 values of the dimension, such that: 5947 - The cumul costs (span costs, soft lower and upper bound costs, etc) are 5948 minimized. 5949 - The cumuls of the ends of the routes are minimized for this given 5950 minimal cumul cost. 5951 - Given these minimal end cumuls, the route start cumuls are maximized. 5952 Returns the assignment resulting from allocating these packed cumuls with 5953 the solver, and nullptr if these cumuls could not be set by the solver. 5954 """ 5955 return _pywrapcp.RoutingModel_PackCumulsOfOptimizerDimensionsFromAssignment(self, original_assignment, duration_limit, time_limit_was_reached) 5956 5957 def GetOrCreateNodeNeighborsByCostClass(self, *args): 5958 r""" 5959 *Overload 1:* 5960 Returns neighbors of all nodes for every cost class. The result is cached 5961 and is computed once. The number of neighbors considered is based on a 5962 ratio of non-vehicle nodes, specified by neighbors_ratio, with a minimum 5963 of min-neighbors node considered. 5964 5965 | 5966 5967 *Overload 2:* 5968 Returns parameters.num_neighbors neighbors of all nodes for every cost 5969 class. The result is cached and is computed once. 5970 """ 5971 return _pywrapcp.RoutingModel_GetOrCreateNodeNeighborsByCostClass(self, *args) 5972 5973 def AddLocalSearchFilter(self, filter): 5974 r""" 5975 Adds a custom local search filter to the list of filters used to speed up 5976 local search by pruning unfeasible variable assignments. 5977 Calling this method after the routing model has been closed (CloseModel() 5978 or Solve() has been called) has no effect. 5979 The routing model does not take ownership of the filter. 5980 """ 5981 return _pywrapcp.RoutingModel_AddLocalSearchFilter(self, filter) 5982 5983 def Start(self, vehicle): 5984 r""" 5985 Model inspection. 5986 Returns the variable index of the starting node of a vehicle route. 5987 """ 5988 return _pywrapcp.RoutingModel_Start(self, vehicle) 5989 5990 def End(self, vehicle): 5991 r"""Returns the variable index of the ending node of a vehicle route.""" 5992 return _pywrapcp.RoutingModel_End(self, vehicle) 5993 5994 def IsStart(self, index): 5995 r"""Returns true if 'index' represents the first node of a route.""" 5996 return _pywrapcp.RoutingModel_IsStart(self, index) 5997 5998 def IsEnd(self, index): 5999 r"""Returns true if 'index' represents the last node of a route.""" 6000 return _pywrapcp.RoutingModel_IsEnd(self, index) 6001 6002 def VehicleIndex(self, index): 6003 r""" 6004 Returns the vehicle of the given start/end index, and -1 if the given 6005 index is not a vehicle start/end. 6006 """ 6007 return _pywrapcp.RoutingModel_VehicleIndex(self, index) 6008 6009 def Next(self, assignment, index): 6010 r""" 6011 Assignment inspection 6012 Returns the variable index of the node directly after the node 6013 corresponding to 'index' in 'assignment'. 6014 """ 6015 return _pywrapcp.RoutingModel_Next(self, assignment, index) 6016 6017 def IsVehicleUsed(self, assignment, vehicle): 6018 r"""Returns true if the route of 'vehicle' is non empty in 'assignment'.""" 6019 return _pywrapcp.RoutingModel_IsVehicleUsed(self, assignment, vehicle) 6020 6021 def NextVar(self, index): 6022 r""" 6023 Returns the next variable of the node corresponding to index. Note that 6024 NextVar(index) == index is equivalent to ActiveVar(index) == 0. 6025 """ 6026 return _pywrapcp.RoutingModel_NextVar(self, index) 6027 6028 def ActiveVar(self, index): 6029 r"""Returns the active variable of the node corresponding to index.""" 6030 return _pywrapcp.RoutingModel_ActiveVar(self, index) 6031 6032 def ActiveVehicleVar(self, vehicle): 6033 r""" 6034 Returns the active variable of the vehicle. It will be equal to 1 iff the 6035 route of the vehicle is not empty, 0 otherwise. 6036 """ 6037 return _pywrapcp.RoutingModel_ActiveVehicleVar(self, vehicle) 6038 6039 def VehicleRouteConsideredVar(self, vehicle): 6040 r""" 6041 Returns the variable specifying whether or not the given vehicle route is 6042 considered for costs and constraints. It will be equal to 1 iff the route 6043 of the vehicle is not empty OR vehicle_used_when_empty_[vehicle] is true. 6044 """ 6045 return _pywrapcp.RoutingModel_VehicleRouteConsideredVar(self, vehicle) 6046 6047 def VehicleVar(self, index): 6048 r""" 6049 Returns the vehicle variable of the node corresponding to index. Note that 6050 VehicleVar(index) == -1 is equivalent to ActiveVar(index) == 0. 6051 """ 6052 return _pywrapcp.RoutingModel_VehicleVar(self, index) 6053 6054 def ResourceVar(self, vehicle, resource_group): 6055 r""" 6056 Returns the resource variable for the given vehicle index in the given 6057 resource group. If a vehicle doesn't require a resource from the 6058 corresponding resource group, then ResourceVar(v, r_g) == -1. 6059 """ 6060 return _pywrapcp.RoutingModel_ResourceVar(self, vehicle, resource_group) 6061 6062 def CostVar(self): 6063 r"""Returns the global cost variable which is being minimized.""" 6064 return _pywrapcp.RoutingModel_CostVar(self) 6065 6066 def GetArcCostForVehicle(self, from_index, to_index, vehicle): 6067 r""" 6068 Returns the cost of the transit arc between two nodes for a given vehicle. 6069 Input are variable indices of node. This returns 0 if vehicle < 0. 6070 """ 6071 return _pywrapcp.RoutingModel_GetArcCostForVehicle(self, from_index, to_index, vehicle) 6072 6073 def CostsAreHomogeneousAcrossVehicles(self): 6074 r"""Whether costs are homogeneous across all vehicles.""" 6075 return _pywrapcp.RoutingModel_CostsAreHomogeneousAcrossVehicles(self) 6076 6077 def GetHomogeneousCost(self, from_index, to_index): 6078 r""" 6079 Returns the cost of the segment between two nodes supposing all vehicle 6080 costs are the same (returns the cost for the first vehicle otherwise). 6081 """ 6082 return _pywrapcp.RoutingModel_GetHomogeneousCost(self, from_index, to_index) 6083 6084 def GetArcCostForFirstSolution(self, from_index, to_index): 6085 r""" 6086 Returns the cost of the arc in the context of the first solution strategy. 6087 This is typically a simplification of the actual cost; see the .cc. 6088 """ 6089 return _pywrapcp.RoutingModel_GetArcCostForFirstSolution(self, from_index, to_index) 6090 6091 def GetArcCostForClass(self, from_index, to_index, cost_class_index): 6092 r""" 6093 Returns the cost of the segment between two nodes for a given cost 6094 class. Input are variable indices of nodes and the cost class. 6095 Unlike GetArcCostForVehicle(), if cost_class is kNoCost, then the 6096 returned cost won't necessarily be zero: only some of the components 6097 of the cost that depend on the cost class will be omited. See the code 6098 for details. 6099 """ 6100 return _pywrapcp.RoutingModel_GetArcCostForClass(self, from_index, to_index, cost_class_index) 6101 6102 def GetCostClassIndexOfVehicle(self, vehicle): 6103 r"""Get the cost class index of the given vehicle.""" 6104 return _pywrapcp.RoutingModel_GetCostClassIndexOfVehicle(self, vehicle) 6105 6106 def HasVehicleWithCostClassIndex(self, cost_class_index): 6107 r""" 6108 Returns true iff the model contains a vehicle with the given 6109 cost_class_index. 6110 """ 6111 return _pywrapcp.RoutingModel_HasVehicleWithCostClassIndex(self, cost_class_index) 6112 6113 def GetCostClassesCount(self): 6114 r"""Returns the number of different cost classes in the model.""" 6115 return _pywrapcp.RoutingModel_GetCostClassesCount(self) 6116 6117 def GetNonZeroCostClassesCount(self): 6118 r"""Ditto, minus the 'always zero', built-in cost class.""" 6119 return _pywrapcp.RoutingModel_GetNonZeroCostClassesCount(self) 6120 6121 def GetVehicleClassIndexOfVehicle(self, vehicle): 6122 return _pywrapcp.RoutingModel_GetVehicleClassIndexOfVehicle(self, vehicle) 6123 6124 def GetVehicleOfClass(self, vehicle_class): 6125 r""" 6126 Returns a vehicle of the given vehicle class, and -1 if there are no 6127 vehicles for this class. 6128 """ 6129 return _pywrapcp.RoutingModel_GetVehicleOfClass(self, vehicle_class) 6130 6131 def GetVehicleClassesCount(self): 6132 r"""Returns the number of different vehicle classes in the model.""" 6133 return _pywrapcp.RoutingModel_GetVehicleClassesCount(self) 6134 6135 def GetSameVehicleIndicesOfIndex(self, node): 6136 r"""Returns variable indices of nodes constrained to be on the same route.""" 6137 return _pywrapcp.RoutingModel_GetSameVehicleIndicesOfIndex(self, node) 6138 6139 def AddSameActivityGroup(self, nodes): 6140 return _pywrapcp.RoutingModel_AddSameActivityGroup(self, nodes) 6141 6142 def GetSameActivityIndicesOfIndex(self, node): 6143 r"""Returns variable indices of nodes constrained to have the same activity.""" 6144 return _pywrapcp.RoutingModel_GetSameActivityIndicesOfIndex(self, node) 6145 6146 def GetSameActivityGroupOfIndex(self, node): 6147 r"""Returns the same activity group of the node.""" 6148 return _pywrapcp.RoutingModel_GetSameActivityGroupOfIndex(self, node) 6149 6150 def GetSameActivityGroups(self): 6151 r"""Returns same activity groups of all nodes.""" 6152 return _pywrapcp.RoutingModel_GetSameActivityGroups(self) 6153 6154 def GetSameActivityGroupsCount(self): 6155 r"""Returns the number of same activity groups.""" 6156 return _pywrapcp.RoutingModel_GetSameActivityGroupsCount(self) 6157 6158 def GetSameActivityIndicesOfGroup(self, group): 6159 r"""Returns variable indices of nodes in the same activity group.""" 6160 return _pywrapcp.RoutingModel_GetSameActivityIndicesOfGroup(self, group) 6161 6162 def GetVehicleTypeContainer(self): 6163 return _pywrapcp.RoutingModel_GetVehicleTypeContainer(self) 6164 6165 def ArcIsMoreConstrainedThanArc(self, _from, to1, to2): 6166 r""" 6167 Returns whether the arc from->to1 is more constrained than from->to2, 6168 taking into account, in order: 6169 - whether the destination node isn't an end node 6170 - whether the destination node is mandatory 6171 - whether the destination node is bound to the same vehicle as the source 6172 - the "primary constrained" dimension (see SetPrimaryConstrainedDimension) 6173 It then breaks ties using, in order: 6174 - the arc cost (taking unperformed penalties into account) 6175 - the size of the vehicle vars of "to1" and "to2" (lowest size wins) 6176 - the value: the lowest value of the indices to1 and to2 wins. 6177 See the .cc for details. 6178 The more constrained arc is typically preferable when building a 6179 first solution. This method is intended to be used as a callback for the 6180 BestValueByComparisonSelector value selector. 6181 Args: 6182 from: the variable index of the source node 6183 to1: the variable index of the first candidate destination node. 6184 to2: the variable index of the second candidate destination node. 6185 """ 6186 return _pywrapcp.RoutingModel_ArcIsMoreConstrainedThanArc(self, _from, to1, to2) 6187 6188 def DebugOutputAssignment(self, solution_assignment, dimension_to_print): 6189 r""" 6190 Print some debugging information about an assignment, including the 6191 feasible intervals of the CumulVar for dimension "dimension_to_print" 6192 at each step of the routes. 6193 If "dimension_to_print" is omitted, all dimensions will be printed. 6194 """ 6195 return _pywrapcp.RoutingModel_DebugOutputAssignment(self, solution_assignment, dimension_to_print) 6196 6197 def CheckIfAssignmentIsFeasible(self, assignment, call_at_solution_monitors): 6198 r""" 6199 Returns a vector cumul_bounds, for which cumul_bounds[i][j] is a pair 6200 containing the minimum and maximum of the CumulVar of the jth node on 6201 route i. 6202 - cumul_bounds[i][j].first is the minimum. 6203 - cumul_bounds[i][j].second is the maximum. 6204 Checks if an assignment is feasible. 6205 """ 6206 return _pywrapcp.RoutingModel_CheckIfAssignmentIsFeasible(self, assignment, call_at_solution_monitors) 6207 6208 def solver(self): 6209 r""" 6210 Returns the underlying constraint solver. Can be used to add extra 6211 constraints and/or modify search algorithms. 6212 """ 6213 return _pywrapcp.RoutingModel_solver(self) 6214 6215 def CheckLimit(self, *args): 6216 r""" 6217 Returns true if the search limit has been crossed with the given time 6218 offset. 6219 """ 6220 return _pywrapcp.RoutingModel_CheckLimit(self, *args) 6221 6222 def RemainingTime(self): 6223 r"""Returns the time left in the search limit.""" 6224 return _pywrapcp.RoutingModel_RemainingTime(self) 6225 6226 def UpdateTimeLimit(self, time_limit): 6227 r"""Updates the time limit of the search limit.""" 6228 return _pywrapcp.RoutingModel_UpdateTimeLimit(self, time_limit) 6229 6230 def TimeBuffer(self): 6231 r"""Returns the time buffer to safely return a solution.""" 6232 return _pywrapcp.RoutingModel_TimeBuffer(self) 6233 6234 def GetMutableCPSatInterrupt(self): 6235 r"""Returns the atomic<bool> to stop the CP-SAT solver.""" 6236 return _pywrapcp.RoutingModel_GetMutableCPSatInterrupt(self) 6237 6238 def GetMutableCPInterrupt(self): 6239 r"""Returns the atomic<bool> to stop the CP solver.""" 6240 return _pywrapcp.RoutingModel_GetMutableCPInterrupt(self) 6241 6242 def CancelSearch(self): 6243 r"""Cancels the current search.""" 6244 return _pywrapcp.RoutingModel_CancelSearch(self) 6245 6246 def nodes(self): 6247 r""" 6248 Sizes and indices 6249 Returns the number of nodes in the model. 6250 """ 6251 return _pywrapcp.RoutingModel_nodes(self) 6252 6253 def vehicles(self): 6254 r"""Returns the number of vehicle routes in the model.""" 6255 return _pywrapcp.RoutingModel_vehicles(self) 6256 6257 def Size(self): 6258 r"""Returns the number of next variables in the model.""" 6259 return _pywrapcp.RoutingModel_Size(self) 6260 6261 def GetNumberOfDecisionsInFirstSolution(self, search_parameters): 6262 r""" 6263 Returns statistics on first solution search, number of decisions sent to 6264 filters, number of decisions rejected by filters. 6265 """ 6266 return _pywrapcp.RoutingModel_GetNumberOfDecisionsInFirstSolution(self, search_parameters) 6267 6268 def GetNumberOfRejectsInFirstSolution(self, search_parameters): 6269 return _pywrapcp.RoutingModel_GetNumberOfRejectsInFirstSolution(self, search_parameters) 6270 6271 def GetAutomaticFirstSolutionStrategy(self): 6272 r"""Returns the automatic first solution strategy selected.""" 6273 return _pywrapcp.RoutingModel_GetAutomaticFirstSolutionStrategy(self) 6274 6275 def IsMatchingModel(self): 6276 r"""Returns true if a vehicle/node matching problem is detected.""" 6277 return _pywrapcp.RoutingModel_IsMatchingModel(self) 6278 6279 def AreRoutesInterdependent(self, parameters): 6280 r""" 6281 Returns true if routes are interdependent. This means that any 6282 modification to a route might impact another. 6283 """ 6284 return _pywrapcp.RoutingModel_AreRoutesInterdependent(self, parameters) 6285 6286 def MakeGuidedSlackFinalizer(self, dimension, initializer): 6287 r""" 6288 The next few members are in the public section only for testing purposes. 6289 6290 MakeGuidedSlackFinalizer creates a DecisionBuilder for the slacks of a 6291 dimension using a callback to choose which values to start with. 6292 The finalizer works only when all next variables in the model have 6293 been fixed. It has the following two characteristics: 6294 1. It follows the routes defined by the nexts variables when choosing a 6295 variable to make a decision on. 6296 2. When it comes to choose a value for the slack of node i, the decision 6297 builder first calls the callback with argument i, and supposingly the 6298 returned value is x it creates decisions slack[i] = x, slack[i] = x + 6299 1, slack[i] = x - 1, slack[i] = x + 2, etc. 6300 """ 6301 return _pywrapcp.RoutingModel_MakeGuidedSlackFinalizer(self, dimension, initializer) 6302 6303 def MakeSelfDependentDimensionFinalizer(self, dimension): 6304 r""" 6305 MakeSelfDependentDimensionFinalizer is a finalizer for the slacks of a 6306 self-dependent dimension. It makes an extensive use of the caches of the 6307 state dependent transits. 6308 In detail, MakeSelfDependentDimensionFinalizer returns a composition of a 6309 local search decision builder with a greedy descent operator for the cumul 6310 of the start of each route and a guided slack finalizer. Provided there 6311 are no time windows and the maximum slacks are large enough, once the 6312 cumul of the start of route is fixed, the guided finalizer can find 6313 optimal values of the slacks for the rest of the route in time 6314 proportional to the length of the route. Therefore the composed finalizer 6315 generally works in time O(log(t)*n*m), where t is the latest possible 6316 departute time, n is the number of nodes in the network and m is the 6317 number of vehicles. 6318 """ 6319 return _pywrapcp.RoutingModel_MakeSelfDependentDimensionFinalizer(self, dimension) 6320 6321 def GetPathsMetadata(self): 6322 return _pywrapcp.RoutingModel_GetPathsMetadata(self) 6323 6324 def GetVehiclesOfSameClass(self, start_end_index): 6325 r""" 6326 Returns indices of the vehicles which are in the same vehicle class as the 6327 vehicle starting or ending at start_end_index. 6328 """ 6329 return _pywrapcp.RoutingModel_GetVehiclesOfSameClass(self, start_end_index) 6330 6331 def GetSameVehicleClassArcs(self, from_index, to_index): 6332 r""" 6333 Returns all arcs which are equivalent to the {from_index, to_index} arc 6334 wrt vehicle classes. Arcs will be returned only if from_index is the 6335 start of a vehicle or if to_index is the end of a vehicle. The returned 6336 arcs will then be starting or ending at start or end nodes of vehicles in 6337 the same vehicle class. The input arc is included in the returned vector. 6338 """ 6339 return _pywrapcp.RoutingModel_GetSameVehicleClassArcs(self, from_index, to_index) 6340 6341# Register RoutingModel in _pywrapcp: 6342_pywrapcp.RoutingModel_swigregister(RoutingModel) 6343cvar = _pywrapcp.cvar 6344RoutingModel.kNoPenalty = _pywrapcp.cvar.RoutingModel_kNoPenalty 6345RoutingModel.kNoDisjunction = _pywrapcp.cvar.RoutingModel_kNoDisjunction 6346RoutingModel.kNoDimension = _pywrapcp.cvar.RoutingModel_kNoDimension 6347 6348class RoutingModelVisitor(BaseObject): 6349 r"""Routing model visitor.""" 6350 6351 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6352 __repr__ = _swig_repr 6353 6354 def __init__(self): 6355 _pywrapcp.RoutingModelVisitor_swiginit(self, _pywrapcp.new_RoutingModelVisitor()) 6356 __swig_destroy__ = _pywrapcp.delete_RoutingModelVisitor 6357 6358# Register RoutingModelVisitor in _pywrapcp: 6359_pywrapcp.RoutingModelVisitor_swigregister(RoutingModelVisitor) 6360RoutingModelVisitor.kLightElement = _pywrapcp.cvar.RoutingModelVisitor_kLightElement 6361RoutingModelVisitor.kLightElement2 = _pywrapcp.cvar.RoutingModelVisitor_kLightElement2 6362RoutingModelVisitor.kRemoveValues = _pywrapcp.cvar.RoutingModelVisitor_kRemoveValues 6363 6364class TypeRegulationsChecker(object): 6365 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6366 6367 def __init__(self, *args, **kwargs): 6368 raise AttributeError("No constructor defined - class is abstract") 6369 __repr__ = _swig_repr 6370 __swig_destroy__ = _pywrapcp.delete_TypeRegulationsChecker 6371 6372 def CheckVehicle(self, vehicle, next_accessor): 6373 return _pywrapcp.TypeRegulationsChecker_CheckVehicle(self, vehicle, next_accessor) 6374 6375# Register TypeRegulationsChecker in _pywrapcp: 6376_pywrapcp.TypeRegulationsChecker_swigregister(TypeRegulationsChecker) 6377class TypeIncompatibilityChecker(TypeRegulationsChecker): 6378 r"""Checker for type incompatibilities.""" 6379 6380 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6381 __repr__ = _swig_repr 6382 6383 def __init__(self, model, check_hard_incompatibilities): 6384 _pywrapcp.TypeIncompatibilityChecker_swiginit(self, _pywrapcp.new_TypeIncompatibilityChecker(model, check_hard_incompatibilities)) 6385 __swig_destroy__ = _pywrapcp.delete_TypeIncompatibilityChecker 6386 6387# Register TypeIncompatibilityChecker in _pywrapcp: 6388_pywrapcp.TypeIncompatibilityChecker_swigregister(TypeIncompatibilityChecker) 6389class TypeRequirementChecker(TypeRegulationsChecker): 6390 r"""Checker for type requirements.""" 6391 6392 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6393 __repr__ = _swig_repr 6394 6395 def __init__(self, model): 6396 _pywrapcp.TypeRequirementChecker_swiginit(self, _pywrapcp.new_TypeRequirementChecker(model)) 6397 __swig_destroy__ = _pywrapcp.delete_TypeRequirementChecker 6398 6399# Register TypeRequirementChecker in _pywrapcp: 6400_pywrapcp.TypeRequirementChecker_swigregister(TypeRequirementChecker) 6401class TypeRegulationsConstraint(Constraint): 6402 r""" 6403 The following constraint ensures that incompatibilities and requirements 6404 between types are respected. 6405 6406 It verifies both "hard" and "temporal" incompatibilities. 6407 Two nodes with hard incompatible types cannot be served by the same vehicle 6408 at all, while with a temporal incompatibility they can't be on the same 6409 route at the same time. 6410 The VisitTypePolicy of a node determines how visiting it impacts the type 6411 count on the route. 6412 6413 For example, for 6414 - three temporally incompatible types T1 T2 and T3 6415 - 2 pairs of nodes a1/r1 and a2/r2 of type T1 and T2 respectively, with 6416 - a1 and a2 of VisitTypePolicy TYPE_ADDED_TO_VEHICLE 6417 - r1 and r2 of policy ADDED_TYPE_REMOVED_FROM_VEHICLE 6418 - 3 nodes A, UV and AR of type T3, respectively with type policies 6419 TYPE_ADDED_TO_VEHICLE, TYPE_ON_VEHICLE_UP_TO_VISIT and 6420 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED 6421 the configurations 6422 UV --> a1 --> r1 --> a2 --> r2, a1 --> r1 --> a2 --> r2 --> A and 6423 a1 --> r1 --> AR --> a2 --> r2 are acceptable, whereas the configurations 6424 a1 --> a2 --> r1 --> ..., or A --> a1 --> r1 --> ..., or 6425 a1 --> r1 --> UV --> ... are not feasible. 6426 6427 It also verifies same-vehicle and temporal type requirements. 6428 A node of type T_d with a same-vehicle requirement for type T_r needs to be 6429 served by the same vehicle as a node of type T_r. 6430 Temporal requirements, on the other hand, can take effect either when the 6431 dependent type is being added to the route or when it's removed from it, 6432 which is determined by the dependent node's VisitTypePolicy. 6433 In the above example: 6434 - If T3 is required on the same vehicle as T1, A, AR or UV must be on the 6435 same vehicle as a1. 6436 - If T2 is required when adding T1, a2 must be visited *before* a1, and if 6437 r2 is also visited on the route, it must be *after* a1, i.e. T2 must be on 6438 the vehicle when a1 is visited: 6439 ... --> a2 --> ... --> a1 --> ... --> r2 --> ... 6440 - If T3 is required when removing T1, T3 needs to be on the vehicle when 6441 r1 is visited: 6442 ... --> A --> ... --> r1 --> ... OR ... --> r1 --> ... --> UV --> ... 6443 """ 6444 6445 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6446 __repr__ = _swig_repr 6447 6448 def __init__(self, model): 6449 _pywrapcp.TypeRegulationsConstraint_swiginit(self, _pywrapcp.new_TypeRegulationsConstraint(model)) 6450 6451 def Post(self): 6452 return _pywrapcp.TypeRegulationsConstraint_Post(self) 6453 6454 def InitialPropagateWrapper(self): 6455 return _pywrapcp.TypeRegulationsConstraint_InitialPropagateWrapper(self) 6456 __swig_destroy__ = _pywrapcp.delete_TypeRegulationsConstraint 6457 6458# Register TypeRegulationsConstraint in _pywrapcp: 6459_pywrapcp.TypeRegulationsConstraint_swigregister(TypeRegulationsConstraint) 6460class BoundCost(object): 6461 r""" 6462 A structure meant to store soft bounds and associated violation constants. 6463 It is 'Simple' because it has one BoundCost per element, 6464 in contrast to 'Multiple'. Design notes: 6465 - it is meant to store model information to be shared through pointers, 6466 so it disallows copy and assign to avoid accidental duplication. 6467 - it keeps soft bounds as an array of structs to help cache, 6468 because code that uses such bounds typically use both bound and cost. 6469 - soft bounds are named pairs, prevents some mistakes. 6470 - using operator[] to access elements is not interesting, 6471 because the structure will be accessed through pointers, moreover having 6472 to type bound_cost reminds the user of the order if they do a copy 6473 assignment of the element. 6474 """ 6475 6476 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6477 __repr__ = _swig_repr 6478 bound = property(_pywrapcp.BoundCost_bound_get, _pywrapcp.BoundCost_bound_set) 6479 cost = property(_pywrapcp.BoundCost_cost_get, _pywrapcp.BoundCost_cost_set) 6480 6481 def __init__(self, *args): 6482 _pywrapcp.BoundCost_swiginit(self, _pywrapcp.new_BoundCost(*args)) 6483 __swig_destroy__ = _pywrapcp.delete_BoundCost 6484 6485# Register BoundCost in _pywrapcp: 6486_pywrapcp.BoundCost_swigregister(BoundCost) 6487class SimpleBoundCosts(object): 6488 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6489 __repr__ = _swig_repr 6490 6491 def __init__(self, num_bounds, default_bound_cost): 6492 _pywrapcp.SimpleBoundCosts_swiginit(self, _pywrapcp.new_SimpleBoundCosts(num_bounds, default_bound_cost)) 6493 6494 def bound_cost(self, element): 6495 return _pywrapcp.SimpleBoundCosts_bound_cost(self, element) 6496 6497 def size(self): 6498 return _pywrapcp.SimpleBoundCosts_size(self) 6499 __swig_destroy__ = _pywrapcp.delete_SimpleBoundCosts 6500 6501# Register SimpleBoundCosts in _pywrapcp: 6502_pywrapcp.SimpleBoundCosts_swigregister(SimpleBoundCosts) 6503class RoutingDimension(object): 6504 r""" 6505 Dimensions represent quantities accumulated at nodes along the routes. They 6506 represent quantities such as weights or volumes carried along the route, or 6507 distance or times. 6508 6509 Quantities at a node are represented by "cumul" variables and the increase 6510 or decrease of quantities between nodes are represented by "transit" 6511 variables. These variables are linked as follows: 6512 6513 if j == next(i), 6514 cumuls(j) = cumuls(i) + transits(i) + slacks(i) + 6515 state_dependent_transits(i) 6516 6517 where slack is a positive slack variable (can represent waiting times for 6518 a time dimension), and state_dependent_transits is a non-purely functional 6519 version of transits_. Favour transits over state_dependent_transits when 6520 possible, because purely functional callbacks allow more optimisations and 6521 make the model faster and easier to solve. 6522 for a given vehicle, it is passed as an external vector, it would be better 6523 to have this information here. 6524 """ 6525 6526 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6527 6528 def __init__(self, *args, **kwargs): 6529 raise AttributeError("No constructor defined") 6530 __repr__ = _swig_repr 6531 __swig_destroy__ = _pywrapcp.delete_RoutingDimension 6532 6533 def model(self): 6534 r"""Returns the model on which the dimension was created.""" 6535 return _pywrapcp.RoutingDimension_model(self) 6536 6537 def GetTransitValue(self, from_index, to_index, vehicle): 6538 r""" 6539 Returns the transition value for a given pair of nodes (as var index); 6540 this value is the one taken by the corresponding transit variable when 6541 the 'next' variable for 'from_index' is bound to 'to_index'. 6542 """ 6543 return _pywrapcp.RoutingDimension_GetTransitValue(self, from_index, to_index, vehicle) 6544 6545 def GetTransitValueFromClass(self, from_index, to_index, vehicle_class): 6546 r""" 6547 Same as above but taking a vehicle class of the dimension instead of a 6548 vehicle (the class of a vehicle can be obtained with vehicle_to_class()). 6549 """ 6550 return _pywrapcp.RoutingDimension_GetTransitValueFromClass(self, from_index, to_index, vehicle_class) 6551 6552 def CumulVar(self, index): 6553 r""" 6554 Get the cumul, transit and slack variables for the given node (given as 6555 int64_t var index). 6556 """ 6557 return _pywrapcp.RoutingDimension_CumulVar(self, index) 6558 6559 def TransitVar(self, index): 6560 return _pywrapcp.RoutingDimension_TransitVar(self, index) 6561 6562 def FixedTransitVar(self, index): 6563 return _pywrapcp.RoutingDimension_FixedTransitVar(self, index) 6564 6565 def SlackVar(self, index): 6566 return _pywrapcp.RoutingDimension_SlackVar(self, index) 6567 6568 def SetCumulVarRange(self, index, min, max): 6569 r""" 6570 Some functions to allow users to use the interface without knowing about 6571 the underlying CP model. 6572 Restricts the range of the cumul variable associated to index. 6573 """ 6574 return _pywrapcp.RoutingDimension_SetCumulVarRange(self, index, min, max) 6575 6576 def GetCumulVarMin(self, index): 6577 r"""Gets the current minimum of the cumul variable associated to index.""" 6578 return _pywrapcp.RoutingDimension_GetCumulVarMin(self, index) 6579 6580 def GetCumulVarMax(self, index): 6581 r"""Gets the current maximum of the cumul variable associated to index.""" 6582 return _pywrapcp.RoutingDimension_GetCumulVarMax(self, index) 6583 6584 def SetSpanUpperBoundForVehicle(self, upper_bound, vehicle): 6585 r""" 6586 Sets an upper bound on the dimension span on a given vehicle. This is the 6587 preferred way to limit the "length" of the route of a vehicle according to 6588 a dimension. 6589 """ 6590 return _pywrapcp.RoutingDimension_SetSpanUpperBoundForVehicle(self, upper_bound, vehicle) 6591 6592 def SetSpanCostCoefficientForVehicle(self, coefficient, vehicle): 6593 r""" 6594 Sets a cost proportional to the dimension span on a given vehicle, 6595 or on all vehicles at once. "coefficient" must be nonnegative. 6596 This is handy to model costs proportional to idle time when the dimension 6597 represents time. 6598 The cost for a vehicle is 6599 span_cost = coefficient * (dimension end value - dimension start value). 6600 """ 6601 return _pywrapcp.RoutingDimension_SetSpanCostCoefficientForVehicle(self, coefficient, vehicle) 6602 6603 def SetSpanCostCoefficientForAllVehicles(self, coefficient): 6604 return _pywrapcp.RoutingDimension_SetSpanCostCoefficientForAllVehicles(self, coefficient) 6605 6606 def SetSlackCostCoefficientForVehicle(self, coefficient, vehicle): 6607 r""" 6608 Sets a cost proportional to the dimension total slack on a given vehicle, 6609 or on all vehicles at once. "coefficient" must be nonnegative. 6610 This is handy to model costs only proportional to idle time when the 6611 dimension represents time. 6612 The cost for a vehicle is 6613 slack_cost = coefficient * 6614 (dimension end value - dimension start value - total_transit). 6615 """ 6616 return _pywrapcp.RoutingDimension_SetSlackCostCoefficientForVehicle(self, coefficient, vehicle) 6617 6618 def SetSlackCostCoefficientForAllVehicles(self, coefficient): 6619 return _pywrapcp.RoutingDimension_SetSlackCostCoefficientForAllVehicles(self, coefficient) 6620 6621 def SetGlobalSpanCostCoefficient(self, coefficient): 6622 r""" 6623 Sets a cost proportional to the *global* dimension span, that is the 6624 difference between the largest value of route end cumul variables and 6625 the smallest value of route start cumul variables. 6626 In other words: 6627 global_span_cost = 6628 coefficient * (Max(dimension end value) - Min(dimension start value)). 6629 """ 6630 return _pywrapcp.RoutingDimension_SetGlobalSpanCostCoefficient(self, coefficient) 6631 6632 def SetCumulVarSoftUpperBound(self, index, upper_bound, coefficient): 6633 r""" 6634 Sets a soft upper bound to the cumul variable of a given variable index. 6635 If the value of the cumul variable is greater than the bound, a cost 6636 proportional to the difference between this value and the bound is added 6637 to the cost function of the model: 6638 cumulVar <= upper_bound -> cost = 0 6639 cumulVar > upper_bound -> cost = coefficient * (cumulVar - upper_bound) 6640 This is also handy to model tardiness costs when the dimension represents 6641 time. 6642 """ 6643 return _pywrapcp.RoutingDimension_SetCumulVarSoftUpperBound(self, index, upper_bound, coefficient) 6644 6645 def HasCumulVarSoftUpperBound(self, index): 6646 r""" 6647 Returns true if a soft upper bound has been set for a given variable 6648 index. 6649 """ 6650 return _pywrapcp.RoutingDimension_HasCumulVarSoftUpperBound(self, index) 6651 6652 def GetCumulVarSoftUpperBound(self, index): 6653 r""" 6654 Returns the soft upper bound of a cumul variable for a given variable 6655 index. The "hard" upper bound of the variable is returned if no soft upper 6656 bound has been set. 6657 """ 6658 return _pywrapcp.RoutingDimension_GetCumulVarSoftUpperBound(self, index) 6659 6660 def GetCumulVarSoftUpperBoundCoefficient(self, index): 6661 r""" 6662 Returns the cost coefficient of the soft upper bound of a cumul variable 6663 for a given variable index. If no soft upper bound has been set, 0 is 6664 returned. 6665 """ 6666 return _pywrapcp.RoutingDimension_GetCumulVarSoftUpperBoundCoefficient(self, index) 6667 6668 def SetCumulVarSoftLowerBound(self, index, lower_bound, coefficient): 6669 r""" 6670 Sets a soft lower bound to the cumul variable of a given variable index. 6671 If the value of the cumul variable is less than the bound, a cost 6672 proportional to the difference between this value and the bound is added 6673 to the cost function of the model: 6674 cumulVar > lower_bound -> cost = 0 6675 cumulVar <= lower_bound -> cost = coefficient * (lower_bound - 6676 cumulVar). 6677 This is also handy to model earliness costs when the dimension represents 6678 time. 6679 """ 6680 return _pywrapcp.RoutingDimension_SetCumulVarSoftLowerBound(self, index, lower_bound, coefficient) 6681 6682 def HasCumulVarSoftLowerBound(self, index): 6683 r""" 6684 Returns true if a soft lower bound has been set for a given variable 6685 index. 6686 """ 6687 return _pywrapcp.RoutingDimension_HasCumulVarSoftLowerBound(self, index) 6688 6689 def GetCumulVarSoftLowerBound(self, index): 6690 r""" 6691 Returns the soft lower bound of a cumul variable for a given variable 6692 index. The "hard" lower bound of the variable is returned if no soft lower 6693 bound has been set. 6694 """ 6695 return _pywrapcp.RoutingDimension_GetCumulVarSoftLowerBound(self, index) 6696 6697 def GetCumulVarSoftLowerBoundCoefficient(self, index): 6698 r""" 6699 Returns the cost coefficient of the soft lower bound of a cumul variable 6700 for a given variable index. If no soft lower bound has been set, 0 is 6701 returned. 6702 """ 6703 return _pywrapcp.RoutingDimension_GetCumulVarSoftLowerBoundCoefficient(self, index) 6704 6705 def SetBreakIntervalsOfVehicle(self, breaks, vehicle, node_visit_transits): 6706 r""" 6707 Sets the breaks for a given vehicle. Breaks are represented by 6708 IntervalVars. They may interrupt transits between nodes and increase 6709 the value of corresponding slack variables. 6710 A break may take place before the start of a vehicle, after the end of 6711 a vehicle, or during a travel i -> j. 6712 6713 In that case, the interval [break.Start(), break.End()) must be a subset 6714 of [CumulVar(i) + pre_travel(i, j), CumulVar(j) - post_travel(i, j)). In 6715 other words, a break may not overlap any node n's visit, given by 6716 [CumulVar(n) - post_travel(_, n), CumulVar(n) + pre_travel(n, _)). 6717 This formula considers post_travel(_, start) and pre_travel(end, _) to be 6718 0; pre_travel will never be called on any (_, start) and post_travel will 6719 never we called on any (end, _). If pre_travel_evaluator or 6720 post_travel_evaluator is -1, it will be taken as a function that always 6721 returns 0. 6722 Deprecated, sets pre_travel(i, j) = node_visit_transit[i]. 6723 """ 6724 return _pywrapcp.RoutingDimension_SetBreakIntervalsOfVehicle(self, breaks, vehicle, node_visit_transits) 6725 6726 def SetBreakDistanceDurationOfVehicle(self, distance, duration, vehicle): 6727 r""" 6728 With breaks supposed to be consecutive, this forces the distance between 6729 breaks of size at least minimum_break_duration to be at most distance. 6730 This supposes that the time until route start and after route end are 6731 infinite breaks. 6732 """ 6733 return _pywrapcp.RoutingDimension_SetBreakDistanceDurationOfVehicle(self, distance, duration, vehicle) 6734 6735 def InitializeBreaks(self): 6736 r""" 6737 Sets up vehicle_break_intervals_, vehicle_break_distance_duration_, 6738 pre_travel_evaluators and post_travel_evaluators. 6739 """ 6740 return _pywrapcp.RoutingDimension_InitializeBreaks(self) 6741 6742 def HasBreakConstraints(self): 6743 r"""Returns true if any break interval or break distance was defined.""" 6744 return _pywrapcp.RoutingDimension_HasBreakConstraints(self) 6745 6746 def GetPreTravelEvaluatorOfVehicle(self, vehicle): 6747 return _pywrapcp.RoutingDimension_GetPreTravelEvaluatorOfVehicle(self, vehicle) 6748 6749 def GetPostTravelEvaluatorOfVehicle(self, vehicle): 6750 return _pywrapcp.RoutingDimension_GetPostTravelEvaluatorOfVehicle(self, vehicle) 6751 6752 def base_dimension(self): 6753 r"""Returns the parent in the dependency tree if any or nullptr otherwise.""" 6754 return _pywrapcp.RoutingDimension_base_dimension(self) 6755 6756 def ShortestTransitionSlack(self, node): 6757 r""" 6758 It makes sense to use the function only for self-dependent dimension. 6759 For such dimensions the value of the slack of a node determines the 6760 transition cost of the next transit. Provided that 6761 1. cumul[node] is fixed, 6762 2. next[node] and next[next[node]] (if exists) are fixed, 6763 the value of slack[node] for which cumul[next[node]] + transit[next[node]] 6764 is minimized can be found in O(1) using this function. 6765 """ 6766 return _pywrapcp.RoutingDimension_ShortestTransitionSlack(self, node) 6767 6768 def index(self): 6769 r"""Returns the index of the dimension in the model.""" 6770 return _pywrapcp.RoutingDimension_index(self) 6771 6772 def name(self): 6773 r"""Returns the name of the dimension.""" 6774 return _pywrapcp.RoutingDimension_name(self) 6775 6776 def SetPickupToDeliveryLimitFunctionForPair(self, limit_function, pair_index): 6777 return _pywrapcp.RoutingDimension_SetPickupToDeliveryLimitFunctionForPair(self, limit_function, pair_index) 6778 6779 def HasPickupToDeliveryLimits(self): 6780 return _pywrapcp.RoutingDimension_HasPickupToDeliveryLimits(self) 6781 6782 def AddNodePrecedence(self, first_node, second_node, offset): 6783 return _pywrapcp.RoutingDimension_AddNodePrecedence(self, first_node, second_node, offset) 6784 6785 def GetSpanUpperBoundForVehicle(self, vehicle): 6786 return _pywrapcp.RoutingDimension_GetSpanUpperBoundForVehicle(self, vehicle) 6787 6788 def GetSpanCostCoefficientForVehicle(self, vehicle): 6789 return _pywrapcp.RoutingDimension_GetSpanCostCoefficientForVehicle(self, vehicle) 6790 6791 def GetSlackCostCoefficientForVehicle(self, vehicle): 6792 return _pywrapcp.RoutingDimension_GetSlackCostCoefficientForVehicle(self, vehicle) 6793 6794 def global_span_cost_coefficient(self): 6795 return _pywrapcp.RoutingDimension_global_span_cost_coefficient(self) 6796 6797 def GetGlobalOptimizerOffset(self): 6798 return _pywrapcp.RoutingDimension_GetGlobalOptimizerOffset(self) 6799 6800 def GetLocalOptimizerOffsetForVehicle(self, vehicle): 6801 return _pywrapcp.RoutingDimension_GetLocalOptimizerOffsetForVehicle(self, vehicle) 6802 6803 def SetSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle): 6804 r""" 6805 If the span of vehicle on this dimension is larger than bound, 6806 the cost will be increased by cost * (span - bound). 6807 """ 6808 return _pywrapcp.RoutingDimension_SetSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle) 6809 6810 def HasSoftSpanUpperBounds(self): 6811 return _pywrapcp.RoutingDimension_HasSoftSpanUpperBounds(self) 6812 6813 def GetSoftSpanUpperBoundForVehicle(self, vehicle): 6814 return _pywrapcp.RoutingDimension_GetSoftSpanUpperBoundForVehicle(self, vehicle) 6815 6816 def SetQuadraticCostSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle): 6817 r""" 6818 If the span of vehicle on this dimension is larger than bound, 6819 the cost will be increased by cost * (span - bound)^2. 6820 """ 6821 return _pywrapcp.RoutingDimension_SetQuadraticCostSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle) 6822 6823 def HasQuadraticCostSoftSpanUpperBounds(self): 6824 return _pywrapcp.RoutingDimension_HasQuadraticCostSoftSpanUpperBounds(self) 6825 6826 def GetQuadraticCostSoftSpanUpperBoundForVehicle(self, vehicle): 6827 return _pywrapcp.RoutingDimension_GetQuadraticCostSoftSpanUpperBoundForVehicle(self, vehicle) 6828 6829# Register RoutingDimension in _pywrapcp: 6830_pywrapcp.RoutingDimension_swigregister(RoutingDimension) 6831 6832def SolveModelWithSat(model, search_stats, search_parameters, initial_solution, solution): 6833 r""" 6834 Attempts to solve the model using the cp-sat solver. As of 5/2019, will 6835 solve the TSP corresponding to the model if it has a single vehicle. 6836 Therefore the resulting solution might not actually be feasible. Will return 6837 false if a solution could not be found. 6838 """ 6839 return _pywrapcp.SolveModelWithSat(model, search_stats, search_parameters, initial_solution, solution)
64class DefaultPhaseParameters(object): 65 r""" 66 This struct holds all parameters for the default search. 67 DefaultPhaseParameters is only used by Solver::MakeDefaultPhase 68 methods. Note this is for advanced users only. 69 """ 70 71 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 72 __repr__ = _swig_repr 73 CHOOSE_MAX_SUM_IMPACT = _pywrapcp.DefaultPhaseParameters_CHOOSE_MAX_SUM_IMPACT 74 CHOOSE_MAX_AVERAGE_IMPACT = _pywrapcp.DefaultPhaseParameters_CHOOSE_MAX_AVERAGE_IMPACT 75 CHOOSE_MAX_VALUE_IMPACT = _pywrapcp.DefaultPhaseParameters_CHOOSE_MAX_VALUE_IMPACT 76 SELECT_MIN_IMPACT = _pywrapcp.DefaultPhaseParameters_SELECT_MIN_IMPACT 77 SELECT_MAX_IMPACT = _pywrapcp.DefaultPhaseParameters_SELECT_MAX_IMPACT 78 NONE = _pywrapcp.DefaultPhaseParameters_NONE 79 NORMAL = _pywrapcp.DefaultPhaseParameters_NORMAL 80 VERBOSE = _pywrapcp.DefaultPhaseParameters_VERBOSE 81 var_selection_schema = property(_pywrapcp.DefaultPhaseParameters_var_selection_schema_get, _pywrapcp.DefaultPhaseParameters_var_selection_schema_set, doc=r""" 82 This parameter describes how the next variable to instantiate 83 will be chosen. 84 """) 85 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.""") 86 initialization_splits = property(_pywrapcp.DefaultPhaseParameters_initialization_splits_get, _pywrapcp.DefaultPhaseParameters_initialization_splits_set, doc=r""" 87 Maximum number of intervals that the initialization of impacts will scan 88 per variable. 89 """) 90 run_all_heuristics = property(_pywrapcp.DefaultPhaseParameters_run_all_heuristics_get, _pywrapcp.DefaultPhaseParameters_run_all_heuristics_set, doc=r""" 91 The default phase will run heuristics periodically. This parameter 92 indicates if we should run all heuristics, or a randomly selected 93 one. 94 """) 95 heuristic_period = property(_pywrapcp.DefaultPhaseParameters_heuristic_period_get, _pywrapcp.DefaultPhaseParameters_heuristic_period_set, doc=r""" 96 The distance in nodes between each run of the heuristics. A 97 negative or null value will mean that we will not run heuristics 98 at all. 99 """) 100 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.""") 101 persistent_impact = property(_pywrapcp.DefaultPhaseParameters_persistent_impact_get, _pywrapcp.DefaultPhaseParameters_persistent_impact_set, doc=r""" 102 Whether to keep the impact from the first search for other searches, 103 or to recompute the impact for each new search. 104 """) 105 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.""") 106 display_level = property(_pywrapcp.DefaultPhaseParameters_display_level_get, _pywrapcp.DefaultPhaseParameters_display_level_set, doc=r""" 107 This represents the amount of information displayed by the default search. 108 NONE means no display, VERBOSE means extra information. 109 """) 110 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.""") 111 112 def __init__(self): 113 _pywrapcp.DefaultPhaseParameters_swiginit(self, _pywrapcp.new_DefaultPhaseParameters()) 114 __swig_destroy__ = _pywrapcp.delete_DefaultPhaseParameters
This struct holds all parameters for the default search. DefaultPhaseParameters is only used by Solver::MakeDefaultPhase methods. Note this is for advanced users only.
71 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Maximum number of intervals that the initialization of impacts will scan per variable.
The default phase will run heuristics periodically. This parameter indicates if we should run all heuristics, or a randomly selected one.
The distance in nodes between each run of the heuristics. A negative or null value will mean that we will not run heuristics at all.
Whether to keep the impact from the first search for other searches, or to recompute the impact for each new search.
118class Solver(object): 119 r""" 120 Solver Class. 121 A solver represents the main computation engine. It implements the 122 entire range of Constraint Programming protocols: 123 - Reversibility 124 - Propagation 125 - Search 126 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. 134 135 For the time being, Solver is neither MT_SAFE nor MT_HOT. 136 """ 137 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 145 r""" 146 Select the first unbound variable. 147 Variables are considered in the order of the vector of IntVars used 148 to create the selector. 149 """ 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 153 r""" 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 157 value. 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. 160 """ 161 CHOOSE_MIN_SIZE_HIGHEST_MIN = _pywrapcp.Solver_CHOOSE_MIN_SIZE_HIGHEST_MIN 162 r""" 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 166 value. 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. 169 """ 170 CHOOSE_MIN_SIZE_LOWEST_MAX = _pywrapcp.Solver_CHOOSE_MIN_SIZE_LOWEST_MAX 171 r""" 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 175 value. 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. 178 """ 179 CHOOSE_MIN_SIZE_HIGHEST_MAX = _pywrapcp.Solver_CHOOSE_MIN_SIZE_HIGHEST_MAX 180 r""" 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 184 value. 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. 187 """ 188 CHOOSE_LOWEST_MIN = _pywrapcp.Solver_CHOOSE_LOWEST_MIN 189 r""" 190 Among unbound variables, select the variable with the smallest minimal 191 value. 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. 194 """ 195 CHOOSE_HIGHEST_MAX = _pywrapcp.Solver_CHOOSE_HIGHEST_MAX 196 r""" 197 Among unbound variables, select the variable with the highest maximal 198 value. 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. 201 """ 202 CHOOSE_MIN_SIZE = _pywrapcp.Solver_CHOOSE_MIN_SIZE 203 r""" 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. 207 """ 208 CHOOSE_MAX_SIZE = _pywrapcp.Solver_CHOOSE_MAX_SIZE 209 r""" 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. 213 """ 214 CHOOSE_MAX_REGRET_ON_MIN = _pywrapcp.Solver_CHOOSE_MAX_REGRET_ON_MIN 215 r""" 216 Among unbound variables, select the variable with the largest 217 gap between the first and the second values of the domain. 218 """ 219 CHOOSE_PATH = _pywrapcp.Solver_CHOOSE_PATH 220 r""" 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. 223 """ 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 235 r""" 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. 239 """ 240 SPLIT_LOWER_HALF = _pywrapcp.Solver_SPLIT_LOWER_HALF 241 r""" 242 Split the domain in two around the center, and choose the lower 243 part first. 244 """ 245 SPLIT_UPPER_HALF = _pywrapcp.Solver_SPLIT_UPPER_HALF 246 r""" 247 Split the domain in two around the center, and choose the lower 248 part first. 249 """ 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 259 r""" 260 Selects the variable with the lowest starting time of all variables, 261 and fixes its starting time to this lowest value. 262 """ 263 INTERVAL_SET_TIMES_BACKWARD = _pywrapcp.Solver_INTERVAL_SET_TIMES_BACKWARD 264 r""" 265 Selects the variable with the highest ending time of all variables, 266 and fixes the ending time to this highest values. 267 """ 268 TWOOPT = _pywrapcp.Solver_TWOOPT 269 r""" 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 272 two-optimal. 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 275 be moved): 276 277 .. code-block:: c++ 278 279 1 -> [3 -> 2] -> 4 -> 5 280 1 -> [4 -> 3 -> 2] -> 5 281 1 -> 2 -> [4 -> 3] -> 5 282 """ 283 OROPT = _pywrapcp.Solver_OROPT 284 r""" 285 Relocate: OROPT and RELOCATE. 286 Operator which moves a sub-chain of a path to another position; the 287 specified chain length is the fixed length of the chains being moved. 288 When this length is 1, the operator simply moves a node to another 289 position. 290 Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5, for a chain 291 length of 2 (where (1, 5) are first and last nodes of the path and can 292 therefore not be moved): 293 294 .. code-block:: c++ 295 296 1 -> 4 -> [2 -> 3] -> 5 297 1 -> [3 -> 4] -> 2 -> 5 298 Using Relocate with chain lengths of 1, 2 and 3 together is equivalent 299 to the OrOpt operator on a path. The OrOpt operator is a limited 300 version of 3Opt (breaks 3 arcs on a path). 301 """ 302 RELOCATE = _pywrapcp.Solver_RELOCATE 303 r"""Relocate neighborhood with length of 1 (see OROPT comment).""" 304 EXCHANGE = _pywrapcp.Solver_EXCHANGE 305 r""" 306 Operator which exchanges the positions of two nodes. 307 Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5 308 (where (1, 5) are first and last nodes of the path and can therefore not 309 be moved): 310 311 .. code-block:: c++ 312 313 1 -> [3] -> [2] -> 4 -> 5 314 1 -> [4] -> 3 -> [2] -> 5 315 1 -> 2 -> [4] -> [3] -> 5 316 """ 317 CROSS = _pywrapcp.Solver_CROSS 318 r""" 319 Operator which cross exchanges the starting chains of 2 paths, including 320 exchanging the whole paths. 321 First and last nodes are not moved. 322 Possible neighbors for the paths 1 -> 2 -> 3 -> 4 -> 5 and 6 -> 7 -> 8 323 (where (1, 5) and (6, 8) are first and last nodes of the paths and can 324 therefore not be moved): 325 326 .. code-block:: c++ 327 328 1 -> [7] -> 3 -> 4 -> 5 6 -> [2] -> 8 329 1 -> [7] -> 4 -> 5 6 -> [2 -> 3] -> 8 330 1 -> [7] -> 5 6 -> [2 -> 3 -> 4] -> 8 331 """ 332 MAKEACTIVE = _pywrapcp.Solver_MAKEACTIVE 333 r""" 334 Operator which inserts an inactive node into a path. 335 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive 336 (where 1 and 4 are first and last nodes of the path) are: 337 338 .. code-block:: c++ 339 340 1 -> [5] -> 2 -> 3 -> 4 341 1 -> 2 -> [5] -> 3 -> 4 342 1 -> 2 -> 3 -> [5] -> 4 343 """ 344 MAKEINACTIVE = _pywrapcp.Solver_MAKEINACTIVE 345 r""" 346 Operator which makes path nodes inactive. 347 Possible neighbors for the path 1 -> 2 -> 3 -> 4 (where 1 and 4 are 348 first and last nodes of the path) are: 349 350 .. code-block:: c++ 351 352 1 -> 3 -> 4 with 2 inactive 353 1 -> 2 -> 4 with 3 inactive 354 """ 355 MAKECHAININACTIVE = _pywrapcp.Solver_MAKECHAININACTIVE 356 r""" 357 Operator which makes a "chain" of path nodes inactive. 358 Possible neighbors for the path 1 -> 2 -> 3 -> 4 (where 1 and 4 are 359 first and last nodes of the path) are: 360 361 .. code-block:: c++ 362 363 1 -> 3 -> 4 with 2 inactive 364 1 -> 2 -> 4 with 3 inactive 365 1 -> 4 with 2 and 3 inactive 366 """ 367 SWAPACTIVE = _pywrapcp.Solver_SWAPACTIVE 368 r""" 369 Operator which replaces an active node by an inactive one. 370 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive 371 (where 1 and 4 are first and last nodes of the path) are: 372 373 .. code-block:: c++ 374 375 1 -> [5] -> 3 -> 4 with 2 inactive 376 1 -> 2 -> [5] -> 4 with 3 inactive 377 """ 378 EXTENDEDSWAPACTIVE = _pywrapcp.Solver_EXTENDEDSWAPACTIVE 379 r""" 380 Operator which makes an inactive node active and an active one inactive. 381 It is similar to SwapActiveOperator except that it tries to insert the 382 inactive node in all possible positions instead of just the position of 383 the node made inactive. 384 Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive 385 (where 1 and 4 are first and last nodes of the path) are: 386 387 .. code-block:: c++ 388 389 1 -> [5] -> 3 -> 4 with 2 inactive 390 1 -> 3 -> [5] -> 4 with 2 inactive 391 1 -> [5] -> 2 -> 4 with 3 inactive 392 1 -> 2 -> [5] -> 4 with 3 inactive 393 """ 394 PATHLNS = _pywrapcp.Solver_PATHLNS 395 r""" 396 Operator which relaxes two sub-chains of three consecutive arcs each. 397 Each sub-chain is defined by a start node and the next three arcs. Those 398 six arcs are relaxed to build a new neighbor. 399 PATHLNS explores all possible pairs of starting nodes and so defines 400 n^2 neighbors, n being the number of nodes. 401 Note that the two sub-chains can be part of the same path; they even may 402 overlap. 403 """ 404 FULLPATHLNS = _pywrapcp.Solver_FULLPATHLNS 405 r""" 406 Operator which relaxes one entire path and all inactive nodes, thus 407 defining num_paths neighbors. 408 """ 409 UNACTIVELNS = _pywrapcp.Solver_UNACTIVELNS 410 r""" 411 Operator which relaxes all inactive nodes and one sub-chain of six 412 consecutive arcs. That way the path can be improved by inserting 413 inactive nodes or swapping arcs. 414 """ 415 INCREMENT = _pywrapcp.Solver_INCREMENT 416 r""" 417 Operator which defines one neighbor per variable. Each neighbor tries to 418 increment by one the value of the corresponding variable. When a new 419 solution is found the neighborhood is rebuilt from scratch, i.e., tries 420 to increment values in the variable order. 421 Consider for instance variables x and y. x is incremented one by one to 422 its max, and when it is not possible to increment x anymore, y is 423 incremented once. If this is a solution, then next neighbor tries to 424 increment x. 425 """ 426 DECREMENT = _pywrapcp.Solver_DECREMENT 427 r""" 428 Operator which defines a neighborhood to decrement values. 429 The behavior is the same as INCREMENT, except values are decremented 430 instead of incremented. 431 """ 432 SIMPLELNS = _pywrapcp.Solver_SIMPLELNS 433 r""" 434 Operator which defines one neighbor per variable. Each neighbor relaxes 435 one variable. 436 When a new solution is found the neighborhood is rebuilt from scratch. 437 Consider for instance variables x and y. First x is relaxed and the 438 solver is looking for the best possible solution (with only x relaxed). 439 Then y is relaxed, and the solver is looking for a new solution. 440 If a new solution is found, then the next variable to be relaxed is x. 441 """ 442 GE = _pywrapcp.Solver_GE 443 r"""Move is accepted when the current objective value >= objective.Min.""" 444 LE = _pywrapcp.Solver_LE 445 r"""Move is accepted when the current objective value <= objective.Max.""" 446 EQ = _pywrapcp.Solver_EQ 447 r""" 448 Move is accepted when the current objective value is in the interval 449 objective.Min .. objective.Max. 450 """ 451 DELAYED_PRIORITY = _pywrapcp.Solver_DELAYED_PRIORITY 452 r""" 453 DELAYED_PRIORITY is the lowest priority: Demons will be processed after 454 VAR_PRIORITY and NORMAL_PRIORITY demons. 455 """ 456 VAR_PRIORITY = _pywrapcp.Solver_VAR_PRIORITY 457 r"""VAR_PRIORITY is between DELAYED_PRIORITY and NORMAL_PRIORITY.""" 458 NORMAL_PRIORITY = _pywrapcp.Solver_NORMAL_PRIORITY 459 r"""NORMAL_PRIORITY is the highest priority: Demons will be processed first.""" 460 461 def __init__(self, *args): 462 r"""Solver API""" 463 _pywrapcp.Solver_swiginit(self, _pywrapcp.new_Solver(*args)) 464 465 self.__python_constraints = [] 466 467 468 469 __swig_destroy__ = _pywrapcp.delete_Solver 470 471 def Parameters(self): 472 r"""Stored Parameters.""" 473 return _pywrapcp.Solver_Parameters(self) 474 475 @staticmethod 476 def DefaultSolverParameters(): 477 r"""Create a ConstraintSolverParameters proto with all the default values.""" 478 return _pywrapcp.Solver_DefaultSolverParameters() 479 480 def AddConstraint(self, c): 481 r""" 482 Adds the constraint 'c' to the model. 483 484 After calling this method, and until there is a backtrack that undoes the 485 addition, any assignment of variables to values must satisfy the given 486 constraint in order to be considered feasible. There are two fairly 487 different use cases: 488 489 - the most common use case is modeling: the given constraint is really 490 part of the problem that the user is trying to solve. In this use case, 491 AddConstraint is called outside of search (i.e., with state() == 492 OUTSIDE_SEARCH). Most users should only use AddConstraint in this 493 way. In this case, the constraint will belong to the model forever: it 494 cannot be removed by backtracking. 495 496 - a rarer use case is that 'c' is not a real constraint of the model. It 497 may be a constraint generated by a branching decision (a constraint whose 498 goal is to restrict the search space), a symmetry breaking constraint (a 499 constraint that does restrict the search space, but in a way that cannot 500 have an impact on the quality of the solutions in the subtree), or an 501 inferred constraint that, while having no semantic value to the model (it 502 does not restrict the set of solutions), is worth having because we 503 believe it may strengthen the propagation. In these cases, it happens 504 that the constraint is added during the search (i.e., with state() == 505 IN_SEARCH or state() == IN_ROOT_NODE). When a constraint is 506 added during a search, it applies only to the subtree of the search tree 507 rooted at the current node, and will be automatically removed by 508 backtracking. 509 510 This method does not take ownership of the constraint. If the constraint 511 has been created by any factory method (Solver::MakeXXX), it will 512 automatically be deleted. However, power users who implement their own 513 constraints should do: solver.AddConstraint(solver.RevAlloc(new 514 MyConstraint(...)); 515 """ 516 return _pywrapcp.Solver_AddConstraint(self, c) 517 518 def Solve(self, *args): 519 r""" 520 Solves the problem using the given DecisionBuilder and returns true if a 521 solution was found and accepted. 522 523 These methods are the ones most users should use to search for a solution. 524 Note that the definition of 'solution' is subtle. A solution here is 525 defined as a leaf of the search tree with respect to the given decision 526 builder for which there is no failure. What this means is that, contrary 527 to intuition, a solution may not have all variables of the model bound. 528 It is the responsibility of the decision builder to keep returning 529 decisions until all variables are indeed bound. The most extreme 530 counterexample is calling Solve with a trivial decision builder whose 531 Next() method always returns nullptr. In this case, Solve immediately 532 returns 'true', since not assigning any variable to any value is a 533 solution, unless the root node propagation discovers that the model is 534 infeasible. 535 536 This function must be called either from outside of search, 537 or from within the Next() method of a decision builder. 538 539 Solve will terminate whenever any of the following event arise: 540 A search monitor asks the solver to terminate the search by calling 541 solver()->FinishCurrentSearch(). 542 A solution is found that is accepted by all search monitors, and none of 543 the search monitors decides to search for another one. 544 545 Upon search termination, there will be a series of backtracks all the way 546 to the top level. This means that a user cannot expect to inspect the 547 solution by querying variables after a call to Solve(): all the 548 information will be lost. In order to do something with the solution, the 549 user must either: 550 551 Use a search monitor that can process such a leaf. See, in particular, 552 the SolutionCollector class. 553 Do not use Solve. Instead, use the more fine-grained approach using 554 methods NewSearch(...), NextSolution(), and EndSearch(). 555 556 :type db: :py:class:`DecisionBuilder` 557 :param db: The decision builder that will generate the search tree. 558 :type monitors: std::vector< operations_research::SearchMonitor * > 559 :param monitors: A vector of search monitors that will be notified of 560 various events during the search. In their reaction to these events, such 561 monitors may influence the search. 562 """ 563 return _pywrapcp.Solver_Solve(self, *args) 564 565 def NewSearch(self, *args): 566 r""" 567 Decomposed search. 568 The code for a top level search should look like 569 solver->NewSearch(db); 570 while (solver->NextSolution()) { 571 .. use the current solution 572 } 573 solver()->EndSearch(); 574 """ 575 return _pywrapcp.Solver_NewSearch(self, *args) 576 577 def NextSolution(self): 578 return _pywrapcp.Solver_NextSolution(self) 579 580 def RestartSearch(self): 581 return _pywrapcp.Solver_RestartSearch(self) 582 583 def EndSearch(self): 584 return _pywrapcp.Solver_EndSearch(self) 585 586 def SolveAndCommit(self, *args): 587 r""" 588 SolveAndCommit using a decision builder and up to three 589 search monitors, usually one for the objective, one for the limits 590 and one to collect solutions. 591 592 The difference between a SolveAndCommit() and a Solve() method 593 call is the fact that SolveAndCommit will not backtrack all 594 modifications at the end of the search. This method is only 595 usable during the Next() method of a decision builder. 596 """ 597 return _pywrapcp.Solver_SolveAndCommit(self, *args) 598 599 def CheckAssignment(self, solution): 600 r"""Checks whether the given assignment satisfies all relevant constraints.""" 601 return _pywrapcp.Solver_CheckAssignment(self, solution) 602 603 def CheckConstraint(self, ct): 604 r""" 605 Checks whether adding this constraint will lead to an immediate 606 failure. It will return false if the model is already inconsistent, or if 607 adding the constraint makes it inconsistent. 608 """ 609 return _pywrapcp.Solver_CheckConstraint(self, ct) 610 611 def Fail(self): 612 r"""Abandon the current branch in the search tree. A backtrack will follow.""" 613 return _pywrapcp.Solver_Fail(self) 614 615 @staticmethod 616 def MemoryUsage(): 617 r"""Current memory usage in bytes""" 618 return _pywrapcp.Solver_MemoryUsage() 619 620 def WallTime(self): 621 r""" 622 Deprecated: Use Now() instead. 623 Time elapsed, in ms since the creation of the solver. 624 """ 625 return _pywrapcp.Solver_WallTime(self) 626 627 def Branches(self): 628 r"""The number of branches explored since the creation of the solver.""" 629 return _pywrapcp.Solver_Branches(self) 630 631 def Solutions(self): 632 r"""The number of solutions found since the start of the search.""" 633 return _pywrapcp.Solver_Solutions(self) 634 635 def Failures(self): 636 r"""The number of failures encountered since the creation of the solver.""" 637 return _pywrapcp.Solver_Failures(self) 638 639 def AcceptedNeighbors(self): 640 r"""The number of accepted neighbors.""" 641 return _pywrapcp.Solver_AcceptedNeighbors(self) 642 643 def Stamp(self): 644 r""" 645 The stamp indicates how many moves in the search tree we have performed. 646 It is useful to detect if we need to update same lazy structures. 647 """ 648 return _pywrapcp.Solver_Stamp(self) 649 650 def FailStamp(self): 651 r"""The fail_stamp() is incremented after each backtrack.""" 652 return _pywrapcp.Solver_FailStamp(self) 653 654 def IntVar(self, *args): 655 r""" 656 *Overload 1:* 657 MakeIntVar will create the best range based int var for the bounds given. 658 659 | 660 661 *Overload 2:* 662 MakeIntVar will create a variable with the given sparse domain. 663 664 | 665 666 *Overload 3:* 667 MakeIntVar will create a variable with the given sparse domain. 668 669 | 670 671 *Overload 4:* 672 MakeIntVar will create the best range based int var for the bounds given. 673 674 | 675 676 *Overload 5:* 677 MakeIntVar will create a variable with the given sparse domain. 678 679 | 680 681 *Overload 6:* 682 MakeIntVar will create a variable with the given sparse domain. 683 """ 684 return _pywrapcp.Solver_IntVar(self, *args) 685 686 def BoolVar(self, *args): 687 r""" 688 *Overload 1:* 689 MakeBoolVar will create a variable with a {0, 1} domain. 690 691 | 692 693 *Overload 2:* 694 MakeBoolVar will create a variable with a {0, 1} domain. 695 """ 696 return _pywrapcp.Solver_BoolVar(self, *args) 697 698 def IntConst(self, *args): 699 r""" 700 *Overload 1:* 701 IntConst will create a constant expression. 702 703 | 704 705 *Overload 2:* 706 IntConst will create a constant expression. 707 """ 708 return _pywrapcp.Solver_IntConst(self, *args) 709 710 def Sum(self, vars): 711 r"""sum of all vars.""" 712 return _pywrapcp.Solver_Sum(self, vars) 713 714 def ScalProd(self, *args): 715 r""" 716 *Overload 1:* 717 scalar product 718 719 | 720 721 *Overload 2:* 722 scalar product 723 """ 724 return _pywrapcp.Solver_ScalProd(self, *args) 725 726 def MonotonicElement(self, values, increasing, index): 727 r""" 728 Function based element. The constraint takes ownership of the 729 callback. The callback must be monotonic. It must be able to 730 cope with any possible value in the domain of 'index' 731 (potentially negative ones too). Furtermore, monotonicity is not 732 checked. Thus giving a non-monotonic function, or specifying an 733 incorrect increasing parameter will result in undefined behavior. 734 """ 735 return _pywrapcp.Solver_MonotonicElement(self, values, increasing, index) 736 737 def Element(self, *args): 738 r""" 739 *Overload 1:* 740 values[index] 741 742 | 743 744 *Overload 2:* 745 values[index] 746 747 | 748 749 *Overload 3:* 750 Function-based element. The constraint takes ownership of the 751 callback. The callback must be able to cope with any possible 752 value in the domain of 'index' (potentially negative ones too). 753 754 | 755 756 *Overload 4:* 757 2D version of function-based element expression, values(expr1, expr2). 758 759 | 760 761 *Overload 5:* 762 vars[expr] 763 """ 764 return _pywrapcp.Solver_Element(self, *args) 765 766 def IndexExpression(self, vars, value): 767 r""" 768 Returns the expression expr such that vars[expr] == value. 769 It assumes that vars are all different. 770 """ 771 return _pywrapcp.Solver_IndexExpression(self, vars, value) 772 773 def Min(self, *args): 774 r""" 775 *Overload 1:* 776 std::min(vars) 777 778 | 779 780 *Overload 2:* 781 std::min (left, right) 782 783 | 784 785 *Overload 3:* 786 std::min(expr, value) 787 788 | 789 790 *Overload 4:* 791 std::min(expr, value) 792 """ 793 return _pywrapcp.Solver_Min(self, *args) 794 795 def Max(self, *args): 796 r""" 797 *Overload 1:* 798 std::max(vars) 799 800 | 801 802 *Overload 2:* 803 std::max(left, right) 804 805 | 806 807 *Overload 3:* 808 std::max(expr, value) 809 810 | 811 812 *Overload 4:* 813 std::max(expr, value) 814 """ 815 return _pywrapcp.Solver_Max(self, *args) 816 817 def ConvexPiecewiseExpr(self, expr, early_cost, early_date, late_date, late_cost): 818 r"""Convex piecewise function.""" 819 return _pywrapcp.Solver_ConvexPiecewiseExpr(self, expr, early_cost, early_date, late_date, late_cost) 820 821 def SemiContinuousExpr(self, expr, fixed_charge, step): 822 r""" 823 Semi continuous Expression (x <= 0 -> f(x) = 0; x > 0 -> f(x) = ax + b) 824 a >= 0 and b >= 0 825 """ 826 return _pywrapcp.Solver_SemiContinuousExpr(self, expr, fixed_charge, step) 827 828 def ConditionalExpression(self, condition, expr, unperformed_value): 829 r"""Conditional Expr condition ? expr : unperformed_value""" 830 return _pywrapcp.Solver_ConditionalExpression(self, condition, expr, unperformed_value) 831 832 def TrueConstraint(self): 833 r"""This constraint always succeeds.""" 834 return _pywrapcp.Solver_TrueConstraint(self) 835 836 def FalseConstraint(self, *args): 837 r"""This constraint always fails.""" 838 return _pywrapcp.Solver_FalseConstraint(self, *args) 839 840 def IsEqualCstCt(self, var, value, boolvar): 841 r"""boolvar == (var == value)""" 842 return _pywrapcp.Solver_IsEqualCstCt(self, var, value, boolvar) 843 844 def IsEqualCstVar(self, var, value): 845 r"""status var of (var == value)""" 846 return _pywrapcp.Solver_IsEqualCstVar(self, var, value) 847 848 def IsEqualCt(self, v1, v2, b): 849 r"""b == (v1 == v2)""" 850 return _pywrapcp.Solver_IsEqualCt(self, v1, v2, b) 851 852 def IsEqualVar(self, v1, v2): 853 r"""status var of (v1 == v2)""" 854 return _pywrapcp.Solver_IsEqualVar(self, v1, v2) 855 856 def IsDifferentCstCt(self, var, value, boolvar): 857 r"""boolvar == (var != value)""" 858 return _pywrapcp.Solver_IsDifferentCstCt(self, var, value, boolvar) 859 860 def IsDifferentCstVar(self, var, value): 861 r"""status var of (var != value)""" 862 return _pywrapcp.Solver_IsDifferentCstVar(self, var, value) 863 864 def IsDifferentVar(self, v1, v2): 865 r"""status var of (v1 != v2)""" 866 return _pywrapcp.Solver_IsDifferentVar(self, v1, v2) 867 868 def IsDifferentCt(self, v1, v2, b): 869 r"""b == (v1 != v2)""" 870 return _pywrapcp.Solver_IsDifferentCt(self, v1, v2, b) 871 872 def IsLessOrEqualCstCt(self, var, value, boolvar): 873 r"""boolvar == (var <= value)""" 874 return _pywrapcp.Solver_IsLessOrEqualCstCt(self, var, value, boolvar) 875 876 def IsLessOrEqualCstVar(self, var, value): 877 r"""status var of (var <= value)""" 878 return _pywrapcp.Solver_IsLessOrEqualCstVar(self, var, value) 879 880 def IsLessOrEqualVar(self, left, right): 881 r"""status var of (left <= right)""" 882 return _pywrapcp.Solver_IsLessOrEqualVar(self, left, right) 883 884 def IsLessOrEqualCt(self, left, right, b): 885 r"""b == (left <= right)""" 886 return _pywrapcp.Solver_IsLessOrEqualCt(self, left, right, b) 887 888 def IsGreaterOrEqualCstCt(self, var, value, boolvar): 889 r"""boolvar == (var >= value)""" 890 return _pywrapcp.Solver_IsGreaterOrEqualCstCt(self, var, value, boolvar) 891 892 def IsGreaterOrEqualCstVar(self, var, value): 893 r"""status var of (var >= value)""" 894 return _pywrapcp.Solver_IsGreaterOrEqualCstVar(self, var, value) 895 896 def IsGreaterOrEqualVar(self, left, right): 897 r"""status var of (left >= right)""" 898 return _pywrapcp.Solver_IsGreaterOrEqualVar(self, left, right) 899 900 def IsGreaterOrEqualCt(self, left, right, b): 901 r"""b == (left >= right)""" 902 return _pywrapcp.Solver_IsGreaterOrEqualCt(self, left, right, b) 903 904 def IsGreaterCstCt(self, v, c, b): 905 r"""b == (v > c)""" 906 return _pywrapcp.Solver_IsGreaterCstCt(self, v, c, b) 907 908 def IsGreaterCstVar(self, var, value): 909 r"""status var of (var > value)""" 910 return _pywrapcp.Solver_IsGreaterCstVar(self, var, value) 911 912 def IsGreaterVar(self, left, right): 913 r"""status var of (left > right)""" 914 return _pywrapcp.Solver_IsGreaterVar(self, left, right) 915 916 def IsGreaterCt(self, left, right, b): 917 r"""b == (left > right)""" 918 return _pywrapcp.Solver_IsGreaterCt(self, left, right, b) 919 920 def IsLessCstCt(self, v, c, b): 921 r"""b == (v < c)""" 922 return _pywrapcp.Solver_IsLessCstCt(self, v, c, b) 923 924 def IsLessCstVar(self, var, value): 925 r"""status var of (var < value)""" 926 return _pywrapcp.Solver_IsLessCstVar(self, var, value) 927 928 def IsLessVar(self, left, right): 929 r"""status var of (left < right)""" 930 return _pywrapcp.Solver_IsLessVar(self, left, right) 931 932 def IsLessCt(self, left, right, b): 933 r"""b == (left < right)""" 934 return _pywrapcp.Solver_IsLessCt(self, left, right, b) 935 936 def SumLessOrEqual(self, vars, cst): 937 r"""Variation on arrays.""" 938 return _pywrapcp.Solver_SumLessOrEqual(self, vars, cst) 939 940 def SumGreaterOrEqual(self, vars, cst): 941 return _pywrapcp.Solver_SumGreaterOrEqual(self, vars, cst) 942 943 def SumEquality(self, *args): 944 return _pywrapcp.Solver_SumEquality(self, *args) 945 946 def ScalProdEquality(self, *args): 947 return _pywrapcp.Solver_ScalProdEquality(self, *args) 948 949 def ScalProdGreaterOrEqual(self, *args): 950 return _pywrapcp.Solver_ScalProdGreaterOrEqual(self, *args) 951 952 def ScalProdLessOrEqual(self, *args): 953 return _pywrapcp.Solver_ScalProdLessOrEqual(self, *args) 954 955 def MinEquality(self, vars, min_var): 956 return _pywrapcp.Solver_MinEquality(self, vars, min_var) 957 958 def MaxEquality(self, vars, max_var): 959 return _pywrapcp.Solver_MaxEquality(self, vars, max_var) 960 961 def ElementEquality(self, *args): 962 return _pywrapcp.Solver_ElementEquality(self, *args) 963 964 def AbsEquality(self, var, abs_var): 965 r"""Creates the constraint abs(var) == abs_var.""" 966 return _pywrapcp.Solver_AbsEquality(self, var, abs_var) 967 968 def IndexOfConstraint(self, vars, index, target): 969 r""" 970 This constraint is a special case of the element constraint with 971 an array of integer variables, where the variables are all 972 different and the index variable is constrained such that 973 vars[index] == target. 974 """ 975 return _pywrapcp.Solver_IndexOfConstraint(self, vars, index, target) 976 977 def ConstraintInitialPropagateCallback(self, ct): 978 r""" 979 This method is a specialized case of the MakeConstraintDemon 980 method to call the InitiatePropagate of the constraint 'ct'. 981 """ 982 return _pywrapcp.Solver_ConstraintInitialPropagateCallback(self, ct) 983 984 def DelayedConstraintInitialPropagateCallback(self, ct): 985 r""" 986 This method is a specialized case of the MakeConstraintDemon 987 method to call the InitiatePropagate of the constraint 'ct' with 988 low priority. 989 """ 990 return _pywrapcp.Solver_DelayedConstraintInitialPropagateCallback(self, ct) 991 992 def ClosureDemon(self, closure): 993 r"""Creates a demon from a closure.""" 994 return _pywrapcp.Solver_ClosureDemon(self, closure) 995 996 def BetweenCt(self, expr, l, u): 997 r"""(l <= expr <= u)""" 998 return _pywrapcp.Solver_BetweenCt(self, expr, l, u) 999 1000 def IsBetweenCt(self, expr, l, u, b): 1001 r"""b == (l <= expr <= u)""" 1002 return _pywrapcp.Solver_IsBetweenCt(self, expr, l, u, b) 1003 1004 def IsBetweenVar(self, v, l, u): 1005 return _pywrapcp.Solver_IsBetweenVar(self, v, l, u) 1006 1007 def MemberCt(self, *args): 1008 r""" 1009 expr in set. Propagation is lazy, i.e. this constraint does not 1010 creates holes in the domain of the variable. 1011 """ 1012 return _pywrapcp.Solver_MemberCt(self, *args) 1013 1014 def NotMemberCt(self, *args): 1015 r""" 1016 *Overload 1:* 1017 expr not in set. 1018 1019 | 1020 1021 *Overload 2:* 1022 expr should not be in the list of forbidden intervals [start[i]..end[i]]. 1023 1024 | 1025 1026 *Overload 3:* 1027 expr should not be in the list of forbidden intervals [start[i]..end[i]]. 1028 """ 1029 return _pywrapcp.Solver_NotMemberCt(self, *args) 1030 1031 def IsMemberCt(self, *args): 1032 r"""boolvar == (expr in set)""" 1033 return _pywrapcp.Solver_IsMemberCt(self, *args) 1034 1035 def IsMemberVar(self, *args): 1036 return _pywrapcp.Solver_IsMemberVar(self, *args) 1037 1038 def Count(self, *args): 1039 r""" 1040 *Overload 1:* 1041 |{i | vars[i] == value}| == max_count 1042 1043 | 1044 1045 *Overload 2:* 1046 |{i | vars[i] == value}| == max_count 1047 """ 1048 return _pywrapcp.Solver_Count(self, *args) 1049 1050 def Distribute(self, *args): 1051 r""" 1052 *Overload 1:* 1053 Aggregated version of count: |{i | v[i] == values[j]}| == cards[j] 1054 1055 | 1056 1057 *Overload 2:* 1058 Aggregated version of count: |{i | v[i] == values[j]}| == cards[j] 1059 1060 | 1061 1062 *Overload 3:* 1063 Aggregated version of count: |{i | v[i] == j}| == cards[j] 1064 1065 | 1066 1067 *Overload 4:* 1068 Aggregated version of count with bounded cardinalities: 1069 forall j in 0 .. card_size - 1: card_min <= |{i | v[i] == j}| <= card_max 1070 1071 | 1072 1073 *Overload 5:* 1074 Aggregated version of count with bounded cardinalities: 1075 forall j in 0 .. card_size - 1: 1076 card_min[j] <= |{i | v[i] == j}| <= card_max[j] 1077 1078 | 1079 1080 *Overload 6:* 1081 Aggregated version of count with bounded cardinalities: 1082 forall j in 0 .. card_size - 1: 1083 card_min[j] <= |{i | v[i] == j}| <= card_max[j] 1084 1085 | 1086 1087 *Overload 7:* 1088 Aggregated version of count with bounded cardinalities: 1089 forall j in 0 .. card_size - 1: 1090 card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j] 1091 1092 | 1093 1094 *Overload 8:* 1095 Aggregated version of count with bounded cardinalities: 1096 forall j in 0 .. card_size - 1: 1097 card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j] 1098 """ 1099 return _pywrapcp.Solver_Distribute(self, *args) 1100 1101 def Deviation(self, vars, deviation_var, total_sum): 1102 r""" 1103 Deviation constraint: 1104 sum_i |n * vars[i] - total_sum| <= deviation_var and 1105 sum_i vars[i] == total_sum 1106 n = #vars 1107 """ 1108 return _pywrapcp.Solver_Deviation(self, vars, deviation_var, total_sum) 1109 1110 def AllDifferent(self, *args): 1111 r""" 1112 *Overload 1:* 1113 All variables are pairwise different. This corresponds to the 1114 stronger version of the propagation algorithm. 1115 1116 | 1117 1118 *Overload 2:* 1119 All variables are pairwise different. If 'stronger_propagation' 1120 is true, stronger, and potentially slower propagation will 1121 occur. This API will be deprecated in the future. 1122 """ 1123 return _pywrapcp.Solver_AllDifferent(self, *args) 1124 1125 def AllDifferentExcept(self, vars, escape_value): 1126 r""" 1127 All variables are pairwise different, unless they are assigned to 1128 the escape value. 1129 """ 1130 return _pywrapcp.Solver_AllDifferentExcept(self, vars, escape_value) 1131 1132 def SortingConstraint(self, vars, sorted): 1133 r""" 1134 Creates a constraint binding the arrays of variables "vars" and 1135 "sorted_vars": sorted_vars[0] must be equal to the minimum of all 1136 variables in vars, and so on: the value of sorted_vars[i] must be 1137 equal to the i-th value of variables invars. 1138 1139 This constraint propagates in both directions: from "vars" to 1140 "sorted_vars" and vice-versa. 1141 1142 Behind the scenes, this constraint maintains that: 1143 - sorted is always increasing. 1144 - whatever the values of vars, there exists a permutation that 1145 injects its values into the sorted variables. 1146 1147 For more info, please have a look at: 1148 https://mpi-inf.mpg.de/~mehlhorn/ftp/Mehlhorn-Thiel.pdf 1149 """ 1150 return _pywrapcp.Solver_SortingConstraint(self, vars, sorted) 1151 1152 def LexicalLess(self, left, right): 1153 r""" 1154 Creates a constraint that enforces that left is lexicographically less 1155 than right. 1156 """ 1157 return _pywrapcp.Solver_LexicalLess(self, left, right) 1158 1159 def LexicalLessOrEqual(self, left, right): 1160 r""" 1161 Creates a constraint that enforces that left is lexicographically less 1162 than or equal to right. 1163 """ 1164 return _pywrapcp.Solver_LexicalLessOrEqual(self, left, right) 1165 1166 def InversePermutationConstraint(self, left, right): 1167 r""" 1168 Creates a constraint that enforces that 'left' and 'right' both 1169 represent permutations of [0..left.size()-1], and that 'right' is 1170 the inverse permutation of 'left', i.e. for all i in 1171 [0..left.size()-1], right[left[i]] = i. 1172 """ 1173 return _pywrapcp.Solver_InversePermutationConstraint(self, left, right) 1174 1175 def NullIntersect(self, first_vars, second_vars): 1176 r""" 1177 Creates a constraint that states that all variables in the first 1178 vector are different from all variables in the second 1179 group. Thus the set of values in the first vector does not 1180 intersect with the set of values in the second vector. 1181 """ 1182 return _pywrapcp.Solver_NullIntersect(self, first_vars, second_vars) 1183 1184 def NullIntersectExcept(self, first_vars, second_vars, escape_value): 1185 r""" 1186 Creates a constraint that states that all variables in the first 1187 vector are different from all variables from the second group, 1188 unless they are assigned to the escape value. Thus the set of 1189 values in the first vector minus the escape value does not 1190 intersect with the set of values in the second vector. 1191 """ 1192 return _pywrapcp.Solver_NullIntersectExcept(self, first_vars, second_vars, escape_value) 1193 1194 def Circuit(self, nexts): 1195 r"""Force the "nexts" variable to create a complete Hamiltonian path.""" 1196 return _pywrapcp.Solver_Circuit(self, nexts) 1197 1198 def SubCircuit(self, nexts): 1199 r""" 1200 Force the "nexts" variable to create a complete Hamiltonian path 1201 for those that do not loop upon themselves. 1202 """ 1203 return _pywrapcp.Solver_SubCircuit(self, nexts) 1204 1205 def DelayedPathCumul(self, nexts, active, cumuls, transits): 1206 r""" 1207 Delayed version of the same constraint: propagation on the nexts variables 1208 is delayed until all constraints have propagated. 1209 """ 1210 return _pywrapcp.Solver_DelayedPathCumul(self, nexts, active, cumuls, transits) 1211 1212 def PathCumul(self, *args): 1213 r""" 1214 *Overload 1:* 1215 Creates a constraint which accumulates values along a path such that: 1216 cumuls[next[i]] = cumuls[i] + transits[i]. 1217 Active variables indicate if the corresponding next variable is active; 1218 this could be useful to model unperformed nodes in a routing problem. 1219 1220 | 1221 1222 *Overload 2:* 1223 Creates a constraint which accumulates values along a path such that: 1224 cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]). 1225 Active variables indicate if the corresponding next variable is active; 1226 this could be useful to model unperformed nodes in a routing problem. 1227 Ownership of transit_evaluator is taken and it must be a repeatable 1228 callback. 1229 1230 | 1231 1232 *Overload 3:* 1233 Creates a constraint which accumulates values along a path such that: 1234 cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]) + slacks[i]. 1235 Active variables indicate if the corresponding next variable is active; 1236 this could be useful to model unperformed nodes in a routing problem. 1237 Ownership of transit_evaluator is taken and it must be a repeatable 1238 callback. 1239 """ 1240 return _pywrapcp.Solver_PathCumul(self, *args) 1241 1242 def AllowedAssignments(self, *args): 1243 r""" 1244 *Overload 1:* 1245 This method creates a constraint where the graph of the relation 1246 between the variables is given in extension. There are 'arity' 1247 variables involved in the relation and the graph is given by a 1248 integer tuple set. 1249 1250 | 1251 1252 *Overload 2:* 1253 Compatibility layer for Python API. 1254 """ 1255 return _pywrapcp.Solver_AllowedAssignments(self, *args) 1256 1257 def TransitionConstraint(self, *args): 1258 r""" 1259 *Overload 1:* 1260 This constraint create a finite automaton that will check the 1261 sequence of variables vars. It uses a transition table called 1262 'transition_table'. Each transition is a triple 1263 (current_state, variable_value, new_state). 1264 The initial state is given, and the set of accepted states is decribed 1265 by 'final_states'. These states are hidden inside the constraint. 1266 Only the transitions (i.e. the variables) are visible. 1267 1268 | 1269 1270 *Overload 2:* 1271 This constraint create a finite automaton that will check the 1272 sequence of variables vars. It uses a transition table called 1273 'transition_table'. Each transition is a triple 1274 (current_state, variable_value, new_state). 1275 The initial state is given, and the set of accepted states is decribed 1276 by 'final_states'. These states are hidden inside the constraint. 1277 Only the transitions (i.e. the variables) are visible. 1278 """ 1279 return _pywrapcp.Solver_TransitionConstraint(self, *args) 1280 1281 def NonOverlappingBoxesConstraint(self, *args): 1282 r""" 1283 This constraint states that all the boxes must not overlap. 1284 The coordinates of box i are: 1285 (x_vars[i], y_vars[i]), 1286 (x_vars[i], y_vars[i] + y_size[i]), 1287 (x_vars[i] + x_size[i], y_vars[i]), 1288 (x_vars[i] + x_size[i], y_vars[i] + y_size[i]). 1289 The sizes must be non-negative. Boxes with a zero dimension can be 1290 pushed like any box. 1291 """ 1292 return _pywrapcp.Solver_NonOverlappingBoxesConstraint(self, *args) 1293 1294 def Pack(self, vars, number_of_bins): 1295 r""" 1296 This constraint packs all variables onto 'number_of_bins' 1297 variables. For any given variable, a value of 'number_of_bins' 1298 indicates that the variable is not assigned to any bin. 1299 Dimensions, i.e., cumulative constraints on this packing, can be 1300 added directly from the pack class. 1301 """ 1302 return _pywrapcp.Solver_Pack(self, vars, number_of_bins) 1303 1304 def FixedDurationIntervalVar(self, *args): 1305 r""" 1306 *Overload 1:* 1307 Creates an interval var with a fixed duration. The duration must 1308 be greater than 0. If optional is true, then the interval can be 1309 performed or unperformed. If optional is false, then the interval 1310 is always performed. 1311 1312 | 1313 1314 *Overload 2:* 1315 Creates a performed interval var with a fixed duration. The duration must 1316 be greater than 0. 1317 1318 | 1319 1320 *Overload 3:* 1321 Creates an interval var with a fixed duration, and performed_variable. 1322 The duration must be greater than 0. 1323 """ 1324 return _pywrapcp.Solver_FixedDurationIntervalVar(self, *args) 1325 1326 def FixedInterval(self, start, duration, name): 1327 r"""Creates a fixed and performed interval.""" 1328 return _pywrapcp.Solver_FixedInterval(self, start, duration, name) 1329 1330 def IntervalVar(self, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name): 1331 r""" 1332 Creates an interval var by specifying the bounds on start, 1333 duration, and end. 1334 """ 1335 return _pywrapcp.Solver_IntervalVar(self, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name) 1336 1337 def MirrorInterval(self, interval_var): 1338 r""" 1339 Creates an interval var that is the mirror image of the given one, that 1340 is, the interval var obtained by reversing the axis. 1341 """ 1342 return _pywrapcp.Solver_MirrorInterval(self, interval_var) 1343 1344 def FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset): 1345 r""" 1346 Creates an interval var with a fixed duration whose start is 1347 synchronized with the start of another interval, with a given 1348 offset. The performed status is also in sync with the performed 1349 status of the given interval variable. 1350 """ 1351 return _pywrapcp.Solver_FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset) 1352 1353 def FixedDurationStartSyncedOnEndIntervalVar(self, interval_var, duration, offset): 1354 r""" 1355 Creates an interval var with a fixed duration whose start is 1356 synchronized with the end of another interval, with a given 1357 offset. The performed status is also in sync with the performed 1358 status of the given interval variable. 1359 """ 1360 return _pywrapcp.Solver_FixedDurationStartSyncedOnEndIntervalVar(self, interval_var, duration, offset) 1361 1362 def FixedDurationEndSyncedOnStartIntervalVar(self, interval_var, duration, offset): 1363 r""" 1364 Creates an interval var with a fixed duration whose end is 1365 synchronized with the start of another interval, with a given 1366 offset. The performed status is also in sync with the performed 1367 status of the given interval variable. 1368 """ 1369 return _pywrapcp.Solver_FixedDurationEndSyncedOnStartIntervalVar(self, interval_var, duration, offset) 1370 1371 def FixedDurationEndSyncedOnEndIntervalVar(self, interval_var, duration, offset): 1372 r""" 1373 Creates an interval var with a fixed duration whose end is 1374 synchronized with the end of another interval, with a given 1375 offset. The performed status is also in sync with the performed 1376 status of the given interval variable. 1377 """ 1378 return _pywrapcp.Solver_FixedDurationEndSyncedOnEndIntervalVar(self, interval_var, duration, offset) 1379 1380 def IntervalRelaxedMin(self, interval_var): 1381 r""" 1382 Creates and returns an interval variable that wraps around the given one, 1383 relaxing the min start and end. Relaxing means making unbounded when 1384 optional. If the variable is non-optional, this method returns 1385 interval_var. 1386 1387 More precisely, such an interval variable behaves as follows: 1388 When the underlying must be performed, the returned interval variable 1389 behaves exactly as the underlying; 1390 When the underlying may or may not be performed, the returned interval 1391 variable behaves like the underlying, except that it is unbounded on 1392 the min side; 1393 When the underlying cannot be performed, the returned interval variable 1394 is of duration 0 and must be performed in an interval unbounded on 1395 both sides. 1396 1397 This is very useful to implement propagators that may only modify 1398 the start max or end max. 1399 """ 1400 return _pywrapcp.Solver_IntervalRelaxedMin(self, interval_var) 1401 1402 def IntervalRelaxedMax(self, interval_var): 1403 r""" 1404 Creates and returns an interval variable that wraps around the given one, 1405 relaxing the max start and end. Relaxing means making unbounded when 1406 optional. If the variable is non optional, this method returns 1407 interval_var. 1408 1409 More precisely, such an interval variable behaves as follows: 1410 When the underlying must be performed, the returned interval variable 1411 behaves exactly as the underlying; 1412 When the underlying may or may not be performed, the returned interval 1413 variable behaves like the underlying, except that it is unbounded on 1414 the max side; 1415 When the underlying cannot be performed, the returned interval variable 1416 is of duration 0 and must be performed in an interval unbounded on 1417 both sides. 1418 1419 This is very useful for implementing propagators that may only modify 1420 the start min or end min. 1421 """ 1422 return _pywrapcp.Solver_IntervalRelaxedMax(self, interval_var) 1423 1424 def TemporalDisjunction(self, *args): 1425 r""" 1426 *Overload 1:* 1427 This constraint implements a temporal disjunction between two 1428 interval vars t1 and t2. 'alt' indicates which alternative was 1429 chosen (alt == 0 is equivalent to t1 before t2). 1430 1431 | 1432 1433 *Overload 2:* 1434 This constraint implements a temporal disjunction between two 1435 interval vars. 1436 """ 1437 return _pywrapcp.Solver_TemporalDisjunction(self, *args) 1438 1439 def DisjunctiveConstraint(self, intervals, name): 1440 r""" 1441 This constraint forces all interval vars into an non-overlapping 1442 sequence. Intervals with zero duration can be scheduled anywhere. 1443 """ 1444 return _pywrapcp.Solver_DisjunctiveConstraint(self, intervals, name) 1445 1446 def Cumulative(self, *args): 1447 r""" 1448 *Overload 1:* 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 1451 capacity. 1452 1453 Intervals and demands should be vectors of equal size. 1454 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. 1458 1459 | 1460 1461 *Overload 2:* 1462 This constraint forces that, for any integer t, the sum of the demands 1463 corresponding to an interval containing t does not exceed the given 1464 capacity. 1465 1466 Intervals and demands should be vectors of equal size. 1467 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. 1471 1472 | 1473 1474 *Overload 3:* 1475 This constraint forces that, for any integer t, the sum of the demands 1476 corresponding to an interval containing t does not exceed the given 1477 capacity. 1478 1479 Intervals and demands should be vectors of equal size. 1480 1481 Demands should only contain non-negative values. Zero values are 1482 supported, and the corresponding intervals are filtered out, as they 1483 neither impact nor are impacted by this constraint. 1484 1485 | 1486 1487 *Overload 4:* 1488 This constraint enforces that, for any integer t, the sum of the demands 1489 corresponding to an interval containing t does not exceed the given 1490 capacity. 1491 1492 Intervals and demands should be vectors of equal size. 1493 1494 Demands should only contain non-negative values. Zero values are 1495 supported, and the corresponding intervals are filtered out, as they 1496 neither impact nor are impacted by this constraint. 1497 1498 | 1499 1500 *Overload 5:* 1501 This constraint enforces that, for any integer t, the sum of demands 1502 corresponding to an interval containing t does not exceed the given 1503 capacity. 1504 1505 Intervals and demands should be vectors of equal size. 1506 1507 Demands should be positive. 1508 1509 | 1510 1511 *Overload 6:* 1512 This constraint enforces that, for any integer t, the sum of demands 1513 corresponding to an interval containing t does not exceed the given 1514 capacity. 1515 1516 Intervals and demands should be vectors of equal size. 1517 1518 Demands should be positive. 1519 """ 1520 return _pywrapcp.Solver_Cumulative(self, *args) 1521 1522 def Cover(self, vars, target_var): 1523 r""" 1524 This constraint states that the target_var is the convex hull of 1525 the intervals. If none of the interval variables is performed, 1526 then the target var is unperformed too. Also, if the target 1527 variable is unperformed, then all the intervals variables are 1528 unperformed too. 1529 """ 1530 return _pywrapcp.Solver_Cover(self, vars, target_var) 1531 1532 def Assignment(self, *args): 1533 r""" 1534 *Overload 1:* 1535 This method creates an empty assignment. 1536 1537 | 1538 1539 *Overload 2:* 1540 This method creates an assignment which is a copy of 'a'. 1541 """ 1542 return _pywrapcp.Solver_Assignment(self, *args) 1543 1544 def FirstSolutionCollector(self, *args): 1545 r""" 1546 *Overload 1:* 1547 Collect the first solution of the search. 1548 1549 | 1550 1551 *Overload 2:* 1552 Collect the first solution of the search. The variables will need to 1553 be added later. 1554 """ 1555 return _pywrapcp.Solver_FirstSolutionCollector(self, *args) 1556 1557 def LastSolutionCollector(self, *args): 1558 r""" 1559 *Overload 1:* 1560 Collect the last solution of the search. 1561 1562 | 1563 1564 *Overload 2:* 1565 Collect the last solution of the search. The variables will need to 1566 be added later. 1567 """ 1568 return _pywrapcp.Solver_LastSolutionCollector(self, *args) 1569 1570 def BestValueSolutionCollector(self, *args): 1571 r""" 1572 *Overload 1:* 1573 Collect the solution corresponding to the optimal value of the objective 1574 of 'assignment'; if 'assignment' does not have an objective no solution is 1575 collected. This collector only collects one solution corresponding to the 1576 best objective value (the first one found). 1577 1578 | 1579 1580 *Overload 2:* 1581 Collect the solution corresponding to the optimal value of the 1582 objective of the internal assignment; if this assignment does not have an 1583 objective no solution is collected. This collector only collects one 1584 solution corresponding to the best objective value (the first one found). 1585 The variables and objective(s) will need to be added later. 1586 """ 1587 return _pywrapcp.Solver_BestValueSolutionCollector(self, *args) 1588 1589 def AllSolutionCollector(self, *args): 1590 r""" 1591 *Overload 1:* 1592 Collect all solutions of the search. 1593 1594 | 1595 1596 *Overload 2:* 1597 Collect all solutions of the search. The variables will need to 1598 be added later. 1599 """ 1600 return _pywrapcp.Solver_AllSolutionCollector(self, *args) 1601 1602 def Minimize(self, v, step): 1603 r"""Creates a minimization objective.""" 1604 return _pywrapcp.Solver_Minimize(self, v, step) 1605 1606 def Maximize(self, v, step): 1607 r"""Creates a maximization objective.""" 1608 return _pywrapcp.Solver_Maximize(self, v, step) 1609 1610 def Optimize(self, maximize, v, step): 1611 r"""Creates a objective with a given sense (true = maximization).""" 1612 return _pywrapcp.Solver_Optimize(self, maximize, v, step) 1613 1614 def WeightedMinimize(self, *args): 1615 r""" 1616 *Overload 1:* 1617 Creates a minimization weighted objective. The actual objective is 1618 scalar_prod(sub_objectives, weights). 1619 1620 | 1621 1622 *Overload 2:* 1623 Creates a minimization weighted objective. The actual objective is 1624 scalar_prod(sub_objectives, weights). 1625 """ 1626 return _pywrapcp.Solver_WeightedMinimize(self, *args) 1627 1628 def WeightedMaximize(self, *args): 1629 r""" 1630 *Overload 1:* 1631 Creates a maximization weigthed objective. 1632 1633 | 1634 1635 *Overload 2:* 1636 Creates a maximization weigthed objective. 1637 """ 1638 return _pywrapcp.Solver_WeightedMaximize(self, *args) 1639 1640 def WeightedOptimize(self, *args): 1641 r""" 1642 *Overload 1:* 1643 Creates a weighted objective with a given sense (true = maximization). 1644 1645 | 1646 1647 *Overload 2:* 1648 Creates a weighted objective with a given sense (true = maximization). 1649 """ 1650 return _pywrapcp.Solver_WeightedOptimize(self, *args) 1651 1652 def TabuSearch(self, maximize, objective, step, vars, keep_tenure, forbid_tenure, tabu_factor): 1653 r""" 1654 MetaHeuristics which try to get the search out of local optima. 1655 Creates a Tabu Search monitor. 1656 In the context of local search the behavior is similar to MakeOptimize(), 1657 creating an objective in a given sense. The behavior differs once a local 1658 optimum is reached: thereafter solutions which degrade the value of the 1659 objective are allowed if they are not "tabu". A solution is "tabu" if it 1660 doesn't respect the following rules: 1661 - improving the best solution found so far 1662 - variables in the "keep" list must keep their value, variables in the 1663 "forbid" list must not take the value they have in the list. 1664 Variables with new values enter the tabu lists after each new solution 1665 found and leave the lists after a given number of iterations (called 1666 tenure). Only the variables passed to the method can enter the lists. 1667 The tabu criterion is softened by the tabu factor which gives the number 1668 of "tabu" violations which is tolerated; a factor of 1 means no violations 1669 allowed; a factor of 0 means all violations are allowed. 1670 """ 1671 return _pywrapcp.Solver_TabuSearch(self, maximize, objective, step, vars, keep_tenure, forbid_tenure, tabu_factor) 1672 1673 def SimulatedAnnealing(self, maximize, v, step, initial_temperature): 1674 r"""Creates a Simulated Annealing monitor.""" 1675 return _pywrapcp.Solver_SimulatedAnnealing(self, maximize, v, step, initial_temperature) 1676 1677 def LubyRestart(self, scale_factor): 1678 r""" 1679 This search monitor will restart the search periodically. 1680 At the iteration n, it will restart after scale_factor * Luby(n) failures 1681 where Luby is the Luby Strategy (i.e. 1 1 2 1 1 2 4 1 1 2 1 1 2 4 8...). 1682 """ 1683 return _pywrapcp.Solver_LubyRestart(self, scale_factor) 1684 1685 def ConstantRestart(self, frequency): 1686 r""" 1687 This search monitor will restart the search periodically after 'frequency' 1688 failures. 1689 """ 1690 return _pywrapcp.Solver_ConstantRestart(self, frequency) 1691 1692 def TimeLimit(self, *args): 1693 r"""Creates a search limit that constrains the running time.""" 1694 return _pywrapcp.Solver_TimeLimit(self, *args) 1695 1696 def BranchesLimit(self, branches): 1697 r""" 1698 Creates a search limit that constrains the number of branches 1699 explored in the search tree. 1700 """ 1701 return _pywrapcp.Solver_BranchesLimit(self, branches) 1702 1703 def FailuresLimit(self, failures): 1704 r""" 1705 Creates a search limit that constrains the number of failures 1706 that can happen when exploring the search tree. 1707 """ 1708 return _pywrapcp.Solver_FailuresLimit(self, failures) 1709 1710 def SolutionsLimit(self, solutions): 1711 r""" 1712 Creates a search limit that constrains the number of solutions found 1713 during the search. 1714 """ 1715 return _pywrapcp.Solver_SolutionsLimit(self, solutions) 1716 1717 def Limit(self, *args): 1718 r""" 1719 *Overload 1:* 1720 Limits the search with the 'time', 'branches', 'failures' and 1721 'solutions' limits. 'smart_time_check' reduces the calls to the wall 1722 1723 | 1724 1725 *Overload 2:* 1726 Creates a search limit from its protobuf description 1727 1728 | 1729 1730 *Overload 3:* 1731 Creates a search limit that is reached when either of the underlying limit 1732 is reached. That is, the returned limit is more stringent than both 1733 argument limits. 1734 """ 1735 return _pywrapcp.Solver_Limit(self, *args) 1736 1737 def CustomLimit(self, limiter): 1738 r""" 1739 Callback-based search limit. Search stops when limiter returns true; if 1740 this happens at a leaf the corresponding solution will be rejected. 1741 """ 1742 return _pywrapcp.Solver_CustomLimit(self, limiter) 1743 1744 def SearchLog(self, *args): 1745 r""" 1746 *Overload 1:* 1747 The SearchMonitors below will display a periodic search log 1748 on LOG(INFO) every branch_period branches explored. 1749 1750 | 1751 1752 *Overload 2:* 1753 At each solution, this monitor also display the var value. 1754 1755 | 1756 1757 *Overload 3:* 1758 At each solution, this monitor will also display result of 1759 ``display_callback``. 1760 1761 | 1762 1763 *Overload 4:* 1764 At each solution, this monitor will display the 'var' value and the 1765 result of ``display_callback``. 1766 1767 | 1768 1769 *Overload 5:* 1770 At each solution, this monitor will display the 'vars' values and the 1771 result of ``display_callback``. 1772 1773 | 1774 1775 *Overload 6:* 1776 OptimizeVar Search Logs 1777 At each solution, this monitor will also display the 'opt_var' value. 1778 1779 | 1780 1781 *Overload 7:* 1782 Creates a search monitor that will also print the result of the 1783 display callback. 1784 """ 1785 return _pywrapcp.Solver_SearchLog(self, *args) 1786 1787 def SearchTrace(self, prefix): 1788 r""" 1789 Creates a search monitor that will trace precisely the behavior of the 1790 search. Use this only for low level debugging. 1791 """ 1792 return _pywrapcp.Solver_SearchTrace(self, prefix) 1793 1794 def PrintModelVisitor(self): 1795 r"""Prints the model.""" 1796 return _pywrapcp.Solver_PrintModelVisitor(self) 1797 1798 def StatisticsModelVisitor(self): 1799 r"""Displays some nice statistics on the model.""" 1800 return _pywrapcp.Solver_StatisticsModelVisitor(self) 1801 1802 def AssignVariableValue(self, var, val): 1803 r"""Decisions.""" 1804 return _pywrapcp.Solver_AssignVariableValue(self, var, val) 1805 1806 def VariableLessOrEqualValue(self, var, value): 1807 return _pywrapcp.Solver_VariableLessOrEqualValue(self, var, value) 1808 1809 def VariableGreaterOrEqualValue(self, var, value): 1810 return _pywrapcp.Solver_VariableGreaterOrEqualValue(self, var, value) 1811 1812 def SplitVariableDomain(self, var, val, start_with_lower_half): 1813 return _pywrapcp.Solver_SplitVariableDomain(self, var, val, start_with_lower_half) 1814 1815 def AssignVariableValueOrFail(self, var, value): 1816 return _pywrapcp.Solver_AssignVariableValueOrFail(self, var, value) 1817 1818 def AssignVariablesValues(self, vars, values): 1819 return _pywrapcp.Solver_AssignVariablesValues(self, vars, values) 1820 1821 def FailDecision(self): 1822 return _pywrapcp.Solver_FailDecision(self) 1823 1824 def Decision(self, apply, refute): 1825 return _pywrapcp.Solver_Decision(self, apply, refute) 1826 1827 def Compose(self, dbs): 1828 return _pywrapcp.Solver_Compose(self, dbs) 1829 1830 def Try(self, dbs): 1831 return _pywrapcp.Solver_Try(self, dbs) 1832 1833 def DefaultPhase(self, *args): 1834 return _pywrapcp.Solver_DefaultPhase(self, *args) 1835 1836 def ScheduleOrPostpone(self, var, est, marker): 1837 r""" 1838 Returns a decision that tries to schedule a task at a given time. 1839 On the Apply branch, it will set that interval var as performed and set 1840 its start to 'est'. On the Refute branch, it will just update the 1841 'marker' to 'est' + 1. This decision is used in the 1842 INTERVAL_SET_TIMES_FORWARD strategy. 1843 """ 1844 return _pywrapcp.Solver_ScheduleOrPostpone(self, var, est, marker) 1845 1846 def ScheduleOrExpedite(self, var, est, marker): 1847 r""" 1848 Returns a decision that tries to schedule a task at a given time. 1849 On the Apply branch, it will set that interval var as performed and set 1850 its end to 'est'. On the Refute branch, it will just update the 1851 'marker' to 'est' - 1. This decision is used in the 1852 INTERVAL_SET_TIMES_BACKWARD strategy. 1853 """ 1854 return _pywrapcp.Solver_ScheduleOrExpedite(self, var, est, marker) 1855 1856 def RankFirstInterval(self, sequence, index): 1857 r""" 1858 Returns a decision that tries to rank first the ith interval var 1859 in the sequence variable. 1860 """ 1861 return _pywrapcp.Solver_RankFirstInterval(self, sequence, index) 1862 1863 def RankLastInterval(self, sequence, index): 1864 r""" 1865 Returns a decision that tries to rank last the ith interval var 1866 in the sequence variable. 1867 """ 1868 return _pywrapcp.Solver_RankLastInterval(self, sequence, index) 1869 1870 def Phase(self, *args): 1871 r""" 1872 *Overload 1:* 1873 Phases on IntVar arrays. 1874 for all other functions that have several homonyms in this .h). 1875 1876 | 1877 1878 *Overload 2:* 1879 Scheduling phases. 1880 """ 1881 return _pywrapcp.Solver_Phase(self, *args) 1882 1883 def DecisionBuilderFromAssignment(self, assignment, db, vars): 1884 r""" 1885 Returns a decision builder for which the left-most leaf corresponds 1886 to assignment, the rest of the tree being explored using 'db'. 1887 """ 1888 return _pywrapcp.Solver_DecisionBuilderFromAssignment(self, assignment, db, vars) 1889 1890 def ConstraintAdder(self, ct): 1891 r""" 1892 Returns a decision builder that will add the given constraint to 1893 the model. 1894 """ 1895 return _pywrapcp.Solver_ConstraintAdder(self, ct) 1896 1897 def SolveOnce(self, db, monitors): 1898 return _pywrapcp.Solver_SolveOnce(self, db, monitors) 1899 1900 def NestedOptimize(self, *args): 1901 r""" 1902 NestedOptimize will collapse a search tree described by a 1903 decision builder 'db' and a set of monitors and wrap it into a 1904 single point. If there are no solutions to this nested tree, then 1905 NestedOptimize will fail. If there are solutions, it will find 1906 the best as described by the mandatory objective in the solution 1907 as well as the optimization direction, instantiate all variables 1908 to this solution, and return nullptr. 1909 """ 1910 return _pywrapcp.Solver_NestedOptimize(self, *args) 1911 1912 def RestoreAssignment(self, assignment): 1913 r""" 1914 Returns a DecisionBuilder which restores an Assignment 1915 (calls void Assignment::Restore()) 1916 """ 1917 return _pywrapcp.Solver_RestoreAssignment(self, assignment) 1918 1919 def StoreAssignment(self, assignment): 1920 r""" 1921 Returns a DecisionBuilder which stores an Assignment 1922 (calls void Assignment::Store()) 1923 """ 1924 return _pywrapcp.Solver_StoreAssignment(self, assignment) 1925 1926 def Operator(self, *args): 1927 r"""Local Search Operators.""" 1928 return _pywrapcp.Solver_Operator(self, *args) 1929 1930 def RandomLnsOperator(self, *args): 1931 r""" 1932 Creates a large neighborhood search operator which creates fragments (set 1933 of relaxed variables) with up to number_of_variables random variables 1934 (sampling with replacement is performed meaning that at most 1935 number_of_variables variables are selected). Warning: this operator will 1936 always return neighbors; using it without a search limit will result in a 1937 non-ending search. 1938 Optionally a random seed can be specified. 1939 """ 1940 return _pywrapcp.Solver_RandomLnsOperator(self, *args) 1941 1942 def MoveTowardTargetOperator(self, *args): 1943 r""" 1944 *Overload 1:* 1945 Creates a local search operator that tries to move the assignment of some 1946 variables toward a target. The target is given as an Assignment. This 1947 operator generates neighbors in which the only difference compared to the 1948 current state is that one variable that belongs to the target assignment 1949 is set to its target value. 1950 1951 | 1952 1953 *Overload 2:* 1954 Creates a local search operator that tries to move the assignment of some 1955 variables toward a target. The target is given either as two vectors: a 1956 vector of variables and a vector of associated target values. The two 1957 vectors should be of the same length. This operator generates neighbors in 1958 which the only difference compared to the current state is that one 1959 variable that belongs to the given vector is set to its target value. 1960 """ 1961 return _pywrapcp.Solver_MoveTowardTargetOperator(self, *args) 1962 1963 def ConcatenateOperators(self, *args): 1964 r""" 1965 Creates a local search operator which concatenates a vector of operators. 1966 Each operator from the vector is called sequentially. By default, when a 1967 neighbor is found the neighborhood exploration restarts from the last 1968 active operator (the one which produced the neighbor). 1969 This can be overridden by setting restart to true to force the exploration 1970 to start from the first operator in the vector. 1971 1972 The default behavior can also be overridden using an evaluation callback 1973 to set the order in which the operators are explored (the callback is 1974 called in LocalSearchOperator::Start()). The first argument of the 1975 callback is the index of the operator which produced the last move, the 1976 second argument is the index of the operator to be evaluated. Ownership of 1977 the callback is taken by ConcatenateOperators. 1978 1979 Example: 1980 1981 const int kPriorities = {10, 100, 10, 0}; 1982 int64_t Evaluate(int active_operator, int current_operator) { 1983 return kPriorities[current_operator]; 1984 } 1985 1986 LocalSearchOperator* concat = 1987 solver.ConcatenateOperators(operators, 1988 NewPermanentCallback(&Evaluate)); 1989 1990 The elements of the vector operators will be sorted by increasing priority 1991 and explored in that order (tie-breaks are handled by keeping the relative 1992 operator order in the vector). This would result in the following order: 1993 operators[3], operators[0], operators[2], operators[1]. 1994 """ 1995 return _pywrapcp.Solver_ConcatenateOperators(self, *args) 1996 1997 def RandomConcatenateOperators(self, *args): 1998 r""" 1999 *Overload 1:* 2000 Randomized version of local search concatenator; calls a random operator 2001 at each call to MakeNextNeighbor(). 2002 2003 | 2004 2005 *Overload 2:* 2006 Randomized version of local search concatenator; calls a random operator 2007 at each call to MakeNextNeighbor(). The provided seed is used to 2008 initialize the random number generator. 2009 """ 2010 return _pywrapcp.Solver_RandomConcatenateOperators(self, *args) 2011 2012 def NeighborhoodLimit(self, op, limit): 2013 r""" 2014 Creates a local search operator that wraps another local search 2015 operator and limits the number of neighbors explored (i.e., calls 2016 to MakeNextNeighbor from the current solution (between two calls 2017 to Start()). When this limit is reached, MakeNextNeighbor() 2018 returns false. The counter is cleared when Start() is called. 2019 """ 2020 return _pywrapcp.Solver_NeighborhoodLimit(self, op, limit) 2021 2022 def LocalSearchPhase(self, *args): 2023 r""" 2024 *Overload 1:* 2025 Local Search decision builders factories. 2026 Local search is used to improve a given solution. This initial solution 2027 can be specified either by an Assignment or by a DecisionBulder, and the 2028 corresponding variables, the initial solution being the first solution 2029 found by the DecisionBuilder. 2030 The LocalSearchPhaseParameters parameter holds the actual definition of 2031 the local search phase: 2032 - a local search operator used to explore the neighborhood of the current 2033 solution, 2034 - a decision builder to instantiate unbound variables once a neighbor has 2035 been defined; in the case of LNS-based operators instantiates fragment 2036 variables; search monitors can be added to this sub-search by wrapping 2037 the decision builder with MakeSolveOnce. 2038 - a search limit specifying how long local search looks for neighbors 2039 before accepting one; the last neighbor is always taken and in the case 2040 of a greedy search, this corresponds to the best local neighbor; 2041 first-accept (which is the default behavior) can be modeled using a 2042 solution found limit of 1, 2043 - a vector of local search filters used to speed up the search by pruning 2044 unfeasible neighbors. 2045 Metaheuristics can be added by defining specialized search monitors; 2046 currently down/up-hill climbing is available through OptimizeVar, as well 2047 as Guided Local Search, Tabu Search and Simulated Annealing. 2048 2049 | 2050 2051 *Overload 2:* 2052 Variant with a sub_decison_builder specific to the first solution. 2053 """ 2054 return _pywrapcp.Solver_LocalSearchPhase(self, *args) 2055 2056 def LocalSearchPhaseParameters(self, *args): 2057 r"""Local Search Phase Parameters""" 2058 return _pywrapcp.Solver_LocalSearchPhaseParameters(self, *args) 2059 2060 def TopProgressPercent(self): 2061 r""" 2062 Returns a percentage representing the propress of the search before 2063 reaching the limits of the top-level search (can be called from a nested 2064 solve). 2065 """ 2066 return _pywrapcp.Solver_TopProgressPercent(self) 2067 2068 def SearchDepth(self): 2069 r""" 2070 Gets the search depth of the current active search. Returns -1 if 2071 there is no active search opened. 2072 """ 2073 return _pywrapcp.Solver_SearchDepth(self) 2074 2075 def SearchLeftDepth(self): 2076 r""" 2077 Gets the search left depth of the current active search. Returns -1 if 2078 there is no active search opened. 2079 """ 2080 return _pywrapcp.Solver_SearchLeftDepth(self) 2081 2082 def SolveDepth(self): 2083 r""" 2084 Gets the number of nested searches. It returns 0 outside search, 2085 1 during the top level search, 2 or more in case of nested searches. 2086 """ 2087 return _pywrapcp.Solver_SolveDepth(self) 2088 2089 def Rand64(self, size): 2090 r"""Returns a random value between 0 and 'size' - 1;""" 2091 return _pywrapcp.Solver_Rand64(self, size) 2092 2093 def Rand32(self, size): 2094 r"""Returns a random value between 0 and 'size' - 1;""" 2095 return _pywrapcp.Solver_Rand32(self, size) 2096 2097 def ReSeed(self, seed): 2098 r"""Reseed the solver random generator.""" 2099 return _pywrapcp.Solver_ReSeed(self, seed) 2100 2101 def LocalSearchProfile(self): 2102 r"""Returns local search profiling information in a human readable format.""" 2103 return _pywrapcp.Solver_LocalSearchProfile(self) 2104 2105 def Constraints(self): 2106 r""" 2107 Counts the number of constraints that have been added 2108 to the solver before the search. 2109 """ 2110 return _pywrapcp.Solver_Constraints(self) 2111 2112 def Accept(self, visitor): 2113 r"""Accepts the given model visitor.""" 2114 return _pywrapcp.Solver_Accept(self, visitor) 2115 2116 def FinishCurrentSearch(self): 2117 r"""Tells the solver to kill or restart the current search.""" 2118 return _pywrapcp.Solver_FinishCurrentSearch(self) 2119 2120 def RestartCurrentSearch(self): 2121 return _pywrapcp.Solver_RestartCurrentSearch(self) 2122 2123 def ShouldFail(self): 2124 r""" 2125 These methods are only useful for the SWIG wrappers, which need a way 2126 to externally cause the Solver to fail. 2127 """ 2128 return _pywrapcp.Solver_ShouldFail(self) 2129 2130 def __str__(self): 2131 return _pywrapcp.Solver___str__(self) 2132 2133 def Add(self, ct): 2134 if isinstance(ct, PyConstraint): 2135 self.__python_constraints.append(ct) 2136 self.AddConstraint(ct) 2137 2138 2139 def TreeNoCycle(self, nexts, active, callback=0): 2140 return _pywrapcp.Solver_TreeNoCycle(self, nexts, active, callback) 2141 2142 def SearchLogWithCallback(self, period, callback): 2143 return _pywrapcp.Solver_SearchLogWithCallback(self, period, callback) 2144 2145 def ElementFunction(self, values, index): 2146 return _pywrapcp.Solver_ElementFunction(self, values, index) 2147 2148 def VarEvalValStrPhase(self, vars, var_evaluator, val_str): 2149 return _pywrapcp.Solver_VarEvalValStrPhase(self, vars, var_evaluator, val_str) 2150 2151 def VarStrValEvalPhase(self, vars, var_str, val_eval): 2152 return _pywrapcp.Solver_VarStrValEvalPhase(self, vars, var_str, val_eval) 2153 2154 def VarEvalValEvalPhase(self, vars, var_eval, val_eval): 2155 return _pywrapcp.Solver_VarEvalValEvalPhase(self, vars, var_eval, val_eval) 2156 2157 def VarStrValEvalTieBreakPhase(self, vars, var_str, val_eval, tie_breaker): 2158 return _pywrapcp.Solver_VarStrValEvalTieBreakPhase(self, vars, var_str, val_eval, tie_breaker) 2159 2160 def VarEvalValEvalTieBreakPhase(self, vars, var_eval, val_eval, tie_breaker): 2161 return _pywrapcp.Solver_VarEvalValEvalTieBreakPhase(self, vars, var_eval, val_eval, tie_breaker) 2162 2163 def EvalEvalStrPhase(self, vars, evaluator, str): 2164 return _pywrapcp.Solver_EvalEvalStrPhase(self, vars, evaluator, str) 2165 2166 def EvalEvalStrTieBreakPhase(self, vars, evaluator, tie_breaker, str): 2167 return _pywrapcp.Solver_EvalEvalStrTieBreakPhase(self, vars, evaluator, tie_breaker, str) 2168 2169 def GuidedLocalSearch(self, maximize, objective, objective_function, step, vars, penalty_factor): 2170 return _pywrapcp.Solver_GuidedLocalSearch(self, maximize, objective, objective_function, step, vars, penalty_factor) 2171 2172 def SumObjectiveFilter(self, vars, values, filter_enum): 2173 return _pywrapcp.Solver_SumObjectiveFilter(self, vars, values, filter_enum)
Solver Class. A solver represents the main computation engine. It implements the entire range of Constraint Programming protocols:
- Reversibility
- Propagation
- Search
Usually, Constraint Programming code consists of
- the creation of the Solver,
- the creation of the decision variables of the model,
- the creation of the constraints of the model and their addition to the solver() through the AddConstraint() method,
- the creation of the main DecisionBuilder class,
- the launch of the solve() method with the decision builder.
For the time being, Solver is neither MT_SAFE nor MT_HOT.
461 def __init__(self, *args): 462 r"""Solver API""" 463 _pywrapcp.Solver_swiginit(self, _pywrapcp.new_Solver(*args)) 464 465 self.__python_constraints = []
Solver API
138 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Select the first unbound variable. Variables are considered in the order of the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of possible values. In case of a tie, the selected variables is the one with the lowest min value. In case of a tie, the first one is selected, first being defined by the order in the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of possible values. In case of a tie, the selected variable is the one with the highest min value. In case of a tie, the first one is selected, first being defined by the order in the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of possible values. In case of a tie, the selected variables is the one with the lowest max value. In case of a tie, the first one is selected, first being defined by the order in the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of possible values. In case of a tie, the selected variable is the one with the highest max value. In case of a tie, the first one is selected, first being defined by the order in the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the smallest minimal value. In case of a tie, the first one is selected, "first" defined by the order in the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the highest maximal value. In case of a tie, the first one is selected, first being defined by the order in the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the smallest size. In case of a tie, the first one is selected, first being defined by the order in the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the highest size. In case of a tie, the first one is selected, first being defined by the order in the vector of IntVars used to create the selector.
Among unbound variables, select the variable with the largest gap between the first and the second values of the domain.
Selects the next unbound variable on a path, the path being defined by the variables: var[i] corresponds to the index of the next of i.
Selects the first possible value which is the closest to the center of the domain of the selected variable. The center is defined as (min + max) / 2.
Selects the variable with the lowest starting time of all variables, and fixes its starting time to this lowest value.
Selects the variable with the highest ending time of all variables, and fixes the ending time to this highest values.
Operator which reverses a sub-chain of a path. It is called TwoOpt because it breaks two arcs on the path; resulting paths are called two-optimal. Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5 (where (1, 5) are first and last nodes of the path and can therefore not be moved):
1 -> [3 -> 2] -> 4 -> 5
1 -> [4 -> 3 -> 2] -> 5
1 -> 2 -> [4 -> 3] -> 5
Relocate: OROPT and RELOCATE. Operator which moves a sub-chain of a path to another position; the specified chain length is the fixed length of the chains being moved. When this length is 1, the operator simply moves a node to another position. Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5, for a chain length of 2 (where (1, 5) are first and last nodes of the path and can therefore not be moved):
1 -> 4 -> [2 -> 3] -> 5
1 -> [3 -> 4] -> 2 -> 5
Using Relocate with chain lengths of 1, 2 and 3 together is equivalent to the OrOpt operator on a path. The OrOpt operator is a limited version of 3Opt (breaks 3 arcs on a path).
Operator which exchanges the positions of two nodes. Possible neighbors for the path 1 -> 2 -> 3 -> 4 -> 5 (where (1, 5) are first and last nodes of the path and can therefore not be moved):
1 -> [3] -> [2] -> 4 -> 5
1 -> [4] -> 3 -> [2] -> 5
1 -> 2 -> [4] -> [3] -> 5
Operator which cross exchanges the starting chains of 2 paths, including exchanging the whole paths. First and last nodes are not moved. Possible neighbors for the paths 1 -> 2 -> 3 -> 4 -> 5 and 6 -> 7 -> 8 (where (1, 5) and (6, 8) are first and last nodes of the paths and can therefore not be moved):
1 -> [7] -> 3 -> 4 -> 5 6 -> [2] -> 8
1 -> [7] -> 4 -> 5 6 -> [2 -> 3] -> 8
1 -> [7] -> 5 6 -> [2 -> 3 -> 4] -> 8
Operator which inserts an inactive node into a path. Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive (where 1 and 4 are first and last nodes of the path) are:
1 -> [5] -> 2 -> 3 -> 4
1 -> 2 -> [5] -> 3 -> 4
1 -> 2 -> 3 -> [5] -> 4
Operator which makes path nodes inactive. Possible neighbors for the path 1 -> 2 -> 3 -> 4 (where 1 and 4 are first and last nodes of the path) are:
1 -> 3 -> 4 with 2 inactive
1 -> 2 -> 4 with 3 inactive
Operator which makes a "chain" of path nodes inactive. Possible neighbors for the path 1 -> 2 -> 3 -> 4 (where 1 and 4 are first and last nodes of the path) are:
1 -> 3 -> 4 with 2 inactive
1 -> 2 -> 4 with 3 inactive
1 -> 4 with 2 and 3 inactive
Operator which replaces an active node by an inactive one. Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive (where 1 and 4 are first and last nodes of the path) are:
1 -> [5] -> 3 -> 4 with 2 inactive
1 -> 2 -> [5] -> 4 with 3 inactive
Operator which makes an inactive node active and an active one inactive. It is similar to SwapActiveOperator except that it tries to insert the inactive node in all possible positions instead of just the position of the node made inactive. Possible neighbors for the path 1 -> 2 -> 3 -> 4 with 5 inactive (where 1 and 4 are first and last nodes of the path) are:
1 -> [5] -> 3 -> 4 with 2 inactive
1 -> 3 -> [5] -> 4 with 2 inactive
1 -> [5] -> 2 -> 4 with 3 inactive
1 -> 2 -> [5] -> 4 with 3 inactive
Operator which relaxes two sub-chains of three consecutive arcs each. Each sub-chain is defined by a start node and the next three arcs. Those six arcs are relaxed to build a new neighbor. PATHLNS explores all possible pairs of starting nodes and so defines n^2 neighbors, n being the number of nodes. Note that the two sub-chains can be part of the same path; they even may overlap.
Operator which relaxes one entire path and all inactive nodes, thus defining num_paths neighbors.
Operator which relaxes all inactive nodes and one sub-chain of six consecutive arcs. That way the path can be improved by inserting inactive nodes or swapping arcs.
Operator which defines one neighbor per variable. Each neighbor tries to increment by one the value of the corresponding variable. When a new solution is found the neighborhood is rebuilt from scratch, i.e., tries to increment values in the variable order. Consider for instance variables x and y. x is incremented one by one to its max, and when it is not possible to increment x anymore, y is incremented once. If this is a solution, then next neighbor tries to increment x.
Operator which defines a neighborhood to decrement values. The behavior is the same as INCREMENT, except values are decremented instead of incremented.
Operator which defines one neighbor per variable. Each neighbor relaxes one variable. When a new solution is found the neighborhood is rebuilt from scratch. Consider for instance variables x and y. First x is relaxed and the solver is looking for the best possible solution (with only x relaxed). Then y is relaxed, and the solver is looking for a new solution. If a new solution is found, then the next variable to be relaxed is x.
Move is accepted when the current objective value is in the interval objective.Min .. objective.Max.
DELAYED_PRIORITY is the lowest priority: Demons will be processed after VAR_PRIORITY and NORMAL_PRIORITY demons.
471 def Parameters(self): 472 r"""Stored Parameters.""" 473 return _pywrapcp.Solver_Parameters(self)
Stored Parameters.
475 @staticmethod 476 def DefaultSolverParameters(): 477 r"""Create a ConstraintSolverParameters proto with all the default values.""" 478 return _pywrapcp.Solver_DefaultSolverParameters()
Create a ConstraintSolverParameters proto with all the default values.
480 def AddConstraint(self, c): 481 r""" 482 Adds the constraint 'c' to the model. 483 484 After calling this method, and until there is a backtrack that undoes the 485 addition, any assignment of variables to values must satisfy the given 486 constraint in order to be considered feasible. There are two fairly 487 different use cases: 488 489 - the most common use case is modeling: the given constraint is really 490 part of the problem that the user is trying to solve. In this use case, 491 AddConstraint is called outside of search (i.e., with state() == 492 OUTSIDE_SEARCH). Most users should only use AddConstraint in this 493 way. In this case, the constraint will belong to the model forever: it 494 cannot be removed by backtracking. 495 496 - a rarer use case is that 'c' is not a real constraint of the model. It 497 may be a constraint generated by a branching decision (a constraint whose 498 goal is to restrict the search space), a symmetry breaking constraint (a 499 constraint that does restrict the search space, but in a way that cannot 500 have an impact on the quality of the solutions in the subtree), or an 501 inferred constraint that, while having no semantic value to the model (it 502 does not restrict the set of solutions), is worth having because we 503 believe it may strengthen the propagation. In these cases, it happens 504 that the constraint is added during the search (i.e., with state() == 505 IN_SEARCH or state() == IN_ROOT_NODE). When a constraint is 506 added during a search, it applies only to the subtree of the search tree 507 rooted at the current node, and will be automatically removed by 508 backtracking. 509 510 This method does not take ownership of the constraint. If the constraint 511 has been created by any factory method (Solver::MakeXXX), it will 512 automatically be deleted. However, power users who implement their own 513 constraints should do: solver.AddConstraint(solver.RevAlloc(new 514 MyConstraint(...)); 515 """ 516 return _pywrapcp.Solver_AddConstraint(self, c)
Adds the constraint 'c' to the model.
After calling this method, and until there is a backtrack that undoes the addition, any assignment of variables to values must satisfy the given constraint in order to be considered feasible. There are two fairly different use cases:
the most common use case is modeling: the given constraint is really part of the problem that the user is trying to solve. In this use case, AddConstraint is called outside of search (i.e., with state() == OUTSIDE_SEARCH). Most users should only use AddConstraint in this way. In this case, the constraint will belong to the model forever: it cannot be removed by backtracking.
a rarer use case is that 'c' is not a real constraint of the model. It may be a constraint generated by a branching decision (a constraint whose goal is to restrict the search space), a symmetry breaking constraint (a constraint that does restrict the search space, but in a way that cannot have an impact on the quality of the solutions in the subtree), or an inferred constraint that, while having no semantic value to the model (it does not restrict the set of solutions), is worth having because we believe it may strengthen the propagation. In these cases, it happens that the constraint is added during the search (i.e., with state() == IN_SEARCH or state() == IN_ROOT_NODE). When a constraint is added during a search, it applies only to the subtree of the search tree rooted at the current node, and will be automatically removed by backtracking.
This method does not take ownership of the constraint. If the constraint has been created by any factory method (Solver::MakeXXX), it will automatically be deleted. However, power users who implement their own constraints should do: solver.AddConstraint(solver.RevAlloc(new MyConstraint(...));
518 def Solve(self, *args): 519 r""" 520 Solves the problem using the given DecisionBuilder and returns true if a 521 solution was found and accepted. 522 523 These methods are the ones most users should use to search for a solution. 524 Note that the definition of 'solution' is subtle. A solution here is 525 defined as a leaf of the search tree with respect to the given decision 526 builder for which there is no failure. What this means is that, contrary 527 to intuition, a solution may not have all variables of the model bound. 528 It is the responsibility of the decision builder to keep returning 529 decisions until all variables are indeed bound. The most extreme 530 counterexample is calling Solve with a trivial decision builder whose 531 Next() method always returns nullptr. In this case, Solve immediately 532 returns 'true', since not assigning any variable to any value is a 533 solution, unless the root node propagation discovers that the model is 534 infeasible. 535 536 This function must be called either from outside of search, 537 or from within the Next() method of a decision builder. 538 539 Solve will terminate whenever any of the following event arise: 540 A search monitor asks the solver to terminate the search by calling 541 solver()->FinishCurrentSearch(). 542 A solution is found that is accepted by all search monitors, and none of 543 the search monitors decides to search for another one. 544 545 Upon search termination, there will be a series of backtracks all the way 546 to the top level. This means that a user cannot expect to inspect the 547 solution by querying variables after a call to Solve(): all the 548 information will be lost. In order to do something with the solution, the 549 user must either: 550 551 Use a search monitor that can process such a leaf. See, in particular, 552 the SolutionCollector class. 553 Do not use Solve. Instead, use the more fine-grained approach using 554 methods NewSearch(...), NextSolution(), and EndSearch(). 555 556 :type db: :py:class:`DecisionBuilder` 557 :param db: The decision builder that will generate the search tree. 558 :type monitors: std::vector< operations_research::SearchMonitor * > 559 :param monitors: A vector of search monitors that will be notified of 560 various events during the search. In their reaction to these events, such 561 monitors may influence the search. 562 """ 563 return _pywrapcp.Solver_Solve(self, *args)
Solves the problem using the given DecisionBuilder and returns true if a solution was found and accepted.
These methods are the ones most users should use to search for a solution. Note that the definition of 'solution' is subtle. A solution here is defined as a leaf of the search tree with respect to the given decision builder for which there is no failure. What this means is that, contrary to intuition, a solution may not have all variables of the model bound. It is the responsibility of the decision builder to keep returning decisions until all variables are indeed bound. The most extreme counterexample is calling Solve with a trivial decision builder whose Next() method always returns nullptr. In this case, Solve immediately returns 'true', since not assigning any variable to any value is a solution, unless the root node propagation discovers that the model is infeasible.
This function must be called either from outside of search, or from within the Next() method of a decision builder.
Solve will terminate whenever any of the following event arise: A search monitor asks the solver to terminate the search by calling solver()->FinishCurrentSearch(). A solution is found that is accepted by all search monitors, and none of the search monitors decides to search for another one.
Upon search termination, there will be a series of backtracks all the way to the top level. This means that a user cannot expect to inspect the solution by querying variables after a call to Solve(): all the information will be lost. In order to do something with the solution, the user must either:
Use a search monitor that can process such a leaf. See, in particular, the SolutionCollector class. Do not use Solve. Instead, use the more fine-grained approach using methods NewSearch(...), NextSolution(), and EndSearch().
:type db: DecisionBuilder
:param db: The decision builder that will generate the search tree.
:type monitors: std::vector< operations_research::SearchMonitor * >
:param monitors: A vector of search monitors that will be notified of
various events during the search. In their reaction to these events, such
monitors may influence the search.
565 def NewSearch(self, *args): 566 r""" 567 Decomposed search. 568 The code for a top level search should look like 569 solver->NewSearch(db); 570 while (solver->NextSolution()) { 571 .. use the current solution 572 } 573 solver()->EndSearch(); 574 """ 575 return _pywrapcp.Solver_NewSearch(self, *args)
Decomposed search. The code for a top level search should look like solver->NewSearch(db); while (solver->NextSolution()) { .. use the current solution } solver()->EndSearch();
586 def SolveAndCommit(self, *args): 587 r""" 588 SolveAndCommit using a decision builder and up to three 589 search monitors, usually one for the objective, one for the limits 590 and one to collect solutions. 591 592 The difference between a SolveAndCommit() and a Solve() method 593 call is the fact that SolveAndCommit will not backtrack all 594 modifications at the end of the search. This method is only 595 usable during the Next() method of a decision builder. 596 """ 597 return _pywrapcp.Solver_SolveAndCommit(self, *args)
SolveAndCommit using a decision builder and up to three search monitors, usually one for the objective, one for the limits and one to collect solutions.
The difference between a SolveAndCommit() and a Solve() method call is the fact that SolveAndCommit will not backtrack all modifications at the end of the search. This method is only usable during the Next() method of a decision builder.
599 def CheckAssignment(self, solution): 600 r"""Checks whether the given assignment satisfies all relevant constraints.""" 601 return _pywrapcp.Solver_CheckAssignment(self, solution)
Checks whether the given assignment satisfies all relevant constraints.
603 def CheckConstraint(self, ct): 604 r""" 605 Checks whether adding this constraint will lead to an immediate 606 failure. It will return false if the model is already inconsistent, or if 607 adding the constraint makes it inconsistent. 608 """ 609 return _pywrapcp.Solver_CheckConstraint(self, ct)
Checks whether adding this constraint will lead to an immediate failure. It will return false if the model is already inconsistent, or if adding the constraint makes it inconsistent.
611 def Fail(self): 612 r"""Abandon the current branch in the search tree. A backtrack will follow.""" 613 return _pywrapcp.Solver_Fail(self)
Abandon the current branch in the search tree. A backtrack will follow.
615 @staticmethod 616 def MemoryUsage(): 617 r"""Current memory usage in bytes""" 618 return _pywrapcp.Solver_MemoryUsage()
Current memory usage in bytes
620 def WallTime(self): 621 r""" 622 Deprecated: Use Now() instead. 623 Time elapsed, in ms since the creation of the solver. 624 """ 625 return _pywrapcp.Solver_WallTime(self)
Deprecated: Use Now() instead. Time elapsed, in ms since the creation of the solver.
627 def Branches(self): 628 r"""The number of branches explored since the creation of the solver.""" 629 return _pywrapcp.Solver_Branches(self)
The number of branches explored since the creation of the solver.
631 def Solutions(self): 632 r"""The number of solutions found since the start of the search.""" 633 return _pywrapcp.Solver_Solutions(self)
The number of solutions found since the start of the search.
635 def Failures(self): 636 r"""The number of failures encountered since the creation of the solver.""" 637 return _pywrapcp.Solver_Failures(self)
The number of failures encountered since the creation of the solver.
639 def AcceptedNeighbors(self): 640 r"""The number of accepted neighbors.""" 641 return _pywrapcp.Solver_AcceptedNeighbors(self)
The number of accepted neighbors.
643 def Stamp(self): 644 r""" 645 The stamp indicates how many moves in the search tree we have performed. 646 It is useful to detect if we need to update same lazy structures. 647 """ 648 return _pywrapcp.Solver_Stamp(self)
The stamp indicates how many moves in the search tree we have performed. It is useful to detect if we need to update same lazy structures.
650 def FailStamp(self): 651 r"""The fail_stamp() is incremented after each backtrack.""" 652 return _pywrapcp.Solver_FailStamp(self)
The fail_stamp() is incremented after each backtrack.
654 def IntVar(self, *args): 655 r""" 656 *Overload 1:* 657 MakeIntVar will create the best range based int var for the bounds given. 658 659 | 660 661 *Overload 2:* 662 MakeIntVar will create a variable with the given sparse domain. 663 664 | 665 666 *Overload 3:* 667 MakeIntVar will create a variable with the given sparse domain. 668 669 | 670 671 *Overload 4:* 672 MakeIntVar will create the best range based int var for the bounds given. 673 674 | 675 676 *Overload 5:* 677 MakeIntVar will create a variable with the given sparse domain. 678 679 | 680 681 *Overload 6:* 682 MakeIntVar will create a variable with the given sparse domain. 683 """ 684 return _pywrapcp.Solver_IntVar(self, *args)
Overload 1: MakeIntVar will create the best range based int var for the bounds given.
|
Overload 2: MakeIntVar will create a variable with the given sparse domain.
|
Overload 3: MakeIntVar will create a variable with the given sparse domain.
|
Overload 4: MakeIntVar will create the best range based int var for the bounds given.
|
Overload 5: MakeIntVar will create a variable with the given sparse domain.
|
Overload 6: MakeIntVar will create a variable with the given sparse domain.
686 def BoolVar(self, *args): 687 r""" 688 *Overload 1:* 689 MakeBoolVar will create a variable with a {0, 1} domain. 690 691 | 692 693 *Overload 2:* 694 MakeBoolVar will create a variable with a {0, 1} domain. 695 """ 696 return _pywrapcp.Solver_BoolVar(self, *args)
Overload 1: MakeBoolVar will create a variable with a {0, 1} domain.
|
Overload 2: MakeBoolVar will create a variable with a {0, 1} domain.
698 def IntConst(self, *args): 699 r""" 700 *Overload 1:* 701 IntConst will create a constant expression. 702 703 | 704 705 *Overload 2:* 706 IntConst will create a constant expression. 707 """ 708 return _pywrapcp.Solver_IntConst(self, *args)
Overload 1: IntConst will create a constant expression.
|
Overload 2: IntConst will create a constant expression.
714 def ScalProd(self, *args): 715 r""" 716 *Overload 1:* 717 scalar product 718 719 | 720 721 *Overload 2:* 722 scalar product 723 """ 724 return _pywrapcp.Solver_ScalProd(self, *args)
Overload 1: scalar product
|
Overload 2: scalar product
726 def MonotonicElement(self, values, increasing, index): 727 r""" 728 Function based element. The constraint takes ownership of the 729 callback. The callback must be monotonic. It must be able to 730 cope with any possible value in the domain of 'index' 731 (potentially negative ones too). Furtermore, monotonicity is not 732 checked. Thus giving a non-monotonic function, or specifying an 733 incorrect increasing parameter will result in undefined behavior. 734 """ 735 return _pywrapcp.Solver_MonotonicElement(self, values, increasing, index)
Function based element. The constraint takes ownership of the callback. The callback must be monotonic. It must be able to cope with any possible value in the domain of 'index' (potentially negative ones too). Furtermore, monotonicity is not checked. Thus giving a non-monotonic function, or specifying an incorrect increasing parameter will result in undefined behavior.
737 def Element(self, *args): 738 r""" 739 *Overload 1:* 740 values[index] 741 742 | 743 744 *Overload 2:* 745 values[index] 746 747 | 748 749 *Overload 3:* 750 Function-based element. The constraint takes ownership of the 751 callback. The callback must be able to cope with any possible 752 value in the domain of 'index' (potentially negative ones too). 753 754 | 755 756 *Overload 4:* 757 2D version of function-based element expression, values(expr1, expr2). 758 759 | 760 761 *Overload 5:* 762 vars[expr] 763 """ 764 return _pywrapcp.Solver_Element(self, *args)
Overload 1: values[index]
|
Overload 2: values[index]
|
Overload 3: Function-based element. The constraint takes ownership of the callback. The callback must be able to cope with any possible value in the domain of 'index' (potentially negative ones too).
|
Overload 4: 2D version of function-based element expression, values(expr1, expr2).
|
Overload 5: vars[expr]
766 def IndexExpression(self, vars, value): 767 r""" 768 Returns the expression expr such that vars[expr] == value. 769 It assumes that vars are all different. 770 """ 771 return _pywrapcp.Solver_IndexExpression(self, vars, value)
Returns the expression expr such that vars[expr] == value. It assumes that vars are all different.
773 def Min(self, *args): 774 r""" 775 *Overload 1:* 776 std::min(vars) 777 778 | 779 780 *Overload 2:* 781 std::min (left, right) 782 783 | 784 785 *Overload 3:* 786 std::min(expr, value) 787 788 | 789 790 *Overload 4:* 791 std::min(expr, value) 792 """ 793 return _pywrapcp.Solver_Min(self, *args)
Overload 1: std::min(vars)
|
Overload 2: std::min (left, right)
|
Overload 3: std::min(expr, value)
|
Overload 4: std::min(expr, value)
795 def Max(self, *args): 796 r""" 797 *Overload 1:* 798 std::max(vars) 799 800 | 801 802 *Overload 2:* 803 std::max(left, right) 804 805 | 806 807 *Overload 3:* 808 std::max(expr, value) 809 810 | 811 812 *Overload 4:* 813 std::max(expr, value) 814 """ 815 return _pywrapcp.Solver_Max(self, *args)
Overload 1: std::max(vars)
|
Overload 2: std::max(left, right)
|
Overload 3: std::max(expr, value)
|
Overload 4: std::max(expr, value)
817 def ConvexPiecewiseExpr(self, expr, early_cost, early_date, late_date, late_cost): 818 r"""Convex piecewise function.""" 819 return _pywrapcp.Solver_ConvexPiecewiseExpr(self, expr, early_cost, early_date, late_date, late_cost)
Convex piecewise function.
821 def SemiContinuousExpr(self, expr, fixed_charge, step): 822 r""" 823 Semi continuous Expression (x <= 0 -> f(x) = 0; x > 0 -> f(x) = ax + b) 824 a >= 0 and b >= 0 825 """ 826 return _pywrapcp.Solver_SemiContinuousExpr(self, expr, fixed_charge, step)
Semi continuous Expression (x <= 0 -> f(x) = 0; x > 0 -> f(x) = ax + b) a >= 0 and b >= 0
828 def ConditionalExpression(self, condition, expr, unperformed_value): 829 r"""Conditional Expr condition ? expr : unperformed_value""" 830 return _pywrapcp.Solver_ConditionalExpression(self, condition, expr, unperformed_value)
Conditional Expr condition ? expr : unperformed_value
832 def TrueConstraint(self): 833 r"""This constraint always succeeds.""" 834 return _pywrapcp.Solver_TrueConstraint(self)
This constraint always succeeds.
836 def FalseConstraint(self, *args): 837 r"""This constraint always fails.""" 838 return _pywrapcp.Solver_FalseConstraint(self, *args)
This constraint always fails.
840 def IsEqualCstCt(self, var, value, boolvar): 841 r"""boolvar == (var == value)""" 842 return _pywrapcp.Solver_IsEqualCstCt(self, var, value, boolvar)
boolvar == (var == value)
844 def IsEqualCstVar(self, var, value): 845 r"""status var of (var == value)""" 846 return _pywrapcp.Solver_IsEqualCstVar(self, var, value)
status var of (var == value)
848 def IsEqualCt(self, v1, v2, b): 849 r"""b == (v1 == v2)""" 850 return _pywrapcp.Solver_IsEqualCt(self, v1, v2, b)
b == (v1 == v2)
852 def IsEqualVar(self, v1, v2): 853 r"""status var of (v1 == v2)""" 854 return _pywrapcp.Solver_IsEqualVar(self, v1, v2)
status var of (v1 == v2)
856 def IsDifferentCstCt(self, var, value, boolvar): 857 r"""boolvar == (var != value)""" 858 return _pywrapcp.Solver_IsDifferentCstCt(self, var, value, boolvar)
boolvar == (var != value)
860 def IsDifferentCstVar(self, var, value): 861 r"""status var of (var != value)""" 862 return _pywrapcp.Solver_IsDifferentCstVar(self, var, value)
status var of (var != value)
864 def IsDifferentVar(self, v1, v2): 865 r"""status var of (v1 != v2)""" 866 return _pywrapcp.Solver_IsDifferentVar(self, v1, v2)
status var of (v1 != v2)
868 def IsDifferentCt(self, v1, v2, b): 869 r"""b == (v1 != v2)""" 870 return _pywrapcp.Solver_IsDifferentCt(self, v1, v2, b)
b == (v1 != v2)
872 def IsLessOrEqualCstCt(self, var, value, boolvar): 873 r"""boolvar == (var <= value)""" 874 return _pywrapcp.Solver_IsLessOrEqualCstCt(self, var, value, boolvar)
boolvar == (var <= value)
876 def IsLessOrEqualCstVar(self, var, value): 877 r"""status var of (var <= value)""" 878 return _pywrapcp.Solver_IsLessOrEqualCstVar(self, var, value)
status var of (var <= value)
880 def IsLessOrEqualVar(self, left, right): 881 r"""status var of (left <= right)""" 882 return _pywrapcp.Solver_IsLessOrEqualVar(self, left, right)
status var of (left <= right)
884 def IsLessOrEqualCt(self, left, right, b): 885 r"""b == (left <= right)""" 886 return _pywrapcp.Solver_IsLessOrEqualCt(self, left, right, b)
b == (left <= right)
888 def IsGreaterOrEqualCstCt(self, var, value, boolvar): 889 r"""boolvar == (var >= value)""" 890 return _pywrapcp.Solver_IsGreaterOrEqualCstCt(self, var, value, boolvar)
boolvar == (var >= value)
892 def IsGreaterOrEqualCstVar(self, var, value): 893 r"""status var of (var >= value)""" 894 return _pywrapcp.Solver_IsGreaterOrEqualCstVar(self, var, value)
status var of (var >= value)
896 def IsGreaterOrEqualVar(self, left, right): 897 r"""status var of (left >= right)""" 898 return _pywrapcp.Solver_IsGreaterOrEqualVar(self, left, right)
status var of (left >= right)
900 def IsGreaterOrEqualCt(self, left, right, b): 901 r"""b == (left >= right)""" 902 return _pywrapcp.Solver_IsGreaterOrEqualCt(self, left, right, b)
b == (left >= right)
904 def IsGreaterCstCt(self, v, c, b): 905 r"""b == (v > c)""" 906 return _pywrapcp.Solver_IsGreaterCstCt(self, v, c, b)
b == (v > c)
908 def IsGreaterCstVar(self, var, value): 909 r"""status var of (var > value)""" 910 return _pywrapcp.Solver_IsGreaterCstVar(self, var, value)
status var of (var > value)
912 def IsGreaterVar(self, left, right): 913 r"""status var of (left > right)""" 914 return _pywrapcp.Solver_IsGreaterVar(self, left, right)
status var of (left > right)
916 def IsGreaterCt(self, left, right, b): 917 r"""b == (left > right)""" 918 return _pywrapcp.Solver_IsGreaterCt(self, left, right, b)
b == (left > right)
920 def IsLessCstCt(self, v, c, b): 921 r"""b == (v < c)""" 922 return _pywrapcp.Solver_IsLessCstCt(self, v, c, b)
b == (v < c)
924 def IsLessCstVar(self, var, value): 925 r"""status var of (var < value)""" 926 return _pywrapcp.Solver_IsLessCstVar(self, var, value)
status var of (var < value)
928 def IsLessVar(self, left, right): 929 r"""status var of (left < right)""" 930 return _pywrapcp.Solver_IsLessVar(self, left, right)
status var of (left < right)
932 def IsLessCt(self, left, right, b): 933 r"""b == (left < right)""" 934 return _pywrapcp.Solver_IsLessCt(self, left, right, b)
b == (left < right)
936 def SumLessOrEqual(self, vars, cst): 937 r"""Variation on arrays.""" 938 return _pywrapcp.Solver_SumLessOrEqual(self, vars, cst)
Variation on arrays.
964 def AbsEquality(self, var, abs_var): 965 r"""Creates the constraint abs(var) == abs_var.""" 966 return _pywrapcp.Solver_AbsEquality(self, var, abs_var)
Creates the constraint abs(var) == abs_var.
968 def IndexOfConstraint(self, vars, index, target): 969 r""" 970 This constraint is a special case of the element constraint with 971 an array of integer variables, where the variables are all 972 different and the index variable is constrained such that 973 vars[index] == target. 974 """ 975 return _pywrapcp.Solver_IndexOfConstraint(self, vars, index, target)
This constraint is a special case of the element constraint with an array of integer variables, where the variables are all different and the index variable is constrained such that vars[index] == target.
977 def ConstraintInitialPropagateCallback(self, ct): 978 r""" 979 This method is a specialized case of the MakeConstraintDemon 980 method to call the InitiatePropagate of the constraint 'ct'. 981 """ 982 return _pywrapcp.Solver_ConstraintInitialPropagateCallback(self, ct)
This method is a specialized case of the MakeConstraintDemon method to call the InitiatePropagate of the constraint 'ct'.
984 def DelayedConstraintInitialPropagateCallback(self, ct): 985 r""" 986 This method is a specialized case of the MakeConstraintDemon 987 method to call the InitiatePropagate of the constraint 'ct' with 988 low priority. 989 """ 990 return _pywrapcp.Solver_DelayedConstraintInitialPropagateCallback(self, ct)
This method is a specialized case of the MakeConstraintDemon method to call the InitiatePropagate of the constraint 'ct' with low priority.
992 def ClosureDemon(self, closure): 993 r"""Creates a demon from a closure.""" 994 return _pywrapcp.Solver_ClosureDemon(self, closure)
Creates a demon from a closure.
996 def BetweenCt(self, expr, l, u): 997 r"""(l <= expr <= u)""" 998 return _pywrapcp.Solver_BetweenCt(self, expr, l, u)
(l <= expr <= u)
1000 def IsBetweenCt(self, expr, l, u, b): 1001 r"""b == (l <= expr <= u)""" 1002 return _pywrapcp.Solver_IsBetweenCt(self, expr, l, u, b)
b == (l <= expr <= u)
1007 def MemberCt(self, *args): 1008 r""" 1009 expr in set. Propagation is lazy, i.e. this constraint does not 1010 creates holes in the domain of the variable. 1011 """ 1012 return _pywrapcp.Solver_MemberCt(self, *args)
expr in set. Propagation is lazy, i.e. this constraint does not creates holes in the domain of the variable.
1014 def NotMemberCt(self, *args): 1015 r""" 1016 *Overload 1:* 1017 expr not in set. 1018 1019 | 1020 1021 *Overload 2:* 1022 expr should not be in the list of forbidden intervals [start[i]..end[i]]. 1023 1024 | 1025 1026 *Overload 3:* 1027 expr should not be in the list of forbidden intervals [start[i]..end[i]]. 1028 """ 1029 return _pywrapcp.Solver_NotMemberCt(self, *args)
Overload 1: expr not in set.
|
Overload 2: expr should not be in the list of forbidden intervals [start[i]..end[i]].
|
Overload 3: expr should not be in the list of forbidden intervals [start[i]..end[i]].
1031 def IsMemberCt(self, *args): 1032 r"""boolvar == (expr in set)""" 1033 return _pywrapcp.Solver_IsMemberCt(self, *args)
boolvar == (expr in set)
1038 def Count(self, *args): 1039 r""" 1040 *Overload 1:* 1041 |{i | vars[i] == value}| == max_count 1042 1043 | 1044 1045 *Overload 2:* 1046 |{i | vars[i] == value}| == max_count 1047 """ 1048 return _pywrapcp.Solver_Count(self, *args)
Overload 1: |{i | vars[i] == value}| == max_count
|
Overload 2: |{i | vars[i] == value}| == max_count
1050 def Distribute(self, *args): 1051 r""" 1052 *Overload 1:* 1053 Aggregated version of count: |{i | v[i] == values[j]}| == cards[j] 1054 1055 | 1056 1057 *Overload 2:* 1058 Aggregated version of count: |{i | v[i] == values[j]}| == cards[j] 1059 1060 | 1061 1062 *Overload 3:* 1063 Aggregated version of count: |{i | v[i] == j}| == cards[j] 1064 1065 | 1066 1067 *Overload 4:* 1068 Aggregated version of count with bounded cardinalities: 1069 forall j in 0 .. card_size - 1: card_min <= |{i | v[i] == j}| <= card_max 1070 1071 | 1072 1073 *Overload 5:* 1074 Aggregated version of count with bounded cardinalities: 1075 forall j in 0 .. card_size - 1: 1076 card_min[j] <= |{i | v[i] == j}| <= card_max[j] 1077 1078 | 1079 1080 *Overload 6:* 1081 Aggregated version of count with bounded cardinalities: 1082 forall j in 0 .. card_size - 1: 1083 card_min[j] <= |{i | v[i] == j}| <= card_max[j] 1084 1085 | 1086 1087 *Overload 7:* 1088 Aggregated version of count with bounded cardinalities: 1089 forall j in 0 .. card_size - 1: 1090 card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j] 1091 1092 | 1093 1094 *Overload 8:* 1095 Aggregated version of count with bounded cardinalities: 1096 forall j in 0 .. card_size - 1: 1097 card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j] 1098 """ 1099 return _pywrapcp.Solver_Distribute(self, *args)
Overload 1: Aggregated version of count: |{i | v[i] == values[j]}| == cards[j]
|
Overload 2: Aggregated version of count: |{i | v[i] == values[j]}| == cards[j]
|
Overload 3: Aggregated version of count: |{i | v[i] == j}| == cards[j]
|
Overload 4: Aggregated version of count with bounded cardinalities: forall j in 0 .. card_size - 1: card_min <= |{i | v[i] == j}| <= card_max
|
Overload 5: Aggregated version of count with bounded cardinalities: forall j in 0 .. card_size - 1: card_min[j] <= |{i | v[i] == j}| <= card_max[j]
|
Overload 6: Aggregated version of count with bounded cardinalities: forall j in 0 .. card_size - 1: card_min[j] <= |{i | v[i] == j}| <= card_max[j]
|
Overload 7: Aggregated version of count with bounded cardinalities: forall j in 0 .. card_size - 1: card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j]
|
Overload 8: Aggregated version of count with bounded cardinalities: forall j in 0 .. card_size - 1: card_min[j] <= |{i | v[i] == values[j]}| <= card_max[j]
1101 def Deviation(self, vars, deviation_var, total_sum): 1102 r""" 1103 Deviation constraint: 1104 sum_i |n * vars[i] - total_sum| <= deviation_var and 1105 sum_i vars[i] == total_sum 1106 n = #vars 1107 """ 1108 return _pywrapcp.Solver_Deviation(self, vars, deviation_var, total_sum)
Deviation constraint: sum_i |n * vars[i] - total_sum| <= deviation_var and sum_i vars[i] == total_sum n = #vars
1110 def AllDifferent(self, *args): 1111 r""" 1112 *Overload 1:* 1113 All variables are pairwise different. This corresponds to the 1114 stronger version of the propagation algorithm. 1115 1116 | 1117 1118 *Overload 2:* 1119 All variables are pairwise different. If 'stronger_propagation' 1120 is true, stronger, and potentially slower propagation will 1121 occur. This API will be deprecated in the future. 1122 """ 1123 return _pywrapcp.Solver_AllDifferent(self, *args)
Overload 1: All variables are pairwise different. This corresponds to the stronger version of the propagation algorithm.
|
Overload 2: All variables are pairwise different. If 'stronger_propagation' is true, stronger, and potentially slower propagation will occur. This API will be deprecated in the future.
1125 def AllDifferentExcept(self, vars, escape_value): 1126 r""" 1127 All variables are pairwise different, unless they are assigned to 1128 the escape value. 1129 """ 1130 return _pywrapcp.Solver_AllDifferentExcept(self, vars, escape_value)
All variables are pairwise different, unless they are assigned to the escape value.
1132 def SortingConstraint(self, vars, sorted): 1133 r""" 1134 Creates a constraint binding the arrays of variables "vars" and 1135 "sorted_vars": sorted_vars[0] must be equal to the minimum of all 1136 variables in vars, and so on: the value of sorted_vars[i] must be 1137 equal to the i-th value of variables invars. 1138 1139 This constraint propagates in both directions: from "vars" to 1140 "sorted_vars" and vice-versa. 1141 1142 Behind the scenes, this constraint maintains that: 1143 - sorted is always increasing. 1144 - whatever the values of vars, there exists a permutation that 1145 injects its values into the sorted variables. 1146 1147 For more info, please have a look at: 1148 https://mpi-inf.mpg.de/~mehlhorn/ftp/Mehlhorn-Thiel.pdf 1149 """ 1150 return _pywrapcp.Solver_SortingConstraint(self, vars, sorted)
Creates a constraint binding the arrays of variables "vars" and "sorted_vars": sorted_vars[0] must be equal to the minimum of all variables in vars, and so on: the value of sorted_vars[i] must be equal to the i-th value of variables invars.
This constraint propagates in both directions: from "vars" to "sorted_vars" and vice-versa.
Behind the scenes, this constraint maintains that:
- sorted is always increasing.
- whatever the values of vars, there exists a permutation that injects its values into the sorted variables.
For more info, please have a look at: https://mpi-inf.mpg.de/~mehlhorn/ftp/Mehlhorn-Thiel.pdf
1152 def LexicalLess(self, left, right): 1153 r""" 1154 Creates a constraint that enforces that left is lexicographically less 1155 than right. 1156 """ 1157 return _pywrapcp.Solver_LexicalLess(self, left, right)
Creates a constraint that enforces that left is lexicographically less than right.
1159 def LexicalLessOrEqual(self, left, right): 1160 r""" 1161 Creates a constraint that enforces that left is lexicographically less 1162 than or equal to right. 1163 """ 1164 return _pywrapcp.Solver_LexicalLessOrEqual(self, left, right)
Creates a constraint that enforces that left is lexicographically less than or equal to right.
1166 def InversePermutationConstraint(self, left, right): 1167 r""" 1168 Creates a constraint that enforces that 'left' and 'right' both 1169 represent permutations of [0..left.size()-1], and that 'right' is 1170 the inverse permutation of 'left', i.e. for all i in 1171 [0..left.size()-1], right[left[i]] = i. 1172 """ 1173 return _pywrapcp.Solver_InversePermutationConstraint(self, left, right)
Creates a constraint that enforces that 'left' and 'right' both represent permutations of [0..left.size()-1], and that 'right' is the inverse permutation of 'left', i.e. for all i in [0..left.size()-1], right[left[i]] = i.
1175 def NullIntersect(self, first_vars, second_vars): 1176 r""" 1177 Creates a constraint that states that all variables in the first 1178 vector are different from all variables in the second 1179 group. Thus the set of values in the first vector does not 1180 intersect with the set of values in the second vector. 1181 """ 1182 return _pywrapcp.Solver_NullIntersect(self, first_vars, second_vars)
Creates a constraint that states that all variables in the first vector are different from all variables in the second group. Thus the set of values in the first vector does not intersect with the set of values in the second vector.
1184 def NullIntersectExcept(self, first_vars, second_vars, escape_value): 1185 r""" 1186 Creates a constraint that states that all variables in the first 1187 vector are different from all variables from the second group, 1188 unless they are assigned to the escape value. Thus the set of 1189 values in the first vector minus the escape value does not 1190 intersect with the set of values in the second vector. 1191 """ 1192 return _pywrapcp.Solver_NullIntersectExcept(self, first_vars, second_vars, escape_value)
Creates a constraint that states that all variables in the first vector are different from all variables from the second group, unless they are assigned to the escape value. Thus the set of values in the first vector minus the escape value does not intersect with the set of values in the second vector.
1194 def Circuit(self, nexts): 1195 r"""Force the "nexts" variable to create a complete Hamiltonian path.""" 1196 return _pywrapcp.Solver_Circuit(self, nexts)
Force the "nexts" variable to create a complete Hamiltonian path.
1198 def SubCircuit(self, nexts): 1199 r""" 1200 Force the "nexts" variable to create a complete Hamiltonian path 1201 for those that do not loop upon themselves. 1202 """ 1203 return _pywrapcp.Solver_SubCircuit(self, nexts)
Force the "nexts" variable to create a complete Hamiltonian path for those that do not loop upon themselves.
1205 def DelayedPathCumul(self, nexts, active, cumuls, transits): 1206 r""" 1207 Delayed version of the same constraint: propagation on the nexts variables 1208 is delayed until all constraints have propagated. 1209 """ 1210 return _pywrapcp.Solver_DelayedPathCumul(self, nexts, active, cumuls, transits)
Delayed version of the same constraint: propagation on the nexts variables is delayed until all constraints have propagated.
1212 def PathCumul(self, *args): 1213 r""" 1214 *Overload 1:* 1215 Creates a constraint which accumulates values along a path such that: 1216 cumuls[next[i]] = cumuls[i] + transits[i]. 1217 Active variables indicate if the corresponding next variable is active; 1218 this could be useful to model unperformed nodes in a routing problem. 1219 1220 | 1221 1222 *Overload 2:* 1223 Creates a constraint which accumulates values along a path such that: 1224 cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]). 1225 Active variables indicate if the corresponding next variable is active; 1226 this could be useful to model unperformed nodes in a routing problem. 1227 Ownership of transit_evaluator is taken and it must be a repeatable 1228 callback. 1229 1230 | 1231 1232 *Overload 3:* 1233 Creates a constraint which accumulates values along a path such that: 1234 cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]) + slacks[i]. 1235 Active variables indicate if the corresponding next variable is active; 1236 this could be useful to model unperformed nodes in a routing problem. 1237 Ownership of transit_evaluator is taken and it must be a repeatable 1238 callback. 1239 """ 1240 return _pywrapcp.Solver_PathCumul(self, *args)
Overload 1: Creates a constraint which accumulates values along a path such that: cumuls[next[i]] = cumuls[i] + transits[i]. Active variables indicate if the corresponding next variable is active; this could be useful to model unperformed nodes in a routing problem.
|
Overload 2: Creates a constraint which accumulates values along a path such that: cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]). Active variables indicate if the corresponding next variable is active; this could be useful to model unperformed nodes in a routing problem. Ownership of transit_evaluator is taken and it must be a repeatable callback.
|
Overload 3: Creates a constraint which accumulates values along a path such that: cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]) + slacks[i]. Active variables indicate if the corresponding next variable is active; this could be useful to model unperformed nodes in a routing problem. Ownership of transit_evaluator is taken and it must be a repeatable callback.
1242 def AllowedAssignments(self, *args): 1243 r""" 1244 *Overload 1:* 1245 This method creates a constraint where the graph of the relation 1246 between the variables is given in extension. There are 'arity' 1247 variables involved in the relation and the graph is given by a 1248 integer tuple set. 1249 1250 | 1251 1252 *Overload 2:* 1253 Compatibility layer for Python API. 1254 """ 1255 return _pywrapcp.Solver_AllowedAssignments(self, *args)
Overload 1: This method creates a constraint where the graph of the relation between the variables is given in extension. There are 'arity' variables involved in the relation and the graph is given by a integer tuple set.
|
Overload 2: Compatibility layer for Python API.
1257 def TransitionConstraint(self, *args): 1258 r""" 1259 *Overload 1:* 1260 This constraint create a finite automaton that will check the 1261 sequence of variables vars. It uses a transition table called 1262 'transition_table'. Each transition is a triple 1263 (current_state, variable_value, new_state). 1264 The initial state is given, and the set of accepted states is decribed 1265 by 'final_states'. These states are hidden inside the constraint. 1266 Only the transitions (i.e. the variables) are visible. 1267 1268 | 1269 1270 *Overload 2:* 1271 This constraint create a finite automaton that will check the 1272 sequence of variables vars. It uses a transition table called 1273 'transition_table'. Each transition is a triple 1274 (current_state, variable_value, new_state). 1275 The initial state is given, and the set of accepted states is decribed 1276 by 'final_states'. These states are hidden inside the constraint. 1277 Only the transitions (i.e. the variables) are visible. 1278 """ 1279 return _pywrapcp.Solver_TransitionConstraint(self, *args)
Overload 1: This constraint create a finite automaton that will check the sequence of variables vars. It uses a transition table called 'transition_table'. Each transition is a triple (current_state, variable_value, new_state). The initial state is given, and the set of accepted states is decribed by 'final_states'. These states are hidden inside the constraint. Only the transitions (i.e. the variables) are visible.
|
Overload 2: This constraint create a finite automaton that will check the sequence of variables vars. It uses a transition table called 'transition_table'. Each transition is a triple (current_state, variable_value, new_state). The initial state is given, and the set of accepted states is decribed by 'final_states'. These states are hidden inside the constraint. Only the transitions (i.e. the variables) are visible.
1281 def NonOverlappingBoxesConstraint(self, *args): 1282 r""" 1283 This constraint states that all the boxes must not overlap. 1284 The coordinates of box i are: 1285 (x_vars[i], y_vars[i]), 1286 (x_vars[i], y_vars[i] + y_size[i]), 1287 (x_vars[i] + x_size[i], y_vars[i]), 1288 (x_vars[i] + x_size[i], y_vars[i] + y_size[i]). 1289 The sizes must be non-negative. Boxes with a zero dimension can be 1290 pushed like any box. 1291 """ 1292 return _pywrapcp.Solver_NonOverlappingBoxesConstraint(self, *args)
This constraint states that all the boxes must not overlap.
The coordinates of box i are:
(x_vars[i], y_vars[i]), (x_vars[i], y_vars[i] + y_size[i]), (x_vars[i] + x_size[i], y_vars[i]), (x_vars[i] + x_size[i], y_vars[i] + y_size[i]).
The sizes must be non-negative. Boxes with a zero dimension can be pushed like any box.
1294 def Pack(self, vars, number_of_bins): 1295 r""" 1296 This constraint packs all variables onto 'number_of_bins' 1297 variables. For any given variable, a value of 'number_of_bins' 1298 indicates that the variable is not assigned to any bin. 1299 Dimensions, i.e., cumulative constraints on this packing, can be 1300 added directly from the pack class. 1301 """ 1302 return _pywrapcp.Solver_Pack(self, vars, number_of_bins)
This constraint packs all variables onto 'number_of_bins' variables. For any given variable, a value of 'number_of_bins' indicates that the variable is not assigned to any bin. Dimensions, i.e., cumulative constraints on this packing, can be added directly from the pack class.
1304 def FixedDurationIntervalVar(self, *args): 1305 r""" 1306 *Overload 1:* 1307 Creates an interval var with a fixed duration. The duration must 1308 be greater than 0. If optional is true, then the interval can be 1309 performed or unperformed. If optional is false, then the interval 1310 is always performed. 1311 1312 | 1313 1314 *Overload 2:* 1315 Creates a performed interval var with a fixed duration. The duration must 1316 be greater than 0. 1317 1318 | 1319 1320 *Overload 3:* 1321 Creates an interval var with a fixed duration, and performed_variable. 1322 The duration must be greater than 0. 1323 """ 1324 return _pywrapcp.Solver_FixedDurationIntervalVar(self, *args)
Overload 1: Creates an interval var with a fixed duration. The duration must be greater than 0. If optional is true, then the interval can be performed or unperformed. If optional is false, then the interval is always performed.
|
Overload 2: Creates a performed interval var with a fixed duration. The duration must be greater than 0.
|
Overload 3: Creates an interval var with a fixed duration, and performed_variable. The duration must be greater than 0.
1326 def FixedInterval(self, start, duration, name): 1327 r"""Creates a fixed and performed interval.""" 1328 return _pywrapcp.Solver_FixedInterval(self, start, duration, name)
Creates a fixed and performed interval.
1330 def IntervalVar(self, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name): 1331 r""" 1332 Creates an interval var by specifying the bounds on start, 1333 duration, and end. 1334 """ 1335 return _pywrapcp.Solver_IntervalVar(self, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name)
Creates an interval var by specifying the bounds on start, duration, and end.
1337 def MirrorInterval(self, interval_var): 1338 r""" 1339 Creates an interval var that is the mirror image of the given one, that 1340 is, the interval var obtained by reversing the axis. 1341 """ 1342 return _pywrapcp.Solver_MirrorInterval(self, interval_var)
Creates an interval var that is the mirror image of the given one, that is, the interval var obtained by reversing the axis.
1344 def FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset): 1345 r""" 1346 Creates an interval var with a fixed duration whose start is 1347 synchronized with the start of another interval, with a given 1348 offset. The performed status is also in sync with the performed 1349 status of the given interval variable. 1350 """ 1351 return _pywrapcp.Solver_FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset)
Creates an interval var with a fixed duration whose start is synchronized with the start of another interval, with a given offset. The performed status is also in sync with the performed status of the given interval variable.
1353 def FixedDurationStartSyncedOnEndIntervalVar(self, interval_var, duration, offset): 1354 r""" 1355 Creates an interval var with a fixed duration whose start is 1356 synchronized with the end of another interval, with a given 1357 offset. The performed status is also in sync with the performed 1358 status of the given interval variable. 1359 """ 1360 return _pywrapcp.Solver_FixedDurationStartSyncedOnEndIntervalVar(self, interval_var, duration, offset)
Creates an interval var with a fixed duration whose start is synchronized with the end of another interval, with a given offset. The performed status is also in sync with the performed status of the given interval variable.
1362 def FixedDurationEndSyncedOnStartIntervalVar(self, interval_var, duration, offset): 1363 r""" 1364 Creates an interval var with a fixed duration whose end is 1365 synchronized with the start of another interval, with a given 1366 offset. The performed status is also in sync with the performed 1367 status of the given interval variable. 1368 """ 1369 return _pywrapcp.Solver_FixedDurationEndSyncedOnStartIntervalVar(self, interval_var, duration, offset)
Creates an interval var with a fixed duration whose end is synchronized with the start of another interval, with a given offset. The performed status is also in sync with the performed status of the given interval variable.
1371 def FixedDurationEndSyncedOnEndIntervalVar(self, interval_var, duration, offset): 1372 r""" 1373 Creates an interval var with a fixed duration whose end is 1374 synchronized with the end of another interval, with a given 1375 offset. The performed status is also in sync with the performed 1376 status of the given interval variable. 1377 """ 1378 return _pywrapcp.Solver_FixedDurationEndSyncedOnEndIntervalVar(self, interval_var, duration, offset)
Creates an interval var with a fixed duration whose end is synchronized with the end of another interval, with a given offset. The performed status is also in sync with the performed status of the given interval variable.
1380 def IntervalRelaxedMin(self, interval_var): 1381 r""" 1382 Creates and returns an interval variable that wraps around the given one, 1383 relaxing the min start and end. Relaxing means making unbounded when 1384 optional. If the variable is non-optional, this method returns 1385 interval_var. 1386 1387 More precisely, such an interval variable behaves as follows: 1388 When the underlying must be performed, the returned interval variable 1389 behaves exactly as the underlying; 1390 When the underlying may or may not be performed, the returned interval 1391 variable behaves like the underlying, except that it is unbounded on 1392 the min side; 1393 When the underlying cannot be performed, the returned interval variable 1394 is of duration 0 and must be performed in an interval unbounded on 1395 both sides. 1396 1397 This is very useful to implement propagators that may only modify 1398 the start max or end max. 1399 """ 1400 return _pywrapcp.Solver_IntervalRelaxedMin(self, interval_var)
Creates and returns an interval variable that wraps around the given one, relaxing the min start and end. Relaxing means making unbounded when optional. If the variable is non-optional, this method returns interval_var.
More precisely, such an interval variable behaves as follows: When the underlying must be performed, the returned interval variable behaves exactly as the underlying; When the underlying may or may not be performed, the returned interval variable behaves like the underlying, except that it is unbounded on the min side; When the underlying cannot be performed, the returned interval variable is of duration 0 and must be performed in an interval unbounded on both sides.
This is very useful to implement propagators that may only modify the start max or end max.
1402 def IntervalRelaxedMax(self, interval_var): 1403 r""" 1404 Creates and returns an interval variable that wraps around the given one, 1405 relaxing the max start and end. Relaxing means making unbounded when 1406 optional. If the variable is non optional, this method returns 1407 interval_var. 1408 1409 More precisely, such an interval variable behaves as follows: 1410 When the underlying must be performed, the returned interval variable 1411 behaves exactly as the underlying; 1412 When the underlying may or may not be performed, the returned interval 1413 variable behaves like the underlying, except that it is unbounded on 1414 the max side; 1415 When the underlying cannot be performed, the returned interval variable 1416 is of duration 0 and must be performed in an interval unbounded on 1417 both sides. 1418 1419 This is very useful for implementing propagators that may only modify 1420 the start min or end min. 1421 """ 1422 return _pywrapcp.Solver_IntervalRelaxedMax(self, interval_var)
Creates and returns an interval variable that wraps around the given one, relaxing the max start and end. Relaxing means making unbounded when optional. If the variable is non optional, this method returns interval_var.
More precisely, such an interval variable behaves as follows: When the underlying must be performed, the returned interval variable behaves exactly as the underlying; When the underlying may or may not be performed, the returned interval variable behaves like the underlying, except that it is unbounded on the max side; When the underlying cannot be performed, the returned interval variable is of duration 0 and must be performed in an interval unbounded on both sides.
This is very useful for implementing propagators that may only modify the start min or end min.
1424 def TemporalDisjunction(self, *args): 1425 r""" 1426 *Overload 1:* 1427 This constraint implements a temporal disjunction between two 1428 interval vars t1 and t2. 'alt' indicates which alternative was 1429 chosen (alt == 0 is equivalent to t1 before t2). 1430 1431 | 1432 1433 *Overload 2:* 1434 This constraint implements a temporal disjunction between two 1435 interval vars. 1436 """ 1437 return _pywrapcp.Solver_TemporalDisjunction(self, *args)
Overload 1: This constraint implements a temporal disjunction between two interval vars t1 and t2. 'alt' indicates which alternative was chosen (alt == 0 is equivalent to t1 before t2).
|
Overload 2: This constraint implements a temporal disjunction between two interval vars.
1439 def DisjunctiveConstraint(self, intervals, name): 1440 r""" 1441 This constraint forces all interval vars into an non-overlapping 1442 sequence. Intervals with zero duration can be scheduled anywhere. 1443 """ 1444 return _pywrapcp.Solver_DisjunctiveConstraint(self, intervals, name)
This constraint forces all interval vars into an non-overlapping sequence. Intervals with zero duration can be scheduled anywhere.
1446 def Cumulative(self, *args): 1447 r""" 1448 *Overload 1:* 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 1451 capacity. 1452 1453 Intervals and demands should be vectors of equal size. 1454 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. 1458 1459 | 1460 1461 *Overload 2:* 1462 This constraint forces that, for any integer t, the sum of the demands 1463 corresponding to an interval containing t does not exceed the given 1464 capacity. 1465 1466 Intervals and demands should be vectors of equal size. 1467 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. 1471 1472 | 1473 1474 *Overload 3:* 1475 This constraint forces that, for any integer t, the sum of the demands 1476 corresponding to an interval containing t does not exceed the given 1477 capacity. 1478 1479 Intervals and demands should be vectors of equal size. 1480 1481 Demands should only contain non-negative values. Zero values are 1482 supported, and the corresponding intervals are filtered out, as they 1483 neither impact nor are impacted by this constraint. 1484 1485 | 1486 1487 *Overload 4:* 1488 This constraint enforces that, for any integer t, the sum of the demands 1489 corresponding to an interval containing t does not exceed the given 1490 capacity. 1491 1492 Intervals and demands should be vectors of equal size. 1493 1494 Demands should only contain non-negative values. Zero values are 1495 supported, and the corresponding intervals are filtered out, as they 1496 neither impact nor are impacted by this constraint. 1497 1498 | 1499 1500 *Overload 5:* 1501 This constraint enforces that, for any integer t, the sum of demands 1502 corresponding to an interval containing t does not exceed the given 1503 capacity. 1504 1505 Intervals and demands should be vectors of equal size. 1506 1507 Demands should be positive. 1508 1509 | 1510 1511 *Overload 6:* 1512 This constraint enforces that, for any integer t, the sum of demands 1513 corresponding to an interval containing t does not exceed the given 1514 capacity. 1515 1516 Intervals and demands should be vectors of equal size. 1517 1518 Demands should be positive. 1519 """ 1520 return _pywrapcp.Solver_Cumulative(self, *args)
Overload 1: This constraint forces that, for any integer t, the sum of the demands corresponding to an interval containing t does not exceed the given capacity.
Intervals and demands should be vectors of equal size.
Demands should only contain non-negative values. Zero values are supported, and the corresponding intervals are filtered out, as they neither impact nor are impacted by this constraint.
|
Overload 2: This constraint forces that, for any integer t, the sum of the demands corresponding to an interval containing t does not exceed the given capacity.
Intervals and demands should be vectors of equal size.
Demands should only contain non-negative values. Zero values are supported, and the corresponding intervals are filtered out, as they neither impact nor are impacted by this constraint.
|
Overload 3: This constraint forces that, for any integer t, the sum of the demands corresponding to an interval containing t does not exceed the given capacity.
Intervals and demands should be vectors of equal size.
Demands should only contain non-negative values. Zero values are supported, and the corresponding intervals are filtered out, as they neither impact nor are impacted by this constraint.
|
Overload 4: This constraint enforces that, for any integer t, the sum of the demands corresponding to an interval containing t does not exceed the given capacity.
Intervals and demands should be vectors of equal size.
Demands should only contain non-negative values. Zero values are supported, and the corresponding intervals are filtered out, as they neither impact nor are impacted by this constraint.
|
Overload 5: This constraint enforces that, for any integer t, the sum of demands corresponding to an interval containing t does not exceed the given capacity.
Intervals and demands should be vectors of equal size.
Demands should be positive.
|
Overload 6: This constraint enforces that, for any integer t, the sum of demands corresponding to an interval containing t does not exceed the given capacity.
Intervals and demands should be vectors of equal size.
Demands should be positive.
1522 def Cover(self, vars, target_var): 1523 r""" 1524 This constraint states that the target_var is the convex hull of 1525 the intervals. If none of the interval variables is performed, 1526 then the target var is unperformed too. Also, if the target 1527 variable is unperformed, then all the intervals variables are 1528 unperformed too. 1529 """ 1530 return _pywrapcp.Solver_Cover(self, vars, target_var)
This constraint states that the target_var is the convex hull of the intervals. If none of the interval variables is performed, then the target var is unperformed too. Also, if the target variable is unperformed, then all the intervals variables are unperformed too.
1532 def Assignment(self, *args): 1533 r""" 1534 *Overload 1:* 1535 This method creates an empty assignment. 1536 1537 | 1538 1539 *Overload 2:* 1540 This method creates an assignment which is a copy of 'a'. 1541 """ 1542 return _pywrapcp.Solver_Assignment(self, *args)
Overload 1: This method creates an empty assignment.
|
Overload 2: This method creates an assignment which is a copy of 'a'.
1544 def FirstSolutionCollector(self, *args): 1545 r""" 1546 *Overload 1:* 1547 Collect the first solution of the search. 1548 1549 | 1550 1551 *Overload 2:* 1552 Collect the first solution of the search. The variables will need to 1553 be added later. 1554 """ 1555 return _pywrapcp.Solver_FirstSolutionCollector(self, *args)
Overload 1: Collect the first solution of the search.
|
Overload 2: Collect the first solution of the search. The variables will need to be added later.
1557 def LastSolutionCollector(self, *args): 1558 r""" 1559 *Overload 1:* 1560 Collect the last solution of the search. 1561 1562 | 1563 1564 *Overload 2:* 1565 Collect the last solution of the search. The variables will need to 1566 be added later. 1567 """ 1568 return _pywrapcp.Solver_LastSolutionCollector(self, *args)
Overload 1: Collect the last solution of the search.
|
Overload 2: Collect the last solution of the search. The variables will need to be added later.
1570 def BestValueSolutionCollector(self, *args): 1571 r""" 1572 *Overload 1:* 1573 Collect the solution corresponding to the optimal value of the objective 1574 of 'assignment'; if 'assignment' does not have an objective no solution is 1575 collected. This collector only collects one solution corresponding to the 1576 best objective value (the first one found). 1577 1578 | 1579 1580 *Overload 2:* 1581 Collect the solution corresponding to the optimal value of the 1582 objective of the internal assignment; if this assignment does not have an 1583 objective no solution is collected. This collector only collects one 1584 solution corresponding to the best objective value (the first one found). 1585 The variables and objective(s) will need to be added later. 1586 """ 1587 return _pywrapcp.Solver_BestValueSolutionCollector(self, *args)
Overload 1: Collect the solution corresponding to the optimal value of the objective of 'assignment'; if 'assignment' does not have an objective no solution is collected. This collector only collects one solution corresponding to the best objective value (the first one found).
|
Overload 2: Collect the solution corresponding to the optimal value of the objective of the internal assignment; if this assignment does not have an objective no solution is collected. This collector only collects one solution corresponding to the best objective value (the first one found). The variables and objective(s) will need to be added later.
1589 def AllSolutionCollector(self, *args): 1590 r""" 1591 *Overload 1:* 1592 Collect all solutions of the search. 1593 1594 | 1595 1596 *Overload 2:* 1597 Collect all solutions of the search. The variables will need to 1598 be added later. 1599 """ 1600 return _pywrapcp.Solver_AllSolutionCollector(self, *args)
Overload 1: Collect all solutions of the search.
|
Overload 2: Collect all solutions of the search. The variables will need to be added later.
1602 def Minimize(self, v, step): 1603 r"""Creates a minimization objective.""" 1604 return _pywrapcp.Solver_Minimize(self, v, step)
Creates a minimization objective.
1606 def Maximize(self, v, step): 1607 r"""Creates a maximization objective.""" 1608 return _pywrapcp.Solver_Maximize(self, v, step)
Creates a maximization objective.
1610 def Optimize(self, maximize, v, step): 1611 r"""Creates a objective with a given sense (true = maximization).""" 1612 return _pywrapcp.Solver_Optimize(self, maximize, v, step)
Creates a objective with a given sense (true = maximization).
1614 def WeightedMinimize(self, *args): 1615 r""" 1616 *Overload 1:* 1617 Creates a minimization weighted objective. The actual objective is 1618 scalar_prod(sub_objectives, weights). 1619 1620 | 1621 1622 *Overload 2:* 1623 Creates a minimization weighted objective. The actual objective is 1624 scalar_prod(sub_objectives, weights). 1625 """ 1626 return _pywrapcp.Solver_WeightedMinimize(self, *args)
Overload 1: Creates a minimization weighted objective. The actual objective is scalar_prod(sub_objectives, weights).
|
Overload 2: Creates a minimization weighted objective. The actual objective is scalar_prod(sub_objectives, weights).
1628 def WeightedMaximize(self, *args): 1629 r""" 1630 *Overload 1:* 1631 Creates a maximization weigthed objective. 1632 1633 | 1634 1635 *Overload 2:* 1636 Creates a maximization weigthed objective. 1637 """ 1638 return _pywrapcp.Solver_WeightedMaximize(self, *args)
Overload 1: Creates a maximization weigthed objective.
|
Overload 2: Creates a maximization weigthed objective.
1640 def WeightedOptimize(self, *args): 1641 r""" 1642 *Overload 1:* 1643 Creates a weighted objective with a given sense (true = maximization). 1644 1645 | 1646 1647 *Overload 2:* 1648 Creates a weighted objective with a given sense (true = maximization). 1649 """ 1650 return _pywrapcp.Solver_WeightedOptimize(self, *args)
Overload 1: Creates a weighted objective with a given sense (true = maximization).
|
Overload 2: Creates a weighted objective with a given sense (true = maximization).
1652 def TabuSearch(self, maximize, objective, step, vars, keep_tenure, forbid_tenure, tabu_factor): 1653 r""" 1654 MetaHeuristics which try to get the search out of local optima. 1655 Creates a Tabu Search monitor. 1656 In the context of local search the behavior is similar to MakeOptimize(), 1657 creating an objective in a given sense. The behavior differs once a local 1658 optimum is reached: thereafter solutions which degrade the value of the 1659 objective are allowed if they are not "tabu". A solution is "tabu" if it 1660 doesn't respect the following rules: 1661 - improving the best solution found so far 1662 - variables in the "keep" list must keep their value, variables in the 1663 "forbid" list must not take the value they have in the list. 1664 Variables with new values enter the tabu lists after each new solution 1665 found and leave the lists after a given number of iterations (called 1666 tenure). Only the variables passed to the method can enter the lists. 1667 The tabu criterion is softened by the tabu factor which gives the number 1668 of "tabu" violations which is tolerated; a factor of 1 means no violations 1669 allowed; a factor of 0 means all violations are allowed. 1670 """ 1671 return _pywrapcp.Solver_TabuSearch(self, maximize, objective, step, vars, keep_tenure, forbid_tenure, tabu_factor)
MetaHeuristics which try to get the search out of local optima. Creates a Tabu Search monitor. In the context of local search the behavior is similar to MakeOptimize(), creating an objective in a given sense. The behavior differs once a local optimum is reached: thereafter solutions which degrade the value of the objective are allowed if they are not "tabu". A solution is "tabu" if it doesn't respect the following rules:
- improving the best solution found so far
- variables in the "keep" list must keep their value, variables in the "forbid" list must not take the value they have in the list. Variables with new values enter the tabu lists after each new solution found and leave the lists after a given number of iterations (called tenure). Only the variables passed to the method can enter the lists. The tabu criterion is softened by the tabu factor which gives the number of "tabu" violations which is tolerated; a factor of 1 means no violations allowed; a factor of 0 means all violations are allowed.
1673 def SimulatedAnnealing(self, maximize, v, step, initial_temperature): 1674 r"""Creates a Simulated Annealing monitor.""" 1675 return _pywrapcp.Solver_SimulatedAnnealing(self, maximize, v, step, initial_temperature)
Creates a Simulated Annealing monitor.
1677 def LubyRestart(self, scale_factor): 1678 r""" 1679 This search monitor will restart the search periodically. 1680 At the iteration n, it will restart after scale_factor * Luby(n) failures 1681 where Luby is the Luby Strategy (i.e. 1 1 2 1 1 2 4 1 1 2 1 1 2 4 8...). 1682 """ 1683 return _pywrapcp.Solver_LubyRestart(self, scale_factor)
This search monitor will restart the search periodically. At the iteration n, it will restart after scale_factor * Luby(n) failures where Luby is the Luby Strategy (i.e. 1 1 2 1 1 2 4 1 1 2 1 1 2 4 8...).
1685 def ConstantRestart(self, frequency): 1686 r""" 1687 This search monitor will restart the search periodically after 'frequency' 1688 failures. 1689 """ 1690 return _pywrapcp.Solver_ConstantRestart(self, frequency)
This search monitor will restart the search periodically after 'frequency' failures.
1692 def TimeLimit(self, *args): 1693 r"""Creates a search limit that constrains the running time.""" 1694 return _pywrapcp.Solver_TimeLimit(self, *args)
Creates a search limit that constrains the running time.
1696 def BranchesLimit(self, branches): 1697 r""" 1698 Creates a search limit that constrains the number of branches 1699 explored in the search tree. 1700 """ 1701 return _pywrapcp.Solver_BranchesLimit(self, branches)
Creates a search limit that constrains the number of branches explored in the search tree.
1703 def FailuresLimit(self, failures): 1704 r""" 1705 Creates a search limit that constrains the number of failures 1706 that can happen when exploring the search tree. 1707 """ 1708 return _pywrapcp.Solver_FailuresLimit(self, failures)
Creates a search limit that constrains the number of failures that can happen when exploring the search tree.
1710 def SolutionsLimit(self, solutions): 1711 r""" 1712 Creates a search limit that constrains the number of solutions found 1713 during the search. 1714 """ 1715 return _pywrapcp.Solver_SolutionsLimit(self, solutions)
Creates a search limit that constrains the number of solutions found during the search.
1717 def Limit(self, *args): 1718 r""" 1719 *Overload 1:* 1720 Limits the search with the 'time', 'branches', 'failures' and 1721 'solutions' limits. 'smart_time_check' reduces the calls to the wall 1722 1723 | 1724 1725 *Overload 2:* 1726 Creates a search limit from its protobuf description 1727 1728 | 1729 1730 *Overload 3:* 1731 Creates a search limit that is reached when either of the underlying limit 1732 is reached. That is, the returned limit is more stringent than both 1733 argument limits. 1734 """ 1735 return _pywrapcp.Solver_Limit(self, *args)
Overload 1: Limits the search with the 'time', 'branches', 'failures' and 'solutions' limits. 'smart_time_check' reduces the calls to the wall
|
Overload 2: Creates a search limit from its protobuf description
|
Overload 3: Creates a search limit that is reached when either of the underlying limit is reached. That is, the returned limit is more stringent than both argument limits.
1737 def CustomLimit(self, limiter): 1738 r""" 1739 Callback-based search limit. Search stops when limiter returns true; if 1740 this happens at a leaf the corresponding solution will be rejected. 1741 """ 1742 return _pywrapcp.Solver_CustomLimit(self, limiter)
Callback-based search limit. Search stops when limiter returns true; if this happens at a leaf the corresponding solution will be rejected.
1744 def SearchLog(self, *args): 1745 r""" 1746 *Overload 1:* 1747 The SearchMonitors below will display a periodic search log 1748 on LOG(INFO) every branch_period branches explored. 1749 1750 | 1751 1752 *Overload 2:* 1753 At each solution, this monitor also display the var value. 1754 1755 | 1756 1757 *Overload 3:* 1758 At each solution, this monitor will also display result of 1759 ``display_callback``. 1760 1761 | 1762 1763 *Overload 4:* 1764 At each solution, this monitor will display the 'var' value and the 1765 result of ``display_callback``. 1766 1767 | 1768 1769 *Overload 5:* 1770 At each solution, this monitor will display the 'vars' values and the 1771 result of ``display_callback``. 1772 1773 | 1774 1775 *Overload 6:* 1776 OptimizeVar Search Logs 1777 At each solution, this monitor will also display the 'opt_var' value. 1778 1779 | 1780 1781 *Overload 7:* 1782 Creates a search monitor that will also print the result of the 1783 display callback. 1784 """ 1785 return _pywrapcp.Solver_SearchLog(self, *args)
Overload 1: The SearchMonitors below will display a periodic search log on LOG(INFO) every branch_period branches explored.
|
Overload 2: At each solution, this monitor also display the var value.
|
Overload 3:
At each solution, this monitor will also display result of
display_callback.
|
Overload 4:
At each solution, this monitor will display the 'var' value and the
result of display_callback.
|
Overload 5:
At each solution, this monitor will display the 'vars' values and the
result of display_callback.
|
Overload 6: OptimizeVar Search Logs At each solution, this monitor will also display the 'opt_var' value.
|
Overload 7: Creates a search monitor that will also print the result of the display callback.
1787 def SearchTrace(self, prefix): 1788 r""" 1789 Creates a search monitor that will trace precisely the behavior of the 1790 search. Use this only for low level debugging. 1791 """ 1792 return _pywrapcp.Solver_SearchTrace(self, prefix)
Creates a search monitor that will trace precisely the behavior of the search. Use this only for low level debugging.
1794 def PrintModelVisitor(self): 1795 r"""Prints the model.""" 1796 return _pywrapcp.Solver_PrintModelVisitor(self)
Prints the model.
1798 def StatisticsModelVisitor(self): 1799 r"""Displays some nice statistics on the model.""" 1800 return _pywrapcp.Solver_StatisticsModelVisitor(self)
Displays some nice statistics on the model.
1802 def AssignVariableValue(self, var, val): 1803 r"""Decisions.""" 1804 return _pywrapcp.Solver_AssignVariableValue(self, var, val)
Decisions.
1836 def ScheduleOrPostpone(self, var, est, marker): 1837 r""" 1838 Returns a decision that tries to schedule a task at a given time. 1839 On the Apply branch, it will set that interval var as performed and set 1840 its start to 'est'. On the Refute branch, it will just update the 1841 'marker' to 'est' + 1. This decision is used in the 1842 INTERVAL_SET_TIMES_FORWARD strategy. 1843 """ 1844 return _pywrapcp.Solver_ScheduleOrPostpone(self, var, est, marker)
Returns a decision that tries to schedule a task at a given time. On the Apply branch, it will set that interval var as performed and set its start to 'est'. On the Refute branch, it will just update the 'marker' to 'est' + 1. This decision is used in the INTERVAL_SET_TIMES_FORWARD strategy.
1846 def ScheduleOrExpedite(self, var, est, marker): 1847 r""" 1848 Returns a decision that tries to schedule a task at a given time. 1849 On the Apply branch, it will set that interval var as performed and set 1850 its end to 'est'. On the Refute branch, it will just update the 1851 'marker' to 'est' - 1. This decision is used in the 1852 INTERVAL_SET_TIMES_BACKWARD strategy. 1853 """ 1854 return _pywrapcp.Solver_ScheduleOrExpedite(self, var, est, marker)
Returns a decision that tries to schedule a task at a given time. On the Apply branch, it will set that interval var as performed and set its end to 'est'. On the Refute branch, it will just update the 'marker' to 'est' - 1. This decision is used in the INTERVAL_SET_TIMES_BACKWARD strategy.
1856 def RankFirstInterval(self, sequence, index): 1857 r""" 1858 Returns a decision that tries to rank first the ith interval var 1859 in the sequence variable. 1860 """ 1861 return _pywrapcp.Solver_RankFirstInterval(self, sequence, index)
Returns a decision that tries to rank first the ith interval var in the sequence variable.
1863 def RankLastInterval(self, sequence, index): 1864 r""" 1865 Returns a decision that tries to rank last the ith interval var 1866 in the sequence variable. 1867 """ 1868 return _pywrapcp.Solver_RankLastInterval(self, sequence, index)
Returns a decision that tries to rank last the ith interval var in the sequence variable.
1870 def Phase(self, *args): 1871 r""" 1872 *Overload 1:* 1873 Phases on IntVar arrays. 1874 for all other functions that have several homonyms in this .h). 1875 1876 | 1877 1878 *Overload 2:* 1879 Scheduling phases. 1880 """ 1881 return _pywrapcp.Solver_Phase(self, *args)
Overload 1: Phases on IntVar arrays. for all other functions that have several homonyms in this .h).
|
Overload 2: Scheduling phases.
1883 def DecisionBuilderFromAssignment(self, assignment, db, vars): 1884 r""" 1885 Returns a decision builder for which the left-most leaf corresponds 1886 to assignment, the rest of the tree being explored using 'db'. 1887 """ 1888 return _pywrapcp.Solver_DecisionBuilderFromAssignment(self, assignment, db, vars)
Returns a decision builder for which the left-most leaf corresponds to assignment, the rest of the tree being explored using 'db'.
1890 def ConstraintAdder(self, ct): 1891 r""" 1892 Returns a decision builder that will add the given constraint to 1893 the model. 1894 """ 1895 return _pywrapcp.Solver_ConstraintAdder(self, ct)
Returns a decision builder that will add the given constraint to the model.
1900 def NestedOptimize(self, *args): 1901 r""" 1902 NestedOptimize will collapse a search tree described by a 1903 decision builder 'db' and a set of monitors and wrap it into a 1904 single point. If there are no solutions to this nested tree, then 1905 NestedOptimize will fail. If there are solutions, it will find 1906 the best as described by the mandatory objective in the solution 1907 as well as the optimization direction, instantiate all variables 1908 to this solution, and return nullptr. 1909 """ 1910 return _pywrapcp.Solver_NestedOptimize(self, *args)
NestedOptimize will collapse a search tree described by a decision builder 'db' and a set of monitors and wrap it into a single point. If there are no solutions to this nested tree, then NestedOptimize will fail. If there are solutions, it will find the best as described by the mandatory objective in the solution as well as the optimization direction, instantiate all variables to this solution, and return nullptr.
1912 def RestoreAssignment(self, assignment): 1913 r""" 1914 Returns a DecisionBuilder which restores an Assignment 1915 (calls void Assignment::Restore()) 1916 """ 1917 return _pywrapcp.Solver_RestoreAssignment(self, assignment)
Returns a DecisionBuilder which restores an Assignment (calls void Assignment::Restore())
1919 def StoreAssignment(self, assignment): 1920 r""" 1921 Returns a DecisionBuilder which stores an Assignment 1922 (calls void Assignment::Store()) 1923 """ 1924 return _pywrapcp.Solver_StoreAssignment(self, assignment)
Returns a DecisionBuilder which stores an Assignment (calls void Assignment::Store())
1926 def Operator(self, *args): 1927 r"""Local Search Operators.""" 1928 return _pywrapcp.Solver_Operator(self, *args)
Local Search Operators.
1930 def RandomLnsOperator(self, *args): 1931 r""" 1932 Creates a large neighborhood search operator which creates fragments (set 1933 of relaxed variables) with up to number_of_variables random variables 1934 (sampling with replacement is performed meaning that at most 1935 number_of_variables variables are selected). Warning: this operator will 1936 always return neighbors; using it without a search limit will result in a 1937 non-ending search. 1938 Optionally a random seed can be specified. 1939 """ 1940 return _pywrapcp.Solver_RandomLnsOperator(self, *args)
Creates a large neighborhood search operator which creates fragments (set of relaxed variables) with up to number_of_variables random variables (sampling with replacement is performed meaning that at most number_of_variables variables are selected). Warning: this operator will always return neighbors; using it without a search limit will result in a non-ending search. Optionally a random seed can be specified.
1942 def MoveTowardTargetOperator(self, *args): 1943 r""" 1944 *Overload 1:* 1945 Creates a local search operator that tries to move the assignment of some 1946 variables toward a target. The target is given as an Assignment. This 1947 operator generates neighbors in which the only difference compared to the 1948 current state is that one variable that belongs to the target assignment 1949 is set to its target value. 1950 1951 | 1952 1953 *Overload 2:* 1954 Creates a local search operator that tries to move the assignment of some 1955 variables toward a target. The target is given either as two vectors: a 1956 vector of variables and a vector of associated target values. The two 1957 vectors should be of the same length. This operator generates neighbors in 1958 which the only difference compared to the current state is that one 1959 variable that belongs to the given vector is set to its target value. 1960 """ 1961 return _pywrapcp.Solver_MoveTowardTargetOperator(self, *args)
Overload 1: Creates a local search operator that tries to move the assignment of some variables toward a target. The target is given as an Assignment. This operator generates neighbors in which the only difference compared to the current state is that one variable that belongs to the target assignment is set to its target value.
|
Overload 2: Creates a local search operator that tries to move the assignment of some variables toward a target. The target is given either as two vectors: a vector of variables and a vector of associated target values. The two vectors should be of the same length. This operator generates neighbors in which the only difference compared to the current state is that one variable that belongs to the given vector is set to its target value.
1963 def ConcatenateOperators(self, *args): 1964 r""" 1965 Creates a local search operator which concatenates a vector of operators. 1966 Each operator from the vector is called sequentially. By default, when a 1967 neighbor is found the neighborhood exploration restarts from the last 1968 active operator (the one which produced the neighbor). 1969 This can be overridden by setting restart to true to force the exploration 1970 to start from the first operator in the vector. 1971 1972 The default behavior can also be overridden using an evaluation callback 1973 to set the order in which the operators are explored (the callback is 1974 called in LocalSearchOperator::Start()). The first argument of the 1975 callback is the index of the operator which produced the last move, the 1976 second argument is the index of the operator to be evaluated. Ownership of 1977 the callback is taken by ConcatenateOperators. 1978 1979 Example: 1980 1981 const int kPriorities = {10, 100, 10, 0}; 1982 int64_t Evaluate(int active_operator, int current_operator) { 1983 return kPriorities[current_operator]; 1984 } 1985 1986 LocalSearchOperator* concat = 1987 solver.ConcatenateOperators(operators, 1988 NewPermanentCallback(&Evaluate)); 1989 1990 The elements of the vector operators will be sorted by increasing priority 1991 and explored in that order (tie-breaks are handled by keeping the relative 1992 operator order in the vector). This would result in the following order: 1993 operators[3], operators[0], operators[2], operators[1]. 1994 """ 1995 return _pywrapcp.Solver_ConcatenateOperators(self, *args)
Creates a local search operator which concatenates a vector of operators. Each operator from the vector is called sequentially. By default, when a neighbor is found the neighborhood exploration restarts from the last active operator (the one which produced the neighbor). This can be overridden by setting restart to true to force the exploration to start from the first operator in the vector.
The default behavior can also be overridden using an evaluation callback to set the order in which the operators are explored (the callback is called in LocalSearchOperator::Start()). The first argument of the callback is the index of the operator which produced the last move, the second argument is the index of the operator to be evaluated. Ownership of the callback is taken by ConcatenateOperators.
Example:
const int kPriorities = {10, 100, 10, 0}; int64_t Evaluate(int active_operator, int current_operator) { return kPriorities[current_operator]; }
LocalSearchOperator* concat = solver.ConcatenateOperators(operators, NewPermanentCallback(&Evaluate));
The elements of the vector operators will be sorted by increasing priority and explored in that order (tie-breaks are handled by keeping the relative operator order in the vector). This would result in the following order: operators[3], operators[0], operators[2], operators[1].
1997 def RandomConcatenateOperators(self, *args): 1998 r""" 1999 *Overload 1:* 2000 Randomized version of local search concatenator; calls a random operator 2001 at each call to MakeNextNeighbor(). 2002 2003 | 2004 2005 *Overload 2:* 2006 Randomized version of local search concatenator; calls a random operator 2007 at each call to MakeNextNeighbor(). The provided seed is used to 2008 initialize the random number generator. 2009 """ 2010 return _pywrapcp.Solver_RandomConcatenateOperators(self, *args)
Overload 1: Randomized version of local search concatenator; calls a random operator at each call to MakeNextNeighbor().
|
Overload 2: Randomized version of local search concatenator; calls a random operator at each call to MakeNextNeighbor(). The provided seed is used to initialize the random number generator.
2012 def NeighborhoodLimit(self, op, limit): 2013 r""" 2014 Creates a local search operator that wraps another local search 2015 operator and limits the number of neighbors explored (i.e., calls 2016 to MakeNextNeighbor from the current solution (between two calls 2017 to Start()). When this limit is reached, MakeNextNeighbor() 2018 returns false. The counter is cleared when Start() is called. 2019 """ 2020 return _pywrapcp.Solver_NeighborhoodLimit(self, op, limit)
Creates a local search operator that wraps another local search operator and limits the number of neighbors explored (i.e., calls to MakeNextNeighbor from the current solution (between two calls to Start()). When this limit is reached, MakeNextNeighbor() returns false. The counter is cleared when Start() is called.
2022 def LocalSearchPhase(self, *args): 2023 r""" 2024 *Overload 1:* 2025 Local Search decision builders factories. 2026 Local search is used to improve a given solution. This initial solution 2027 can be specified either by an Assignment or by a DecisionBulder, and the 2028 corresponding variables, the initial solution being the first solution 2029 found by the DecisionBuilder. 2030 The LocalSearchPhaseParameters parameter holds the actual definition of 2031 the local search phase: 2032 - a local search operator used to explore the neighborhood of the current 2033 solution, 2034 - a decision builder to instantiate unbound variables once a neighbor has 2035 been defined; in the case of LNS-based operators instantiates fragment 2036 variables; search monitors can be added to this sub-search by wrapping 2037 the decision builder with MakeSolveOnce. 2038 - a search limit specifying how long local search looks for neighbors 2039 before accepting one; the last neighbor is always taken and in the case 2040 of a greedy search, this corresponds to the best local neighbor; 2041 first-accept (which is the default behavior) can be modeled using a 2042 solution found limit of 1, 2043 - a vector of local search filters used to speed up the search by pruning 2044 unfeasible neighbors. 2045 Metaheuristics can be added by defining specialized search monitors; 2046 currently down/up-hill climbing is available through OptimizeVar, as well 2047 as Guided Local Search, Tabu Search and Simulated Annealing. 2048 2049 | 2050 2051 *Overload 2:* 2052 Variant with a sub_decison_builder specific to the first solution. 2053 """ 2054 return _pywrapcp.Solver_LocalSearchPhase(self, *args)
Overload 1: Local Search decision builders factories. Local search is used to improve a given solution. This initial solution can be specified either by an Assignment or by a DecisionBulder, and the corresponding variables, the initial solution being the first solution found by the DecisionBuilder. The LocalSearchPhaseParameters parameter holds the actual definition of the local search phase:
- a local search operator used to explore the neighborhood of the current solution,
- a decision builder to instantiate unbound variables once a neighbor has been defined; in the case of LNS-based operators instantiates fragment variables; search monitors can be added to this sub-search by wrapping the decision builder with MakeSolveOnce.
- a search limit specifying how long local search looks for neighbors before accepting one; the last neighbor is always taken and in the case of a greedy search, this corresponds to the best local neighbor; first-accept (which is the default behavior) can be modeled using a solution found limit of 1,
- a vector of local search filters used to speed up the search by pruning unfeasible neighbors. Metaheuristics can be added by defining specialized search monitors; currently down/up-hill climbing is available through OptimizeVar, as well as Guided Local Search, Tabu Search and Simulated Annealing.
|
Overload 2: Variant with a sub_decison_builder specific to the first solution.
2056 def LocalSearchPhaseParameters(self, *args): 2057 r"""Local Search Phase Parameters""" 2058 return _pywrapcp.Solver_LocalSearchPhaseParameters(self, *args)
Local Search Phase Parameters
2060 def TopProgressPercent(self): 2061 r""" 2062 Returns a percentage representing the propress of the search before 2063 reaching the limits of the top-level search (can be called from a nested 2064 solve). 2065 """ 2066 return _pywrapcp.Solver_TopProgressPercent(self)
Returns a percentage representing the propress of the search before reaching the limits of the top-level search (can be called from a nested solve).
2068 def SearchDepth(self): 2069 r""" 2070 Gets the search depth of the current active search. Returns -1 if 2071 there is no active search opened. 2072 """ 2073 return _pywrapcp.Solver_SearchDepth(self)
Gets the search depth of the current active search. Returns -1 if there is no active search opened.
2075 def SearchLeftDepth(self): 2076 r""" 2077 Gets the search left depth of the current active search. Returns -1 if 2078 there is no active search opened. 2079 """ 2080 return _pywrapcp.Solver_SearchLeftDepth(self)
Gets the search left depth of the current active search. Returns -1 if there is no active search opened.
2082 def SolveDepth(self): 2083 r""" 2084 Gets the number of nested searches. It returns 0 outside search, 2085 1 during the top level search, 2 or more in case of nested searches. 2086 """ 2087 return _pywrapcp.Solver_SolveDepth(self)
Gets the number of nested searches. It returns 0 outside search, 1 during the top level search, 2 or more in case of nested searches.
2089 def Rand64(self, size): 2090 r"""Returns a random value between 0 and 'size' - 1;""" 2091 return _pywrapcp.Solver_Rand64(self, size)
Returns a random value between 0 and 'size' - 1;
2093 def Rand32(self, size): 2094 r"""Returns a random value between 0 and 'size' - 1;""" 2095 return _pywrapcp.Solver_Rand32(self, size)
Returns a random value between 0 and 'size' - 1;
2097 def ReSeed(self, seed): 2098 r"""Reseed the solver random generator.""" 2099 return _pywrapcp.Solver_ReSeed(self, seed)
Reseed the solver random generator.
2101 def LocalSearchProfile(self): 2102 r"""Returns local search profiling information in a human readable format.""" 2103 return _pywrapcp.Solver_LocalSearchProfile(self)
Returns local search profiling information in a human readable format.
2105 def Constraints(self): 2106 r""" 2107 Counts the number of constraints that have been added 2108 to the solver before the search. 2109 """ 2110 return _pywrapcp.Solver_Constraints(self)
Counts the number of constraints that have been added to the solver before the search.
2112 def Accept(self, visitor): 2113 r"""Accepts the given model visitor.""" 2114 return _pywrapcp.Solver_Accept(self, visitor)
Accepts the given model visitor.
2116 def FinishCurrentSearch(self): 2117 r"""Tells the solver to kill or restart the current search.""" 2118 return _pywrapcp.Solver_FinishCurrentSearch(self)
Tells the solver to kill or restart the current search.
2123 def ShouldFail(self): 2124 r""" 2125 These methods are only useful for the SWIG wrappers, which need a way 2126 to externally cause the Solver to fail. 2127 """ 2128 return _pywrapcp.Solver_ShouldFail(self)
These methods are only useful for the SWIG wrappers, which need a way to externally cause the Solver to fail.
2177class BaseObject(object): 2178 r""" 2179 A BaseObject is the root of all reversibly allocated objects. 2180 A DebugString method and the associated << operator are implemented 2181 as a convenience. 2182 """ 2183 2184 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2185 2186 def __init__(self): 2187 if self.__class__ == BaseObject: 2188 _self = None 2189 else: 2190 _self = self 2191 _pywrapcp.BaseObject_swiginit(self, _pywrapcp.new_BaseObject(_self, )) 2192 __swig_destroy__ = _pywrapcp.delete_BaseObject 2193 2194 def DebugString(self): 2195 return _pywrapcp.BaseObject_DebugString(self) 2196 2197 def __str__(self): 2198 return _pywrapcp.BaseObject___str__(self) 2199 2200 def __repr__(self): 2201 return _pywrapcp.BaseObject___repr__(self) 2202 def __disown__(self): 2203 self.this.disown() 2204 _pywrapcp.disown_BaseObject(self) 2205 return weakref.proxy(self)
A BaseObject is the root of all reversibly allocated objects. A DebugString method and the associated << operator are implemented as a convenience.
2184 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2209class PropagationBaseObject(BaseObject): 2210 r""" 2211 NOLINT 2212 The PropagationBaseObject is a subclass of BaseObject that is also 2213 friend to the Solver class. It allows accessing methods useful when 2214 writing new constraints or new expressions. 2215 """ 2216 2217 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2218 __repr__ = _swig_repr 2219 2220 def __init__(self, s): 2221 if self.__class__ == PropagationBaseObject: 2222 _self = None 2223 else: 2224 _self = self 2225 _pywrapcp.PropagationBaseObject_swiginit(self, _pywrapcp.new_PropagationBaseObject(_self, s)) 2226 __swig_destroy__ = _pywrapcp.delete_PropagationBaseObject 2227 2228 def DebugString(self): 2229 return _pywrapcp.PropagationBaseObject_DebugString(self) 2230 2231 def solver(self): 2232 return _pywrapcp.PropagationBaseObject_solver(self) 2233 2234 def Name(self): 2235 r"""Object naming.""" 2236 return _pywrapcp.PropagationBaseObject_Name(self) 2237 def __disown__(self): 2238 self.this.disown() 2239 _pywrapcp.disown_PropagationBaseObject(self) 2240 return weakref.proxy(self)
NOLINT The PropagationBaseObject is a subclass of BaseObject that is also friend to the Solver class. It allows accessing methods useful when writing new constraints or new expressions.
2217 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2244class Decision(BaseObject): 2245 r""" 2246 A Decision represents a choice point in the search tree. The two main 2247 methods are Apply() to go left, or Refute() to go right. 2248 """ 2249 2250 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2251 2252 def __init__(self): 2253 if self.__class__ == Decision: 2254 _self = None 2255 else: 2256 _self = self 2257 _pywrapcp.Decision_swiginit(self, _pywrapcp.new_Decision(_self, )) 2258 __swig_destroy__ = _pywrapcp.delete_Decision 2259 2260 def ApplyWrapper(self, s): 2261 r"""Apply will be called first when the decision is executed.""" 2262 return _pywrapcp.Decision_ApplyWrapper(self, s) 2263 2264 def RefuteWrapper(self, s): 2265 r"""Refute will be called after a backtrack.""" 2266 return _pywrapcp.Decision_RefuteWrapper(self, s) 2267 2268 def DebugString(self): 2269 return _pywrapcp.Decision_DebugString(self) 2270 2271 def __repr__(self): 2272 return _pywrapcp.Decision___repr__(self) 2273 2274 def __str__(self): 2275 return _pywrapcp.Decision___str__(self) 2276 def __disown__(self): 2277 self.this.disown() 2278 _pywrapcp.disown_Decision(self) 2279 return weakref.proxy(self)
A Decision represents a choice point in the search tree. The two main methods are Apply() to go left, or Refute() to go right.
2250 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2260 def ApplyWrapper(self, s): 2261 r"""Apply will be called first when the decision is executed.""" 2262 return _pywrapcp.Decision_ApplyWrapper(self, s)
Apply will be called first when the decision is executed.
2283class DecisionBuilder(BaseObject): 2284 r""" 2285 A DecisionBuilder is responsible for creating the search tree. The 2286 important method is Next(), which returns the next decision to execute. 2287 """ 2288 2289 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2290 2291 def __init__(self): 2292 if self.__class__ == DecisionBuilder: 2293 _self = None 2294 else: 2295 _self = self 2296 _pywrapcp.DecisionBuilder_swiginit(self, _pywrapcp.new_DecisionBuilder(_self, )) 2297 __swig_destroy__ = _pywrapcp.delete_DecisionBuilder 2298 2299 def NextWrapper(self, s): 2300 r""" 2301 This is the main method of the decision builder class. It must 2302 return a decision (an instance of the class Decision). If it 2303 returns nullptr, this means that the decision builder has finished 2304 its work. 2305 """ 2306 return _pywrapcp.DecisionBuilder_NextWrapper(self, s) 2307 2308 def DebugString(self): 2309 return _pywrapcp.DecisionBuilder_DebugString(self) 2310 2311 def __repr__(self): 2312 return _pywrapcp.DecisionBuilder___repr__(self) 2313 2314 def __str__(self): 2315 return _pywrapcp.DecisionBuilder___str__(self) 2316 def __disown__(self): 2317 self.this.disown() 2318 _pywrapcp.disown_DecisionBuilder(self) 2319 return weakref.proxy(self)
A DecisionBuilder is responsible for creating the search tree. The important method is Next(), which returns the next decision to execute.
2289 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2299 def NextWrapper(self, s): 2300 r""" 2301 This is the main method of the decision builder class. It must 2302 return a decision (an instance of the class Decision). If it 2303 returns nullptr, this means that the decision builder has finished 2304 its work. 2305 """ 2306 return _pywrapcp.DecisionBuilder_NextWrapper(self, s)
This is the main method of the decision builder class. It must return a decision (an instance of the class Decision). If it returns nullptr, this means that the decision builder has finished its work.
2323class Demon(BaseObject): 2324 r""" 2325 A Demon is the base element of a propagation queue. It is the main 2326 object responsible for implementing the actual propagation 2327 of the constraint and pruning the inconsistent values in the domains 2328 of the variables. The main concept is that demons are listeners that are 2329 attached to the variables and listen to their modifications. 2330 There are two methods: 2331 - Run() is the actual method called when the demon is processed. 2332 - priority() returns its priority. Standard priorities are slow, normal 2333 or fast. "immediate" is reserved for variables and is treated separately. 2334 """ 2335 2336 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2337 __repr__ = _swig_repr 2338 2339 def __init__(self): 2340 r""" 2341 This indicates the priority of a demon. Immediate demons are treated 2342 separately and corresponds to variables. 2343 """ 2344 if self.__class__ == Demon: 2345 _self = None 2346 else: 2347 _self = self 2348 _pywrapcp.Demon_swiginit(self, _pywrapcp.new_Demon(_self, )) 2349 __swig_destroy__ = _pywrapcp.delete_Demon 2350 2351 def RunWrapper(self, s): 2352 r"""This is the main callback of the demon.""" 2353 return _pywrapcp.Demon_RunWrapper(self, s) 2354 2355 def Priority(self): 2356 r""" 2357 This method returns the priority of the demon. Usually a demon is 2358 fast, slow or normal. Immediate demons are reserved for internal 2359 use to maintain variables. 2360 """ 2361 return _pywrapcp.Demon_Priority(self) 2362 2363 def DebugString(self): 2364 return _pywrapcp.Demon_DebugString(self) 2365 2366 def Inhibit(self, s): 2367 r""" 2368 This method inhibits the demon in the search tree below the 2369 current position. 2370 """ 2371 return _pywrapcp.Demon_Inhibit(self, s) 2372 2373 def Desinhibit(self, s): 2374 r"""This method un-inhibits the demon that was previously inhibited.""" 2375 return _pywrapcp.Demon_Desinhibit(self, s) 2376 def __disown__(self): 2377 self.this.disown() 2378 _pywrapcp.disown_Demon(self) 2379 return weakref.proxy(self)
A Demon is the base element of a propagation queue. It is the main object responsible for implementing the actual propagation of the constraint and pruning the inconsistent values in the domains of the variables. The main concept is that demons are listeners that are attached to the variables and listen to their modifications.
There are two methods:
- Run() is the actual method called when the demon is processed.
- priority() returns its priority. Standard priorities are slow, normal or fast. "immediate" is reserved for variables and is treated separately.
2339 def __init__(self): 2340 r""" 2341 This indicates the priority of a demon. Immediate demons are treated 2342 separately and corresponds to variables. 2343 """ 2344 if self.__class__ == Demon: 2345 _self = None 2346 else: 2347 _self = self 2348 _pywrapcp.Demon_swiginit(self, _pywrapcp.new_Demon(_self, ))
This indicates the priority of a demon. Immediate demons are treated separately and corresponds to variables.
2336 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2351 def RunWrapper(self, s): 2352 r"""This is the main callback of the demon.""" 2353 return _pywrapcp.Demon_RunWrapper(self, s)
This is the main callback of the demon.
2355 def Priority(self): 2356 r""" 2357 This method returns the priority of the demon. Usually a demon is 2358 fast, slow or normal. Immediate demons are reserved for internal 2359 use to maintain variables. 2360 """ 2361 return _pywrapcp.Demon_Priority(self)
This method returns the priority of the demon. Usually a demon is fast, slow or normal. Immediate demons are reserved for internal use to maintain variables.
2383class Constraint(PropagationBaseObject): 2384 r""" 2385 A constraint is the main modeling object. It provides two methods: 2386 - Post() is responsible for creating the demons and attaching them to 2387 immediate demons(). 2388 - InitialPropagate() is called once just after Post and performs 2389 the initial propagation. The subsequent propagations will be performed 2390 by the demons Posted during the post() method. 2391 """ 2392 2393 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2394 2395 def __init__(self, solver): 2396 if self.__class__ == Constraint: 2397 _self = None 2398 else: 2399 _self = self 2400 _pywrapcp.Constraint_swiginit(self, _pywrapcp.new_Constraint(_self, solver)) 2401 __swig_destroy__ = _pywrapcp.delete_Constraint 2402 2403 def Post(self): 2404 r""" 2405 This method is called when the constraint is processed by the 2406 solver. Its main usage is to attach demons to variables. 2407 """ 2408 return _pywrapcp.Constraint_Post(self) 2409 2410 def InitialPropagateWrapper(self): 2411 r""" 2412 This method performs the initial propagation of the 2413 constraint. It is called just after the post. 2414 """ 2415 return _pywrapcp.Constraint_InitialPropagateWrapper(self) 2416 2417 def DebugString(self): 2418 return _pywrapcp.Constraint_DebugString(self) 2419 2420 def Var(self): 2421 r""" 2422 Creates a Boolean variable representing the status of the constraint 2423 (false = constraint is violated, true = constraint is satisfied). It 2424 returns nullptr if the constraint does not support this API. 2425 """ 2426 return _pywrapcp.Constraint_Var(self) 2427 2428 def __repr__(self): 2429 return _pywrapcp.Constraint___repr__(self) 2430 2431 def __str__(self): 2432 return _pywrapcp.Constraint___str__(self) 2433 2434 def __add__(self, *args): 2435 return _pywrapcp.Constraint___add__(self, *args) 2436 2437 def __radd__(self, v): 2438 return _pywrapcp.Constraint___radd__(self, v) 2439 2440 def __sub__(self, *args): 2441 return _pywrapcp.Constraint___sub__(self, *args) 2442 2443 def __rsub__(self, v): 2444 return _pywrapcp.Constraint___rsub__(self, v) 2445 2446 def __mul__(self, *args): 2447 return _pywrapcp.Constraint___mul__(self, *args) 2448 2449 def __rmul__(self, v): 2450 return _pywrapcp.Constraint___rmul__(self, v) 2451 2452 def __floordiv__(self, v): 2453 return _pywrapcp.Constraint___floordiv__(self, v) 2454 2455 def __neg__(self): 2456 return _pywrapcp.Constraint___neg__(self) 2457 2458 def __abs__(self): 2459 return _pywrapcp.Constraint___abs__(self) 2460 2461 def Square(self): 2462 return _pywrapcp.Constraint_Square(self) 2463 2464 def __eq__(self, *args): 2465 return _pywrapcp.Constraint___eq__(self, *args) 2466 2467 def __ne__(self, *args): 2468 return _pywrapcp.Constraint___ne__(self, *args) 2469 2470 def __ge__(self, *args): 2471 return _pywrapcp.Constraint___ge__(self, *args) 2472 2473 def __gt__(self, *args): 2474 return _pywrapcp.Constraint___gt__(self, *args) 2475 2476 def __le__(self, *args): 2477 return _pywrapcp.Constraint___le__(self, *args) 2478 2479 def __lt__(self, *args): 2480 return _pywrapcp.Constraint___lt__(self, *args) 2481 2482 def MapTo(self, vars): 2483 return _pywrapcp.Constraint_MapTo(self, vars) 2484 2485 def IndexOf(self, *args): 2486 return _pywrapcp.Constraint_IndexOf(self, *args) 2487 def __disown__(self): 2488 self.this.disown() 2489 _pywrapcp.disown_Constraint(self) 2490 return weakref.proxy(self)
A constraint is the main modeling object. It provides two methods:
- Post() is responsible for creating the demons and attaching them to immediate demons().
- InitialPropagate() is called once just after Post and performs the initial propagation. The subsequent propagations will be performed by the demons Posted during the post() method.
2393 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2403 def Post(self): 2404 r""" 2405 This method is called when the constraint is processed by the 2406 solver. Its main usage is to attach demons to variables. 2407 """ 2408 return _pywrapcp.Constraint_Post(self)
This method is called when the constraint is processed by the solver. Its main usage is to attach demons to variables.
2410 def InitialPropagateWrapper(self): 2411 r""" 2412 This method performs the initial propagation of the 2413 constraint. It is called just after the post. 2414 """ 2415 return _pywrapcp.Constraint_InitialPropagateWrapper(self)
This method performs the initial propagation of the constraint. It is called just after the post.
2420 def Var(self): 2421 r""" 2422 Creates a Boolean variable representing the status of the constraint 2423 (false = constraint is violated, true = constraint is satisfied). It 2424 returns nullptr if the constraint does not support this API. 2425 """ 2426 return _pywrapcp.Constraint_Var(self)
Creates a Boolean variable representing the status of the constraint (false = constraint is violated, true = constraint is satisfied). It returns nullptr if the constraint does not support this API.
Inherited Members
2494class SearchMonitor(BaseObject): 2495 r"""A search monitor is a simple set of callbacks to monitor all search events""" 2496 2497 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2498 kNoProgress = _pywrapcp.SearchMonitor_kNoProgress 2499 2500 def __init__(self, s): 2501 if self.__class__ == SearchMonitor: 2502 _self = None 2503 else: 2504 _self = self 2505 _pywrapcp.SearchMonitor_swiginit(self, _pywrapcp.new_SearchMonitor(_self, s)) 2506 __swig_destroy__ = _pywrapcp.delete_SearchMonitor 2507 2508 def EnterSearch(self): 2509 r"""Beginning of the search.""" 2510 return _pywrapcp.SearchMonitor_EnterSearch(self) 2511 2512 def RestartSearch(self): 2513 r"""Restart the search.""" 2514 return _pywrapcp.SearchMonitor_RestartSearch(self) 2515 2516 def ExitSearch(self): 2517 r"""End of the search.""" 2518 return _pywrapcp.SearchMonitor_ExitSearch(self) 2519 2520 def BeginNextDecision(self, b): 2521 r"""Before calling DecisionBuilder::Next.""" 2522 return _pywrapcp.SearchMonitor_BeginNextDecision(self, b) 2523 2524 def EndNextDecision(self, b, d): 2525 r"""After calling DecisionBuilder::Next, along with the returned decision.""" 2526 return _pywrapcp.SearchMonitor_EndNextDecision(self, b, d) 2527 2528 def ApplyDecision(self, d): 2529 r"""Before applying the decision.""" 2530 return _pywrapcp.SearchMonitor_ApplyDecision(self, d) 2531 2532 def RefuteDecision(self, d): 2533 r"""Before refuting the decision.""" 2534 return _pywrapcp.SearchMonitor_RefuteDecision(self, d) 2535 2536 def AfterDecision(self, d, apply): 2537 r""" 2538 Just after refuting or applying the decision, apply is true after Apply. 2539 This is called only if the Apply() or Refute() methods have not failed. 2540 """ 2541 return _pywrapcp.SearchMonitor_AfterDecision(self, d, apply) 2542 2543 def BeginFail(self): 2544 r"""Just when the failure occurs.""" 2545 return _pywrapcp.SearchMonitor_BeginFail(self) 2546 2547 def EndFail(self): 2548 r"""After completing the backtrack.""" 2549 return _pywrapcp.SearchMonitor_EndFail(self) 2550 2551 def BeginInitialPropagation(self): 2552 r"""Before the initial propagation.""" 2553 return _pywrapcp.SearchMonitor_BeginInitialPropagation(self) 2554 2555 def EndInitialPropagation(self): 2556 r"""After the initial propagation.""" 2557 return _pywrapcp.SearchMonitor_EndInitialPropagation(self) 2558 2559 def AcceptSolution(self): 2560 r""" 2561 This method is called when a solution is found. It asserts whether the 2562 solution is valid. A value of false indicates that the solution 2563 should be discarded. 2564 """ 2565 return _pywrapcp.SearchMonitor_AcceptSolution(self) 2566 2567 def AtSolution(self): 2568 r""" 2569 This method is called when a valid solution is found. If the 2570 return value is true, then search will resume after. If the result 2571 is false, then search will stop there. 2572 """ 2573 return _pywrapcp.SearchMonitor_AtSolution(self) 2574 2575 def NoMoreSolutions(self): 2576 r"""When the search tree is finished.""" 2577 return _pywrapcp.SearchMonitor_NoMoreSolutions(self) 2578 2579 def AcceptDelta(self, delta, deltadelta): 2580 2581 return _pywrapcp.SearchMonitor_AcceptDelta(self, delta, deltadelta) 2582 2583 def AcceptNeighbor(self): 2584 r"""After accepting a neighbor during local search.""" 2585 return _pywrapcp.SearchMonitor_AcceptNeighbor(self) 2586 2587 def ProgressPercent(self): 2588 r""" 2589 Returns a percentage representing the propress of the search before 2590 reaching limits. 2591 """ 2592 return _pywrapcp.SearchMonitor_ProgressPercent(self) 2593 2594 def solver(self): 2595 return _pywrapcp.SearchMonitor_solver(self) 2596 2597 def __repr__(self): 2598 return _pywrapcp.SearchMonitor___repr__(self) 2599 2600 def __str__(self): 2601 return _pywrapcp.SearchMonitor___str__(self) 2602 def __disown__(self): 2603 self.this.disown() 2604 _pywrapcp.disown_SearchMonitor(self) 2605 return weakref.proxy(self)
A search monitor is a simple set of callbacks to monitor all search events
2497 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2508 def EnterSearch(self): 2509 r"""Beginning of the search.""" 2510 return _pywrapcp.SearchMonitor_EnterSearch(self)
Beginning of the search.
2512 def RestartSearch(self): 2513 r"""Restart the search.""" 2514 return _pywrapcp.SearchMonitor_RestartSearch(self)
Restart the search.
2516 def ExitSearch(self): 2517 r"""End of the search.""" 2518 return _pywrapcp.SearchMonitor_ExitSearch(self)
End of the search.
2520 def BeginNextDecision(self, b): 2521 r"""Before calling DecisionBuilder::Next.""" 2522 return _pywrapcp.SearchMonitor_BeginNextDecision(self, b)
Before calling DecisionBuilder::Next.
2524 def EndNextDecision(self, b, d): 2525 r"""After calling DecisionBuilder::Next, along with the returned decision.""" 2526 return _pywrapcp.SearchMonitor_EndNextDecision(self, b, d)
After calling DecisionBuilder::Next, along with the returned decision.
2528 def ApplyDecision(self, d): 2529 r"""Before applying the decision.""" 2530 return _pywrapcp.SearchMonitor_ApplyDecision(self, d)
Before applying the decision.
2532 def RefuteDecision(self, d): 2533 r"""Before refuting the decision.""" 2534 return _pywrapcp.SearchMonitor_RefuteDecision(self, d)
Before refuting the decision.
2536 def AfterDecision(self, d, apply): 2537 r""" 2538 Just after refuting or applying the decision, apply is true after Apply. 2539 This is called only if the Apply() or Refute() methods have not failed. 2540 """ 2541 return _pywrapcp.SearchMonitor_AfterDecision(self, d, apply)
Just after refuting or applying the decision, apply is true after Apply. This is called only if the Apply() or Refute() methods have not failed.
2543 def BeginFail(self): 2544 r"""Just when the failure occurs.""" 2545 return _pywrapcp.SearchMonitor_BeginFail(self)
Just when the failure occurs.
2547 def EndFail(self): 2548 r"""After completing the backtrack.""" 2549 return _pywrapcp.SearchMonitor_EndFail(self)
After completing the backtrack.
2551 def BeginInitialPropagation(self): 2552 r"""Before the initial propagation.""" 2553 return _pywrapcp.SearchMonitor_BeginInitialPropagation(self)
Before the initial propagation.
2555 def EndInitialPropagation(self): 2556 r"""After the initial propagation.""" 2557 return _pywrapcp.SearchMonitor_EndInitialPropagation(self)
After the initial propagation.
2559 def AcceptSolution(self): 2560 r""" 2561 This method is called when a solution is found. It asserts whether the 2562 solution is valid. A value of false indicates that the solution 2563 should be discarded. 2564 """ 2565 return _pywrapcp.SearchMonitor_AcceptSolution(self)
This method is called when a solution is found. It asserts whether the solution is valid. A value of false indicates that the solution should be discarded.
2567 def AtSolution(self): 2568 r""" 2569 This method is called when a valid solution is found. If the 2570 return value is true, then search will resume after. If the result 2571 is false, then search will stop there. 2572 """ 2573 return _pywrapcp.SearchMonitor_AtSolution(self)
This method is called when a valid solution is found. If the return value is true, then search will resume after. If the result is false, then search will stop there.
2575 def NoMoreSolutions(self): 2576 r"""When the search tree is finished.""" 2577 return _pywrapcp.SearchMonitor_NoMoreSolutions(self)
When the search tree is finished.
2583 def AcceptNeighbor(self): 2584 r"""After accepting a neighbor during local search.""" 2585 return _pywrapcp.SearchMonitor_AcceptNeighbor(self)
After accepting a neighbor during local search.
2587 def ProgressPercent(self): 2588 r""" 2589 Returns a percentage representing the propress of the search before 2590 reaching limits. 2591 """ 2592 return _pywrapcp.SearchMonitor_ProgressPercent(self)
Returns a percentage representing the propress of the search before reaching limits.
Inherited Members
2609class IntExpr(PropagationBaseObject): 2610 r""" 2611 The class IntExpr is the base of all integer expressions in 2612 constraint programming. 2613 It contains the basic protocol for an expression: 2614 - setting and modifying its bound 2615 - querying if it is bound 2616 - listening to events modifying its bounds 2617 - casting it into a variable (instance of IntVar) 2618 """ 2619 2620 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2621 2622 def __init__(self, *args, **kwargs): 2623 raise AttributeError("No constructor defined - class is abstract") 2624 2625 def Min(self): 2626 return _pywrapcp.IntExpr_Min(self) 2627 2628 def SetMin(self, m): 2629 return _pywrapcp.IntExpr_SetMin(self, m) 2630 2631 def Max(self): 2632 return _pywrapcp.IntExpr_Max(self) 2633 2634 def SetMax(self, m): 2635 return _pywrapcp.IntExpr_SetMax(self, m) 2636 2637 def SetRange(self, l, u): 2638 r"""This method sets both the min and the max of the expression.""" 2639 return _pywrapcp.IntExpr_SetRange(self, l, u) 2640 2641 def SetValue(self, v): 2642 r"""This method sets the value of the expression.""" 2643 return _pywrapcp.IntExpr_SetValue(self, v) 2644 2645 def Bound(self): 2646 r"""Returns true if the min and the max of the expression are equal.""" 2647 return _pywrapcp.IntExpr_Bound(self) 2648 2649 def IsVar(self): 2650 r"""Returns true if the expression is indeed a variable.""" 2651 return _pywrapcp.IntExpr_IsVar(self) 2652 2653 def Var(self): 2654 r"""Creates a variable from the expression.""" 2655 return _pywrapcp.IntExpr_Var(self) 2656 2657 def VarWithName(self, name): 2658 r""" 2659 Creates a variable from the expression and set the name of the 2660 resulting var. If the expression is already a variable, then it 2661 will set the name of the expression, possibly overwriting it. 2662 This is just a shortcut to Var() followed by set_name(). 2663 """ 2664 return _pywrapcp.IntExpr_VarWithName(self, name) 2665 2666 def WhenRange(self, *args): 2667 r""" 2668 *Overload 1:* 2669 Attach a demon that will watch the min or the max of the expression. 2670 2671 | 2672 2673 *Overload 2:* 2674 Attach a demon that will watch the min or the max of the expression. 2675 """ 2676 return _pywrapcp.IntExpr_WhenRange(self, *args) 2677 2678 def __repr__(self): 2679 return _pywrapcp.IntExpr___repr__(self) 2680 2681 def __str__(self): 2682 return _pywrapcp.IntExpr___str__(self) 2683 2684 def __add__(self, *args): 2685 return _pywrapcp.IntExpr___add__(self, *args) 2686 2687 def __radd__(self, v): 2688 return _pywrapcp.IntExpr___radd__(self, v) 2689 2690 def __sub__(self, *args): 2691 return _pywrapcp.IntExpr___sub__(self, *args) 2692 2693 def __rsub__(self, v): 2694 return _pywrapcp.IntExpr___rsub__(self, v) 2695 2696 def __mul__(self, *args): 2697 return _pywrapcp.IntExpr___mul__(self, *args) 2698 2699 def __rmul__(self, v): 2700 return _pywrapcp.IntExpr___rmul__(self, v) 2701 2702 def __floordiv__(self, *args): 2703 return _pywrapcp.IntExpr___floordiv__(self, *args) 2704 2705 def __mod__(self, *args): 2706 return _pywrapcp.IntExpr___mod__(self, *args) 2707 2708 def __neg__(self): 2709 return _pywrapcp.IntExpr___neg__(self) 2710 2711 def __abs__(self): 2712 return _pywrapcp.IntExpr___abs__(self) 2713 2714 def Square(self): 2715 return _pywrapcp.IntExpr_Square(self) 2716 2717 def __eq__(self, *args): 2718 return _pywrapcp.IntExpr___eq__(self, *args) 2719 2720 def __ne__(self, *args): 2721 return _pywrapcp.IntExpr___ne__(self, *args) 2722 2723 def __ge__(self, *args): 2724 return _pywrapcp.IntExpr___ge__(self, *args) 2725 2726 def __gt__(self, *args): 2727 return _pywrapcp.IntExpr___gt__(self, *args) 2728 2729 def __le__(self, *args): 2730 return _pywrapcp.IntExpr___le__(self, *args) 2731 2732 def __lt__(self, *args): 2733 return _pywrapcp.IntExpr___lt__(self, *args) 2734 2735 def MapTo(self, vars): 2736 return _pywrapcp.IntExpr_MapTo(self, vars) 2737 2738 def IndexOf(self, *args): 2739 return _pywrapcp.IntExpr_IndexOf(self, *args) 2740 2741 def IsMember(self, values): 2742 return _pywrapcp.IntExpr_IsMember(self, values) 2743 2744 def Member(self, values): 2745 return _pywrapcp.IntExpr_Member(self, values) 2746 2747 def NotMember(self, starts, ends): 2748 return _pywrapcp.IntExpr_NotMember(self, starts, ends)
The class IntExpr is the base of all integer expressions in constraint programming.
It contains the basic protocol for an expression:
- setting and modifying its bound
- querying if it is bound
- listening to events modifying its bounds
- casting it into a variable (instance of IntVar)
2620 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2637 def SetRange(self, l, u): 2638 r"""This method sets both the min and the max of the expression.""" 2639 return _pywrapcp.IntExpr_SetRange(self, l, u)
This method sets both the min and the max of the expression.
2641 def SetValue(self, v): 2642 r"""This method sets the value of the expression.""" 2643 return _pywrapcp.IntExpr_SetValue(self, v)
This method sets the value of the expression.
2645 def Bound(self): 2646 r"""Returns true if the min and the max of the expression are equal.""" 2647 return _pywrapcp.IntExpr_Bound(self)
Returns true if the min and the max of the expression are equal.
2649 def IsVar(self): 2650 r"""Returns true if the expression is indeed a variable.""" 2651 return _pywrapcp.IntExpr_IsVar(self)
Returns true if the expression is indeed a variable.
2653 def Var(self): 2654 r"""Creates a variable from the expression.""" 2655 return _pywrapcp.IntExpr_Var(self)
Creates a variable from the expression.
2657 def VarWithName(self, name): 2658 r""" 2659 Creates a variable from the expression and set the name of the 2660 resulting var. If the expression is already a variable, then it 2661 will set the name of the expression, possibly overwriting it. 2662 This is just a shortcut to Var() followed by set_name(). 2663 """ 2664 return _pywrapcp.IntExpr_VarWithName(self, name)
Creates a variable from the expression and set the name of the resulting var. If the expression is already a variable, then it will set the name of the expression, possibly overwriting it. This is just a shortcut to Var() followed by set_name().
2666 def WhenRange(self, *args): 2667 r""" 2668 *Overload 1:* 2669 Attach a demon that will watch the min or the max of the expression. 2670 2671 | 2672 2673 *Overload 2:* 2674 Attach a demon that will watch the min or the max of the expression. 2675 """ 2676 return _pywrapcp.IntExpr_WhenRange(self, *args)
Overload 1: Attach a demon that will watch the min or the max of the expression.
|
Overload 2: Attach a demon that will watch the min or the max of the expression.
Inherited Members
2752class IntVarIterator(BaseObject): 2753 r""" 2754 The class Iterator has two direct subclasses. HoleIterators 2755 iterates over all holes, that is value removed between the 2756 current min and max of the variable since the last time the 2757 variable was processed in the queue. DomainIterators iterates 2758 over all elements of the variable domain. Both iterators are not 2759 robust to domain changes. Hole iterators can also report values outside 2760 the current min and max of the variable. 2761 HoleIterators should only be called from a demon attached to the 2762 variable that has created this iterator. 2763 IntVar* current_var; 2764 std::unique_ptr<IntVarIterator> it(current_var->MakeHoleIterator(false)); 2765 for (const int64_t hole : InitAndGetValues(it)) { 2766 use the hole 2767 } 2768 """ 2769 2770 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2771 2772 def __init__(self, *args, **kwargs): 2773 raise AttributeError("No constructor defined - class is abstract") 2774 __repr__ = _swig_repr 2775 2776 def Init(self): 2777 r"""This method must be called before each loop.""" 2778 return _pywrapcp.IntVarIterator_Init(self) 2779 2780 def Ok(self): 2781 r"""This method indicates if we can call Value() or not.""" 2782 return _pywrapcp.IntVarIterator_Ok(self) 2783 2784 def Value(self): 2785 r"""This method returns the current value of the iterator.""" 2786 return _pywrapcp.IntVarIterator_Value(self) 2787 2788 def Next(self): 2789 r"""This method moves the iterator to the next value.""" 2790 return _pywrapcp.IntVarIterator_Next(self) 2791 2792 def DebugString(self): 2793 r"""Pretty Print.""" 2794 return _pywrapcp.IntVarIterator_DebugString(self) 2795 2796 def __iter__(self): 2797 self.Init() 2798 return self 2799 2800 def next(self): 2801 if self.Ok(): 2802 result = self.Value() 2803 self.Next() 2804 return result 2805 else: 2806 raise StopIteration() 2807 2808 def __next__(self): 2809 return self.next()
The class Iterator has two direct subclasses. HoleIterators
iterates over all holes, that is value removed between the
current min and max of the variable since the last time the
variable was processed in the queue. DomainIterators iterates
over all elements of the variable domain. Both iterators are not
robust to domain changes. Hole iterators can also report values outside
the current min and max of the variable.
HoleIterators should only be called from a demon attached to the
variable that has created this iterator.
IntVar* current_var;
std::unique_ptr
2770 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2776 def Init(self): 2777 r"""This method must be called before each loop.""" 2778 return _pywrapcp.IntVarIterator_Init(self)
This method must be called before each loop.
2780 def Ok(self): 2781 r"""This method indicates if we can call Value() or not.""" 2782 return _pywrapcp.IntVarIterator_Ok(self)
This method indicates if we can call Value() or not.
2784 def Value(self): 2785 r"""This method returns the current value of the iterator.""" 2786 return _pywrapcp.IntVarIterator_Value(self)
This method returns the current value of the iterator.
2788 def Next(self): 2789 r"""This method moves the iterator to the next value.""" 2790 return _pywrapcp.IntVarIterator_Next(self)
This method moves the iterator to the next value.
2814class IntVar(IntExpr): 2815 r""" 2816 The class IntVar is a subset of IntExpr. In addition to the 2817 IntExpr protocol, it offers persistence, removing values from the domains, 2818 and a finer model for events. 2819 """ 2820 2821 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2822 2823 def __init__(self, *args, **kwargs): 2824 raise AttributeError("No constructor defined - class is abstract") 2825 2826 def IsVar(self): 2827 return _pywrapcp.IntVar_IsVar(self) 2828 2829 def Var(self): 2830 return _pywrapcp.IntVar_Var(self) 2831 2832 def Value(self): 2833 r""" 2834 This method returns the value of the variable. This method checks 2835 before that the variable is bound. 2836 """ 2837 return _pywrapcp.IntVar_Value(self) 2838 2839 def RemoveValue(self, v): 2840 r"""This method removes the value 'v' from the domain of the variable.""" 2841 return _pywrapcp.IntVar_RemoveValue(self, v) 2842 2843 def RemoveInterval(self, l, u): 2844 r""" 2845 This method removes the interval 'l' .. 'u' from the domain of 2846 the variable. It assumes that 'l' <= 'u'. 2847 """ 2848 return _pywrapcp.IntVar_RemoveInterval(self, l, u) 2849 2850 def RemoveValues(self, values): 2851 r"""This method remove the values from the domain of the variable.""" 2852 return _pywrapcp.IntVar_RemoveValues(self, values) 2853 2854 def SetValues(self, values): 2855 r"""This method intersects the current domain with the values in the array.""" 2856 return _pywrapcp.IntVar_SetValues(self, values) 2857 2858 def WhenBound(self, *args): 2859 r""" 2860 *Overload 1:* 2861 This method attaches a demon that will be awakened when the 2862 variable is bound. 2863 2864 | 2865 2866 *Overload 2:* 2867 This method attaches a closure that will be awakened when the 2868 variable is bound. 2869 """ 2870 return _pywrapcp.IntVar_WhenBound(self, *args) 2871 2872 def WhenDomain(self, *args): 2873 r""" 2874 *Overload 1:* 2875 This method attaches a demon that will watch any domain 2876 modification of the domain of the variable. 2877 2878 | 2879 2880 *Overload 2:* 2881 This method attaches a closure that will watch any domain 2882 modification of the domain of the variable. 2883 """ 2884 return _pywrapcp.IntVar_WhenDomain(self, *args) 2885 2886 def Size(self): 2887 r"""This method returns the number of values in the domain of the variable.""" 2888 return _pywrapcp.IntVar_Size(self) 2889 2890 def Contains(self, v): 2891 r""" 2892 This method returns whether the value 'v' is in the domain of the 2893 variable. 2894 """ 2895 return _pywrapcp.IntVar_Contains(self, v) 2896 2897 def HoleIteratorAux(self, reversible): 2898 r""" 2899 Creates a hole iterator. When 'reversible' is false, the returned 2900 object is created on the normal C++ heap and the solver does NOT 2901 take ownership of the object. 2902 """ 2903 return _pywrapcp.IntVar_HoleIteratorAux(self, reversible) 2904 2905 def DomainIteratorAux(self, reversible): 2906 r""" 2907 Creates a domain iterator. When 'reversible' is false, the 2908 returned object is created on the normal C++ heap and the solver 2909 does NOT take ownership of the object. 2910 """ 2911 return _pywrapcp.IntVar_DomainIteratorAux(self, reversible) 2912 2913 def OldMin(self): 2914 r"""Returns the previous min.""" 2915 return _pywrapcp.IntVar_OldMin(self) 2916 2917 def OldMax(self): 2918 r"""Returns the previous max.""" 2919 return _pywrapcp.IntVar_OldMax(self) 2920 2921 def __repr__(self): 2922 return _pywrapcp.IntVar___repr__(self) 2923 2924 def __str__(self): 2925 return _pywrapcp.IntVar___str__(self) 2926 2927 def DomainIterator(self): 2928 return iter(self.DomainIteratorAux(False)) 2929 2930 def HoleIterator(self): 2931 return iter(self.HoleIteratorAux(False))
The class IntVar is a subset of IntExpr. In addition to the IntExpr protocol, it offers persistence, removing values from the domains, and a finer model for events.
2821 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2832 def Value(self): 2833 r""" 2834 This method returns the value of the variable. This method checks 2835 before that the variable is bound. 2836 """ 2837 return _pywrapcp.IntVar_Value(self)
This method returns the value of the variable. This method checks before that the variable is bound.
2839 def RemoveValue(self, v): 2840 r"""This method removes the value 'v' from the domain of the variable.""" 2841 return _pywrapcp.IntVar_RemoveValue(self, v)
This method removes the value 'v' from the domain of the variable.
2843 def RemoveInterval(self, l, u): 2844 r""" 2845 This method removes the interval 'l' .. 'u' from the domain of 2846 the variable. It assumes that 'l' <= 'u'. 2847 """ 2848 return _pywrapcp.IntVar_RemoveInterval(self, l, u)
This method removes the interval 'l' .. 'u' from the domain of the variable. It assumes that 'l' <= 'u'.
2850 def RemoveValues(self, values): 2851 r"""This method remove the values from the domain of the variable.""" 2852 return _pywrapcp.IntVar_RemoveValues(self, values)
This method remove the values from the domain of the variable.
2854 def SetValues(self, values): 2855 r"""This method intersects the current domain with the values in the array.""" 2856 return _pywrapcp.IntVar_SetValues(self, values)
This method intersects the current domain with the values in the array.
2858 def WhenBound(self, *args): 2859 r""" 2860 *Overload 1:* 2861 This method attaches a demon that will be awakened when the 2862 variable is bound. 2863 2864 | 2865 2866 *Overload 2:* 2867 This method attaches a closure that will be awakened when the 2868 variable is bound. 2869 """ 2870 return _pywrapcp.IntVar_WhenBound(self, *args)
Overload 1: This method attaches a demon that will be awakened when the variable is bound.
|
Overload 2: This method attaches a closure that will be awakened when the variable is bound.
2872 def WhenDomain(self, *args): 2873 r""" 2874 *Overload 1:* 2875 This method attaches a demon that will watch any domain 2876 modification of the domain of the variable. 2877 2878 | 2879 2880 *Overload 2:* 2881 This method attaches a closure that will watch any domain 2882 modification of the domain of the variable. 2883 """ 2884 return _pywrapcp.IntVar_WhenDomain(self, *args)
Overload 1: This method attaches a demon that will watch any domain modification of the domain of the variable.
|
Overload 2: This method attaches a closure that will watch any domain modification of the domain of the variable.
2886 def Size(self): 2887 r"""This method returns the number of values in the domain of the variable.""" 2888 return _pywrapcp.IntVar_Size(self)
This method returns the number of values in the domain of the variable.
2890 def Contains(self, v): 2891 r""" 2892 This method returns whether the value 'v' is in the domain of the 2893 variable. 2894 """ 2895 return _pywrapcp.IntVar_Contains(self, v)
This method returns whether the value 'v' is in the domain of the variable.
2897 def HoleIteratorAux(self, reversible): 2898 r""" 2899 Creates a hole iterator. When 'reversible' is false, the returned 2900 object is created on the normal C++ heap and the solver does NOT 2901 take ownership of the object. 2902 """ 2903 return _pywrapcp.IntVar_HoleIteratorAux(self, reversible)
Creates a hole iterator. When 'reversible' is false, the returned object is created on the normal C++ heap and the solver does NOT take ownership of the object.
2905 def DomainIteratorAux(self, reversible): 2906 r""" 2907 Creates a domain iterator. When 'reversible' is false, the 2908 returned object is created on the normal C++ heap and the solver 2909 does NOT take ownership of the object. 2910 """ 2911 return _pywrapcp.IntVar_DomainIteratorAux(self, reversible)
Creates a domain iterator. When 'reversible' is false, the returned object is created on the normal C++ heap and the solver does NOT take ownership of the object.
2913 def OldMin(self): 2914 r"""Returns the previous min.""" 2915 return _pywrapcp.IntVar_OldMin(self)
Returns the previous min.
2917 def OldMax(self): 2918 r"""Returns the previous max.""" 2919 return _pywrapcp.IntVar_OldMax(self)
Returns the previous max.
2936class SolutionCollector(SearchMonitor): 2937 r""" 2938 This class is the root class of all solution collectors. 2939 It implements a basic query API to be used independently 2940 of the collector used. 2941 """ 2942 2943 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 2944 2945 def __init__(self, *args, **kwargs): 2946 raise AttributeError("No constructor defined") 2947 __repr__ = _swig_repr 2948 2949 def DebugString(self): 2950 return _pywrapcp.SolutionCollector_DebugString(self) 2951 2952 def Add(self, *args): 2953 r"""Add API.""" 2954 return _pywrapcp.SolutionCollector_Add(self, *args) 2955 2956 def AddObjective(self, objective): 2957 return _pywrapcp.SolutionCollector_AddObjective(self, objective) 2958 2959 def EnterSearch(self): 2960 r"""Beginning of the search.""" 2961 return _pywrapcp.SolutionCollector_EnterSearch(self) 2962 2963 def SolutionCount(self): 2964 r"""Returns how many solutions were stored during the search.""" 2965 return _pywrapcp.SolutionCollector_SolutionCount(self) 2966 2967 def Solution(self, n): 2968 r"""Returns the nth solution.""" 2969 return _pywrapcp.SolutionCollector_Solution(self, n) 2970 2971 def WallTime(self, n): 2972 r"""Returns the wall time in ms for the nth solution.""" 2973 return _pywrapcp.SolutionCollector_WallTime(self, n) 2974 2975 def Branches(self, n): 2976 r"""Returns the number of branches when the nth solution was found.""" 2977 return _pywrapcp.SolutionCollector_Branches(self, n) 2978 2979 def Failures(self, n): 2980 r""" 2981 Returns the number of failures encountered at the time of the nth 2982 solution. 2983 """ 2984 return _pywrapcp.SolutionCollector_Failures(self, n) 2985 2986 def ObjectiveValue(self, n): 2987 r"""Returns the objective value of the nth solution.""" 2988 return _pywrapcp.SolutionCollector_ObjectiveValue(self, n) 2989 2990 def Value(self, n, var): 2991 r"""This is a shortcut to get the Value of 'var' in the nth solution.""" 2992 return _pywrapcp.SolutionCollector_Value(self, n, var) 2993 2994 def StartValue(self, n, var): 2995 r"""This is a shortcut to get the StartValue of 'var' in the nth solution.""" 2996 return _pywrapcp.SolutionCollector_StartValue(self, n, var) 2997 2998 def EndValue(self, n, var): 2999 r"""This is a shortcut to get the EndValue of 'var' in the nth solution.""" 3000 return _pywrapcp.SolutionCollector_EndValue(self, n, var) 3001 3002 def DurationValue(self, n, var): 3003 r"""This is a shortcut to get the DurationValue of 'var' in the nth solution.""" 3004 return _pywrapcp.SolutionCollector_DurationValue(self, n, var) 3005 3006 def PerformedValue(self, n, var): 3007 r"""This is a shortcut to get the PerformedValue of 'var' in the nth solution.""" 3008 return _pywrapcp.SolutionCollector_PerformedValue(self, n, var) 3009 3010 def ForwardSequence(self, n, var): 3011 r""" 3012 This is a shortcut to get the ForwardSequence of 'var' in the 3013 nth solution. The forward sequence is the list of ranked interval 3014 variables starting from the start of the sequence. 3015 """ 3016 return _pywrapcp.SolutionCollector_ForwardSequence(self, n, var) 3017 3018 def BackwardSequence(self, n, var): 3019 r""" 3020 This is a shortcut to get the BackwardSequence of 'var' in the 3021 nth solution. The backward sequence is the list of ranked interval 3022 variables starting from the end of the sequence. 3023 """ 3024 return _pywrapcp.SolutionCollector_BackwardSequence(self, n, var) 3025 3026 def Unperformed(self, n, var): 3027 r""" 3028 This is a shortcut to get the list of unperformed of 'var' in the 3029 nth solution. 3030 """ 3031 return _pywrapcp.SolutionCollector_Unperformed(self, n, var)
This class is the root class of all solution collectors. It implements a basic query API to be used independently of the collector used.
2943 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
2952 def Add(self, *args): 2953 r"""Add API.""" 2954 return _pywrapcp.SolutionCollector_Add(self, *args)
Add API.
2959 def EnterSearch(self): 2960 r"""Beginning of the search.""" 2961 return _pywrapcp.SolutionCollector_EnterSearch(self)
Beginning of the search.
2963 def SolutionCount(self): 2964 r"""Returns how many solutions were stored during the search.""" 2965 return _pywrapcp.SolutionCollector_SolutionCount(self)
Returns how many solutions were stored during the search.
2967 def Solution(self, n): 2968 r"""Returns the nth solution.""" 2969 return _pywrapcp.SolutionCollector_Solution(self, n)
Returns the nth solution.
2971 def WallTime(self, n): 2972 r"""Returns the wall time in ms for the nth solution.""" 2973 return _pywrapcp.SolutionCollector_WallTime(self, n)
Returns the wall time in ms for the nth solution.
2975 def Branches(self, n): 2976 r"""Returns the number of branches when the nth solution was found.""" 2977 return _pywrapcp.SolutionCollector_Branches(self, n)
Returns the number of branches when the nth solution was found.
2979 def Failures(self, n): 2980 r""" 2981 Returns the number of failures encountered at the time of the nth 2982 solution. 2983 """ 2984 return _pywrapcp.SolutionCollector_Failures(self, n)
Returns the number of failures encountered at the time of the nth solution.
2986 def ObjectiveValue(self, n): 2987 r"""Returns the objective value of the nth solution.""" 2988 return _pywrapcp.SolutionCollector_ObjectiveValue(self, n)
Returns the objective value of the nth solution.
2990 def Value(self, n, var): 2991 r"""This is a shortcut to get the Value of 'var' in the nth solution.""" 2992 return _pywrapcp.SolutionCollector_Value(self, n, var)
This is a shortcut to get the Value of 'var' in the nth solution.
2994 def StartValue(self, n, var): 2995 r"""This is a shortcut to get the StartValue of 'var' in the nth solution.""" 2996 return _pywrapcp.SolutionCollector_StartValue(self, n, var)
This is a shortcut to get the StartValue of 'var' in the nth solution.
2998 def EndValue(self, n, var): 2999 r"""This is a shortcut to get the EndValue of 'var' in the nth solution.""" 3000 return _pywrapcp.SolutionCollector_EndValue(self, n, var)
This is a shortcut to get the EndValue of 'var' in the nth solution.
3002 def DurationValue(self, n, var): 3003 r"""This is a shortcut to get the DurationValue of 'var' in the nth solution.""" 3004 return _pywrapcp.SolutionCollector_DurationValue(self, n, var)
This is a shortcut to get the DurationValue of 'var' in the nth solution.
3006 def PerformedValue(self, n, var): 3007 r"""This is a shortcut to get the PerformedValue of 'var' in the nth solution.""" 3008 return _pywrapcp.SolutionCollector_PerformedValue(self, n, var)
This is a shortcut to get the PerformedValue of 'var' in the nth solution.
3010 def ForwardSequence(self, n, var): 3011 r""" 3012 This is a shortcut to get the ForwardSequence of 'var' in the 3013 nth solution. The forward sequence is the list of ranked interval 3014 variables starting from the start of the sequence. 3015 """ 3016 return _pywrapcp.SolutionCollector_ForwardSequence(self, n, var)
This is a shortcut to get the ForwardSequence of 'var' in the nth solution. The forward sequence is the list of ranked interval variables starting from the start of the sequence.
3018 def BackwardSequence(self, n, var): 3019 r""" 3020 This is a shortcut to get the BackwardSequence of 'var' in the 3021 nth solution. The backward sequence is the list of ranked interval 3022 variables starting from the end of the sequence. 3023 """ 3024 return _pywrapcp.SolutionCollector_BackwardSequence(self, n, var)
This is a shortcut to get the BackwardSequence of 'var' in the nth solution. The backward sequence is the list of ranked interval variables starting from the end of the sequence.
3026 def Unperformed(self, n, var): 3027 r""" 3028 This is a shortcut to get the list of unperformed of 'var' in the 3029 nth solution. 3030 """ 3031 return _pywrapcp.SolutionCollector_Unperformed(self, n, var)
This is a shortcut to get the list of unperformed of 'var' in the nth solution.
Inherited Members
3035class OptimizeVar(object): 3036 r""" 3037 This class encapsulates an objective. It requires the direction 3038 (minimize or maximize), the variable to optimize, and the 3039 improvement step. 3040 """ 3041 3042 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3043 3044 def __init__(self, *args, **kwargs): 3045 raise AttributeError("No constructor defined") 3046 __repr__ = _swig_repr 3047 3048 def Best(self): 3049 r"""Returns the best value found during search.""" 3050 return _pywrapcp.OptimizeVar_Best(self) 3051 3052 def BeginNextDecision(self, db): 3053 r"""Internal methods.""" 3054 return _pywrapcp.OptimizeVar_BeginNextDecision(self, db) 3055 3056 def RefuteDecision(self, d): 3057 return _pywrapcp.OptimizeVar_RefuteDecision(self, d) 3058 3059 def AtSolution(self): 3060 return _pywrapcp.OptimizeVar_AtSolution(self) 3061 3062 def AcceptSolution(self): 3063 return _pywrapcp.OptimizeVar_AcceptSolution(self) 3064 3065 def DebugString(self): 3066 return _pywrapcp.OptimizeVar_DebugString(self) 3067 __swig_destroy__ = _pywrapcp.delete_OptimizeVar
This class encapsulates an objective. It requires the direction (minimize or maximize), the variable to optimize, and the improvement step.
3042 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
3048 def Best(self): 3049 r"""Returns the best value found during search.""" 3050 return _pywrapcp.OptimizeVar_Best(self)
Returns the best value found during search.
3052 def BeginNextDecision(self, db): 3053 r"""Internal methods.""" 3054 return _pywrapcp.OptimizeVar_BeginNextDecision(self, db)
Internal methods.
3071class SearchLimit(SearchMonitor): 3072 r"""Base class of all search limits.""" 3073 3074 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3075 3076 def __init__(self, *args, **kwargs): 3077 raise AttributeError("No constructor defined - class is abstract") 3078 __repr__ = _swig_repr 3079 __swig_destroy__ = _pywrapcp.delete_SearchLimit 3080 3081 def Crossed(self): 3082 r"""Returns true if the limit has been crossed.""" 3083 return _pywrapcp.SearchLimit_Crossed(self) 3084 3085 def Check(self): 3086 r""" 3087 This method is called to check the status of the limit. A return 3088 value of true indicates that we have indeed crossed the limit. In 3089 that case, this method will not be called again and the remaining 3090 search will be discarded. 3091 """ 3092 return _pywrapcp.SearchLimit_Check(self) 3093 3094 def Init(self): 3095 r"""This method is called when the search limit is initialized.""" 3096 return _pywrapcp.SearchLimit_Init(self) 3097 3098 def EnterSearch(self): 3099 r"""Internal methods.""" 3100 return _pywrapcp.SearchLimit_EnterSearch(self) 3101 3102 def BeginNextDecision(self, b): 3103 return _pywrapcp.SearchLimit_BeginNextDecision(self, b) 3104 3105 def RefuteDecision(self, d): 3106 return _pywrapcp.SearchLimit_RefuteDecision(self, d) 3107 3108 def DebugString(self): 3109 return _pywrapcp.SearchLimit_DebugString(self)
Base class of all search limits.
3074 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
3081 def Crossed(self): 3082 r"""Returns true if the limit has been crossed.""" 3083 return _pywrapcp.SearchLimit_Crossed(self)
Returns true if the limit has been crossed.
3085 def Check(self): 3086 r""" 3087 This method is called to check the status of the limit. A return 3088 value of true indicates that we have indeed crossed the limit. In 3089 that case, this method will not be called again and the remaining 3090 search will be discarded. 3091 """ 3092 return _pywrapcp.SearchLimit_Check(self)
This method is called to check the status of the limit. A return value of true indicates that we have indeed crossed the limit. In that case, this method will not be called again and the remaining search will be discarded.
3094 def Init(self): 3095 r"""This method is called when the search limit is initialized.""" 3096 return _pywrapcp.SearchLimit_Init(self)
This method is called when the search limit is initialized.
3098 def EnterSearch(self): 3099 r"""Internal methods.""" 3100 return _pywrapcp.SearchLimit_EnterSearch(self)
Internal methods.
3113class IntervalVar(PropagationBaseObject): 3114 r""" 3115 Interval variables are often used in scheduling. The main characteristics 3116 of an IntervalVar are the start position, duration, and end 3117 date. All these characteristics can be queried and set, and demons can 3118 be posted on their modifications. 3119 3120 An important aspect is optionality: an IntervalVar can be performed or not. 3121 If unperformed, then it simply does not exist, and its characteristics 3122 cannot be accessed any more. An interval var is automatically marked 3123 as unperformed when it is not consistent anymore (start greater 3124 than end, duration < 0...) 3125 """ 3126 3127 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3128 3129 def __init__(self, *args, **kwargs): 3130 raise AttributeError("No constructor defined - class is abstract") 3131 3132 def StartMin(self): 3133 r""" 3134 These methods query, set, and watch the start position of the 3135 interval var. 3136 """ 3137 return _pywrapcp.IntervalVar_StartMin(self) 3138 3139 def StartMax(self): 3140 return _pywrapcp.IntervalVar_StartMax(self) 3141 3142 def SetStartMin(self, m): 3143 return _pywrapcp.IntervalVar_SetStartMin(self, m) 3144 3145 def SetStartMax(self, m): 3146 return _pywrapcp.IntervalVar_SetStartMax(self, m) 3147 3148 def SetStartRange(self, mi, ma): 3149 return _pywrapcp.IntervalVar_SetStartRange(self, mi, ma) 3150 3151 def OldStartMin(self): 3152 return _pywrapcp.IntervalVar_OldStartMin(self) 3153 3154 def OldStartMax(self): 3155 return _pywrapcp.IntervalVar_OldStartMax(self) 3156 3157 def WhenStartRange(self, *args): 3158 return _pywrapcp.IntervalVar_WhenStartRange(self, *args) 3159 3160 def WhenStartBound(self, *args): 3161 return _pywrapcp.IntervalVar_WhenStartBound(self, *args) 3162 3163 def DurationMin(self): 3164 r"""These methods query, set, and watch the duration of the interval var.""" 3165 return _pywrapcp.IntervalVar_DurationMin(self) 3166 3167 def DurationMax(self): 3168 return _pywrapcp.IntervalVar_DurationMax(self) 3169 3170 def SetDurationMin(self, m): 3171 return _pywrapcp.IntervalVar_SetDurationMin(self, m) 3172 3173 def SetDurationMax(self, m): 3174 return _pywrapcp.IntervalVar_SetDurationMax(self, m) 3175 3176 def SetDurationRange(self, mi, ma): 3177 return _pywrapcp.IntervalVar_SetDurationRange(self, mi, ma) 3178 3179 def OldDurationMin(self): 3180 return _pywrapcp.IntervalVar_OldDurationMin(self) 3181 3182 def OldDurationMax(self): 3183 return _pywrapcp.IntervalVar_OldDurationMax(self) 3184 3185 def WhenDurationRange(self, *args): 3186 return _pywrapcp.IntervalVar_WhenDurationRange(self, *args) 3187 3188 def WhenDurationBound(self, *args): 3189 return _pywrapcp.IntervalVar_WhenDurationBound(self, *args) 3190 3191 def EndMin(self): 3192 r"""These methods query, set, and watch the end position of the interval var.""" 3193 return _pywrapcp.IntervalVar_EndMin(self) 3194 3195 def EndMax(self): 3196 return _pywrapcp.IntervalVar_EndMax(self) 3197 3198 def SetEndMin(self, m): 3199 return _pywrapcp.IntervalVar_SetEndMin(self, m) 3200 3201 def SetEndMax(self, m): 3202 return _pywrapcp.IntervalVar_SetEndMax(self, m) 3203 3204 def SetEndRange(self, mi, ma): 3205 return _pywrapcp.IntervalVar_SetEndRange(self, mi, ma) 3206 3207 def OldEndMin(self): 3208 return _pywrapcp.IntervalVar_OldEndMin(self) 3209 3210 def OldEndMax(self): 3211 return _pywrapcp.IntervalVar_OldEndMax(self) 3212 3213 def WhenEndRange(self, *args): 3214 return _pywrapcp.IntervalVar_WhenEndRange(self, *args) 3215 3216 def WhenEndBound(self, *args): 3217 return _pywrapcp.IntervalVar_WhenEndBound(self, *args) 3218 3219 def MustBePerformed(self): 3220 r""" 3221 These methods query, set, and watch the performed status of the 3222 interval var. 3223 """ 3224 return _pywrapcp.IntervalVar_MustBePerformed(self) 3225 3226 def MayBePerformed(self): 3227 return _pywrapcp.IntervalVar_MayBePerformed(self) 3228 3229 def CannotBePerformed(self): 3230 return _pywrapcp.IntervalVar_CannotBePerformed(self) 3231 3232 def IsPerformedBound(self): 3233 return _pywrapcp.IntervalVar_IsPerformedBound(self) 3234 3235 def SetPerformed(self, val): 3236 return _pywrapcp.IntervalVar_SetPerformed(self, val) 3237 3238 def WasPerformedBound(self): 3239 return _pywrapcp.IntervalVar_WasPerformedBound(self) 3240 3241 def WhenPerformedBound(self, *args): 3242 return _pywrapcp.IntervalVar_WhenPerformedBound(self, *args) 3243 3244 def WhenAnything(self, *args): 3245 r""" 3246 *Overload 1:* 3247 Attaches a demon awakened when anything about this interval changes. 3248 3249 | 3250 3251 *Overload 2:* 3252 Attaches a closure awakened when anything about this interval changes. 3253 """ 3254 return _pywrapcp.IntervalVar_WhenAnything(self, *args) 3255 3256 def StartExpr(self): 3257 r""" 3258 These methods create expressions encapsulating the start, end 3259 and duration of the interval var. Please note that these must not 3260 be used if the interval var is unperformed. 3261 """ 3262 return _pywrapcp.IntervalVar_StartExpr(self) 3263 3264 def DurationExpr(self): 3265 return _pywrapcp.IntervalVar_DurationExpr(self) 3266 3267 def EndExpr(self): 3268 return _pywrapcp.IntervalVar_EndExpr(self) 3269 3270 def PerformedExpr(self): 3271 return _pywrapcp.IntervalVar_PerformedExpr(self) 3272 3273 def SafeStartExpr(self, unperformed_value): 3274 r""" 3275 These methods create expressions encapsulating the start, end 3276 and duration of the interval var. If the interval var is 3277 unperformed, they will return the unperformed_value. 3278 """ 3279 return _pywrapcp.IntervalVar_SafeStartExpr(self, unperformed_value) 3280 3281 def SafeDurationExpr(self, unperformed_value): 3282 return _pywrapcp.IntervalVar_SafeDurationExpr(self, unperformed_value) 3283 3284 def SafeEndExpr(self, unperformed_value): 3285 return _pywrapcp.IntervalVar_SafeEndExpr(self, unperformed_value) 3286 3287 def EndsAfterEnd(self, other): 3288 return _pywrapcp.IntervalVar_EndsAfterEnd(self, other) 3289 3290 def EndsAfterEndWithDelay(self, other, delay): 3291 return _pywrapcp.IntervalVar_EndsAfterEndWithDelay(self, other, delay) 3292 3293 def EndsAfterStart(self, other): 3294 return _pywrapcp.IntervalVar_EndsAfterStart(self, other) 3295 3296 def EndsAfterStartWithDelay(self, other, delay): 3297 return _pywrapcp.IntervalVar_EndsAfterStartWithDelay(self, other, delay) 3298 3299 def EndsAtEnd(self, other): 3300 return _pywrapcp.IntervalVar_EndsAtEnd(self, other) 3301 3302 def EndsAtEndWithDelay(self, other, delay): 3303 return _pywrapcp.IntervalVar_EndsAtEndWithDelay(self, other, delay) 3304 3305 def EndsAtStart(self, other): 3306 return _pywrapcp.IntervalVar_EndsAtStart(self, other) 3307 3308 def EndsAtStartWithDelay(self, other, delay): 3309 return _pywrapcp.IntervalVar_EndsAtStartWithDelay(self, other, delay) 3310 3311 def StartsAfterEnd(self, other): 3312 return _pywrapcp.IntervalVar_StartsAfterEnd(self, other) 3313 3314 def StartsAfterEndWithDelay(self, other, delay): 3315 return _pywrapcp.IntervalVar_StartsAfterEndWithDelay(self, other, delay) 3316 3317 def StartsAfterStart(self, other): 3318 return _pywrapcp.IntervalVar_StartsAfterStart(self, other) 3319 3320 def StartsAfterStartWithDelay(self, other, delay): 3321 return _pywrapcp.IntervalVar_StartsAfterStartWithDelay(self, other, delay) 3322 3323 def StartsAtEnd(self, other): 3324 return _pywrapcp.IntervalVar_StartsAtEnd(self, other) 3325 3326 def StartsAtEndWithDelay(self, other, delay): 3327 return _pywrapcp.IntervalVar_StartsAtEndWithDelay(self, other, delay) 3328 3329 def StartsAtStart(self, other): 3330 return _pywrapcp.IntervalVar_StartsAtStart(self, other) 3331 3332 def StartsAtStartWithDelay(self, other, delay): 3333 return _pywrapcp.IntervalVar_StartsAtStartWithDelay(self, other, delay) 3334 3335 def StaysInSync(self, other): 3336 return _pywrapcp.IntervalVar_StaysInSync(self, other) 3337 3338 def StaysInSyncWithDelay(self, other, delay): 3339 return _pywrapcp.IntervalVar_StaysInSyncWithDelay(self, other, delay) 3340 3341 def EndsAfter(self, date): 3342 return _pywrapcp.IntervalVar_EndsAfter(self, date) 3343 3344 def EndsAt(self, date): 3345 return _pywrapcp.IntervalVar_EndsAt(self, date) 3346 3347 def EndsBefore(self, date): 3348 return _pywrapcp.IntervalVar_EndsBefore(self, date) 3349 3350 def StartsAfter(self, date): 3351 return _pywrapcp.IntervalVar_StartsAfter(self, date) 3352 3353 def StartsAt(self, date): 3354 return _pywrapcp.IntervalVar_StartsAt(self, date) 3355 3356 def StartsBefore(self, date): 3357 return _pywrapcp.IntervalVar_StartsBefore(self, date) 3358 3359 def CrossesDate(self, date): 3360 return _pywrapcp.IntervalVar_CrossesDate(self, date) 3361 3362 def AvoidsDate(self, date): 3363 return _pywrapcp.IntervalVar_AvoidsDate(self, date) 3364 3365 def __repr__(self): 3366 return _pywrapcp.IntervalVar___repr__(self) 3367 3368 def __str__(self): 3369 return _pywrapcp.IntervalVar___str__(self)
Interval variables are often used in scheduling. The main characteristics of an IntervalVar are the start position, duration, and end date. All these characteristics can be queried and set, and demons can be posted on their modifications.
An important aspect is optionality: an IntervalVar can be performed or not. If unperformed, then it simply does not exist, and its characteristics cannot be accessed any more. An interval var is automatically marked as unperformed when it is not consistent anymore (start greater than end, duration < 0...)
3127 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
3132 def StartMin(self): 3133 r""" 3134 These methods query, set, and watch the start position of the 3135 interval var. 3136 """ 3137 return _pywrapcp.IntervalVar_StartMin(self)
These methods query, set, and watch the start position of the interval var.
3163 def DurationMin(self): 3164 r"""These methods query, set, and watch the duration of the interval var.""" 3165 return _pywrapcp.IntervalVar_DurationMin(self)
These methods query, set, and watch the duration of the interval var.
3191 def EndMin(self): 3192 r"""These methods query, set, and watch the end position of the interval var.""" 3193 return _pywrapcp.IntervalVar_EndMin(self)
These methods query, set, and watch the end position of the interval var.
3219 def MustBePerformed(self): 3220 r""" 3221 These methods query, set, and watch the performed status of the 3222 interval var. 3223 """ 3224 return _pywrapcp.IntervalVar_MustBePerformed(self)
These methods query, set, and watch the performed status of the interval var.
3244 def WhenAnything(self, *args): 3245 r""" 3246 *Overload 1:* 3247 Attaches a demon awakened when anything about this interval changes. 3248 3249 | 3250 3251 *Overload 2:* 3252 Attaches a closure awakened when anything about this interval changes. 3253 """ 3254 return _pywrapcp.IntervalVar_WhenAnything(self, *args)
Overload 1: Attaches a demon awakened when anything about this interval changes.
|
Overload 2: Attaches a closure awakened when anything about this interval changes.
3256 def StartExpr(self): 3257 r""" 3258 These methods create expressions encapsulating the start, end 3259 and duration of the interval var. Please note that these must not 3260 be used if the interval var is unperformed. 3261 """ 3262 return _pywrapcp.IntervalVar_StartExpr(self)
These methods create expressions encapsulating the start, end and duration of the interval var. Please note that these must not be used if the interval var is unperformed.
3273 def SafeStartExpr(self, unperformed_value): 3274 r""" 3275 These methods create expressions encapsulating the start, end 3276 and duration of the interval var. If the interval var is 3277 unperformed, they will return the unperformed_value. 3278 """ 3279 return _pywrapcp.IntervalVar_SafeStartExpr(self, unperformed_value)
These methods create expressions encapsulating the start, end and duration of the interval var. If the interval var is unperformed, they will return the unperformed_value.
Inherited Members
3373class SequenceVar(PropagationBaseObject): 3374 r""" 3375 A sequence variable is a variable whose domain is a set of possible 3376 orderings of the interval variables. It allows ordering of tasks. It 3377 has two sets of methods: ComputePossibleFirstsAndLasts(), which 3378 returns the list of interval variables that can be ranked first or 3379 last; and RankFirst/RankNotFirst/RankLast/RankNotLast, which can be 3380 used to create the search decision. 3381 """ 3382 3383 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3384 3385 def __init__(self, *args, **kwargs): 3386 raise AttributeError("No constructor defined") 3387 3388 def DebugString(self): 3389 return _pywrapcp.SequenceVar_DebugString(self) 3390 3391 def RankFirst(self, index): 3392 r""" 3393 Ranks the index_th interval var first of all unranked interval 3394 vars. After that, it will no longer be considered ranked. 3395 """ 3396 return _pywrapcp.SequenceVar_RankFirst(self, index) 3397 3398 def RankNotFirst(self, index): 3399 r""" 3400 Indicates that the index_th interval var will not be ranked first 3401 of all currently unranked interval vars. 3402 """ 3403 return _pywrapcp.SequenceVar_RankNotFirst(self, index) 3404 3405 def RankLast(self, index): 3406 r""" 3407 Ranks the index_th interval var first of all unranked interval 3408 vars. After that, it will no longer be considered ranked. 3409 """ 3410 return _pywrapcp.SequenceVar_RankLast(self, index) 3411 3412 def RankNotLast(self, index): 3413 r""" 3414 Indicates that the index_th interval var will not be ranked first 3415 of all currently unranked interval vars. 3416 """ 3417 return _pywrapcp.SequenceVar_RankNotLast(self, index) 3418 3419 def Interval(self, index): 3420 r"""Returns the index_th interval of the sequence.""" 3421 return _pywrapcp.SequenceVar_Interval(self, index) 3422 3423 def Next(self, index): 3424 r"""Returns the next of the index_th interval of the sequence.""" 3425 return _pywrapcp.SequenceVar_Next(self, index) 3426 3427 def Size(self): 3428 r"""Returns the number of interval vars in the sequence.""" 3429 return _pywrapcp.SequenceVar_Size(self) 3430 3431 def __repr__(self): 3432 return _pywrapcp.SequenceVar___repr__(self) 3433 3434 def __str__(self): 3435 return _pywrapcp.SequenceVar___str__(self)
A sequence variable is a variable whose domain is a set of possible orderings of the interval variables. It allows ordering of tasks. It has two sets of methods: ComputePossibleFirstsAndLasts(), which returns the list of interval variables that can be ranked first or last; and RankFirst/RankNotFirst/RankLast/RankNotLast, which can be used to create the search decision.
3383 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
3391 def RankFirst(self, index): 3392 r""" 3393 Ranks the index_th interval var first of all unranked interval 3394 vars. After that, it will no longer be considered ranked. 3395 """ 3396 return _pywrapcp.SequenceVar_RankFirst(self, index)
Ranks the index_th interval var first of all unranked interval vars. After that, it will no longer be considered ranked.
3398 def RankNotFirst(self, index): 3399 r""" 3400 Indicates that the index_th interval var will not be ranked first 3401 of all currently unranked interval vars. 3402 """ 3403 return _pywrapcp.SequenceVar_RankNotFirst(self, index)
Indicates that the index_th interval var will not be ranked first of all currently unranked interval vars.
3405 def RankLast(self, index): 3406 r""" 3407 Ranks the index_th interval var first of all unranked interval 3408 vars. After that, it will no longer be considered ranked. 3409 """ 3410 return _pywrapcp.SequenceVar_RankLast(self, index)
Ranks the index_th interval var first of all unranked interval vars. After that, it will no longer be considered ranked.
3412 def RankNotLast(self, index): 3413 r""" 3414 Indicates that the index_th interval var will not be ranked first 3415 of all currently unranked interval vars. 3416 """ 3417 return _pywrapcp.SequenceVar_RankNotLast(self, index)
Indicates that the index_th interval var will not be ranked first of all currently unranked interval vars.
3419 def Interval(self, index): 3420 r"""Returns the index_th interval of the sequence.""" 3421 return _pywrapcp.SequenceVar_Interval(self, index)
Returns the index_th interval of the sequence.
3423 def Next(self, index): 3424 r"""Returns the next of the index_th interval of the sequence.""" 3425 return _pywrapcp.SequenceVar_Next(self, index)
Returns the next of the index_th interval of the sequence.
3427 def Size(self): 3428 r"""Returns the number of interval vars in the sequence.""" 3429 return _pywrapcp.SequenceVar_Size(self)
Returns the number of interval vars in the sequence.
Inherited Members
3439class AssignmentElement(object): 3440 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3441 3442 def __init__(self, *args, **kwargs): 3443 raise AttributeError("No constructor defined") 3444 __repr__ = _swig_repr 3445 3446 def Activate(self): 3447 return _pywrapcp.AssignmentElement_Activate(self) 3448 3449 def Deactivate(self): 3450 return _pywrapcp.AssignmentElement_Deactivate(self) 3451 3452 def Activated(self): 3453 return _pywrapcp.AssignmentElement_Activated(self) 3454 __swig_destroy__ = _pywrapcp.delete_AssignmentElement
3440 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
3458class IntVarElement(AssignmentElement): 3459 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3460 3461 def __init__(self, *args, **kwargs): 3462 raise AttributeError("No constructor defined") 3463 __repr__ = _swig_repr 3464 3465 def Var(self): 3466 return _pywrapcp.IntVarElement_Var(self) 3467 3468 def Min(self): 3469 return _pywrapcp.IntVarElement_Min(self) 3470 3471 def SetMin(self, m): 3472 return _pywrapcp.IntVarElement_SetMin(self, m) 3473 3474 def Max(self): 3475 return _pywrapcp.IntVarElement_Max(self) 3476 3477 def SetMax(self, m): 3478 return _pywrapcp.IntVarElement_SetMax(self, m) 3479 3480 def Value(self): 3481 return _pywrapcp.IntVarElement_Value(self) 3482 3483 def Bound(self): 3484 return _pywrapcp.IntVarElement_Bound(self) 3485 3486 def SetRange(self, l, u): 3487 return _pywrapcp.IntVarElement_SetRange(self, l, u) 3488 3489 def SetValue(self, v): 3490 return _pywrapcp.IntVarElement_SetValue(self, v) 3491 3492 def __eq__(self, element): 3493 return _pywrapcp.IntVarElement___eq__(self, element) 3494 3495 def __ne__(self, element): 3496 return _pywrapcp.IntVarElement___ne__(self, element) 3497 __swig_destroy__ = _pywrapcp.delete_IntVarElement
3459 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Inherited Members
3501class IntervalVarElement(AssignmentElement): 3502 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3503 3504 def __init__(self, *args, **kwargs): 3505 raise AttributeError("No constructor defined") 3506 __repr__ = _swig_repr 3507 3508 def Var(self): 3509 return _pywrapcp.IntervalVarElement_Var(self) 3510 3511 def StartMin(self): 3512 return _pywrapcp.IntervalVarElement_StartMin(self) 3513 3514 def StartMax(self): 3515 return _pywrapcp.IntervalVarElement_StartMax(self) 3516 3517 def StartValue(self): 3518 return _pywrapcp.IntervalVarElement_StartValue(self) 3519 3520 def DurationMin(self): 3521 return _pywrapcp.IntervalVarElement_DurationMin(self) 3522 3523 def DurationMax(self): 3524 return _pywrapcp.IntervalVarElement_DurationMax(self) 3525 3526 def DurationValue(self): 3527 return _pywrapcp.IntervalVarElement_DurationValue(self) 3528 3529 def EndMin(self): 3530 return _pywrapcp.IntervalVarElement_EndMin(self) 3531 3532 def EndMax(self): 3533 return _pywrapcp.IntervalVarElement_EndMax(self) 3534 3535 def EndValue(self): 3536 return _pywrapcp.IntervalVarElement_EndValue(self) 3537 3538 def PerformedMin(self): 3539 return _pywrapcp.IntervalVarElement_PerformedMin(self) 3540 3541 def PerformedMax(self): 3542 return _pywrapcp.IntervalVarElement_PerformedMax(self) 3543 3544 def PerformedValue(self): 3545 return _pywrapcp.IntervalVarElement_PerformedValue(self) 3546 3547 def SetStartMin(self, m): 3548 return _pywrapcp.IntervalVarElement_SetStartMin(self, m) 3549 3550 def SetStartMax(self, m): 3551 return _pywrapcp.IntervalVarElement_SetStartMax(self, m) 3552 3553 def SetStartRange(self, mi, ma): 3554 return _pywrapcp.IntervalVarElement_SetStartRange(self, mi, ma) 3555 3556 def SetStartValue(self, v): 3557 return _pywrapcp.IntervalVarElement_SetStartValue(self, v) 3558 3559 def SetDurationMin(self, m): 3560 return _pywrapcp.IntervalVarElement_SetDurationMin(self, m) 3561 3562 def SetDurationMax(self, m): 3563 return _pywrapcp.IntervalVarElement_SetDurationMax(self, m) 3564 3565 def SetDurationRange(self, mi, ma): 3566 return _pywrapcp.IntervalVarElement_SetDurationRange(self, mi, ma) 3567 3568 def SetDurationValue(self, v): 3569 return _pywrapcp.IntervalVarElement_SetDurationValue(self, v) 3570 3571 def SetEndMin(self, m): 3572 return _pywrapcp.IntervalVarElement_SetEndMin(self, m) 3573 3574 def SetEndMax(self, m): 3575 return _pywrapcp.IntervalVarElement_SetEndMax(self, m) 3576 3577 def SetEndRange(self, mi, ma): 3578 return _pywrapcp.IntervalVarElement_SetEndRange(self, mi, ma) 3579 3580 def SetEndValue(self, v): 3581 return _pywrapcp.IntervalVarElement_SetEndValue(self, v) 3582 3583 def SetPerformedMin(self, m): 3584 return _pywrapcp.IntervalVarElement_SetPerformedMin(self, m) 3585 3586 def SetPerformedMax(self, m): 3587 return _pywrapcp.IntervalVarElement_SetPerformedMax(self, m) 3588 3589 def SetPerformedRange(self, mi, ma): 3590 return _pywrapcp.IntervalVarElement_SetPerformedRange(self, mi, ma) 3591 3592 def SetPerformedValue(self, v): 3593 return _pywrapcp.IntervalVarElement_SetPerformedValue(self, v) 3594 3595 def __eq__(self, element): 3596 return _pywrapcp.IntervalVarElement___eq__(self, element) 3597 3598 def __ne__(self, element): 3599 return _pywrapcp.IntervalVarElement___ne__(self, element) 3600 __swig_destroy__ = _pywrapcp.delete_IntervalVarElement
3502 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Inherited Members
3604class SequenceVarElement(AssignmentElement): 3605 r""" 3606 The SequenceVarElement stores a partial representation of ranked 3607 interval variables in the underlying sequence variable. 3608 This representation consists of three vectors: 3609 - the forward sequence. That is the list of interval variables 3610 ranked first in the sequence. The first element of the backward 3611 sequence is the first interval in the sequence variable. 3612 - the backward sequence. That is the list of interval variables 3613 ranked last in the sequence. The first element of the backward 3614 sequence is the last interval in the sequence variable. 3615 - The list of unperformed interval variables. 3616 Furthermore, if all performed variables are ranked, then by 3617 convention, the forward_sequence will contain all such variables 3618 and the backward_sequence will be empty. 3619 """ 3620 3621 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3622 3623 def __init__(self, *args, **kwargs): 3624 raise AttributeError("No constructor defined") 3625 __repr__ = _swig_repr 3626 3627 def Var(self): 3628 return _pywrapcp.SequenceVarElement_Var(self) 3629 3630 def ForwardSequence(self): 3631 return _pywrapcp.SequenceVarElement_ForwardSequence(self) 3632 3633 def BackwardSequence(self): 3634 return _pywrapcp.SequenceVarElement_BackwardSequence(self) 3635 3636 def Unperformed(self): 3637 return _pywrapcp.SequenceVarElement_Unperformed(self) 3638 3639 def SetSequence(self, forward_sequence, backward_sequence, unperformed): 3640 return _pywrapcp.SequenceVarElement_SetSequence(self, forward_sequence, backward_sequence, unperformed) 3641 3642 def SetForwardSequence(self, forward_sequence): 3643 return _pywrapcp.SequenceVarElement_SetForwardSequence(self, forward_sequence) 3644 3645 def SetBackwardSequence(self, backward_sequence): 3646 return _pywrapcp.SequenceVarElement_SetBackwardSequence(self, backward_sequence) 3647 3648 def SetUnperformed(self, unperformed): 3649 return _pywrapcp.SequenceVarElement_SetUnperformed(self, unperformed) 3650 3651 def __eq__(self, element): 3652 return _pywrapcp.SequenceVarElement___eq__(self, element) 3653 3654 def __ne__(self, element): 3655 return _pywrapcp.SequenceVarElement___ne__(self, element) 3656 __swig_destroy__ = _pywrapcp.delete_SequenceVarElement
The SequenceVarElement stores a partial representation of ranked interval variables in the underlying sequence variable.
This representation consists of three vectors:
- the forward sequence. That is the list of interval variables ranked first in the sequence. The first element of the backward sequence is the first interval in the sequence variable.
- the backward sequence. That is the list of interval variables ranked last in the sequence. The first element of the backward sequence is the last interval in the sequence variable.
- The list of unperformed interval variables. Furthermore, if all performed variables are ranked, then by convention, the forward_sequence will contain all such variables and the backward_sequence will be empty.
3621 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Inherited Members
3660class Assignment(PropagationBaseObject): 3661 r""" 3662 An Assignment is a variable -> domains mapping, used 3663 to report solutions to the user. 3664 """ 3665 3666 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3667 3668 def __init__(self, *args, **kwargs): 3669 raise AttributeError("No constructor defined") 3670 __repr__ = _swig_repr 3671 3672 def Clear(self): 3673 return _pywrapcp.Assignment_Clear(self) 3674 3675 def Empty(self): 3676 return _pywrapcp.Assignment_Empty(self) 3677 3678 def Size(self): 3679 return _pywrapcp.Assignment_Size(self) 3680 3681 def NumIntVars(self): 3682 return _pywrapcp.Assignment_NumIntVars(self) 3683 3684 def NumIntervalVars(self): 3685 return _pywrapcp.Assignment_NumIntervalVars(self) 3686 3687 def NumSequenceVars(self): 3688 return _pywrapcp.Assignment_NumSequenceVars(self) 3689 3690 def Store(self): 3691 return _pywrapcp.Assignment_Store(self) 3692 3693 def Restore(self): 3694 return _pywrapcp.Assignment_Restore(self) 3695 3696 def Load(self, *args): 3697 r""" 3698 Loads an assignment from a file; does not add variables to the 3699 assignment (only the variables contained in the assignment are modified). 3700 """ 3701 return _pywrapcp.Assignment_Load(self, *args) 3702 3703 def Save(self, *args): 3704 r"""Saves the assignment to a file.""" 3705 return _pywrapcp.Assignment_Save(self, *args) 3706 3707 def AddObjective(self, v): 3708 return _pywrapcp.Assignment_AddObjective(self, v) 3709 3710 def Objective(self): 3711 return _pywrapcp.Assignment_Objective(self) 3712 3713 def HasObjective(self): 3714 return _pywrapcp.Assignment_HasObjective(self) 3715 3716 def ObjectiveMin(self): 3717 return _pywrapcp.Assignment_ObjectiveMin(self) 3718 3719 def ObjectiveMax(self): 3720 return _pywrapcp.Assignment_ObjectiveMax(self) 3721 3722 def ObjectiveValue(self): 3723 return _pywrapcp.Assignment_ObjectiveValue(self) 3724 3725 def ObjectiveBound(self): 3726 return _pywrapcp.Assignment_ObjectiveBound(self) 3727 3728 def SetObjectiveMin(self, m): 3729 return _pywrapcp.Assignment_SetObjectiveMin(self, m) 3730 3731 def SetObjectiveMax(self, m): 3732 return _pywrapcp.Assignment_SetObjectiveMax(self, m) 3733 3734 def SetObjectiveValue(self, value): 3735 return _pywrapcp.Assignment_SetObjectiveValue(self, value) 3736 3737 def SetObjectiveRange(self, l, u): 3738 return _pywrapcp.Assignment_SetObjectiveRange(self, l, u) 3739 3740 def Min(self, var): 3741 return _pywrapcp.Assignment_Min(self, var) 3742 3743 def Max(self, var): 3744 return _pywrapcp.Assignment_Max(self, var) 3745 3746 def Value(self, var): 3747 return _pywrapcp.Assignment_Value(self, var) 3748 3749 def Bound(self, var): 3750 return _pywrapcp.Assignment_Bound(self, var) 3751 3752 def SetMin(self, var, m): 3753 return _pywrapcp.Assignment_SetMin(self, var, m) 3754 3755 def SetMax(self, var, m): 3756 return _pywrapcp.Assignment_SetMax(self, var, m) 3757 3758 def SetRange(self, var, l, u): 3759 return _pywrapcp.Assignment_SetRange(self, var, l, u) 3760 3761 def SetValue(self, var, value): 3762 return _pywrapcp.Assignment_SetValue(self, var, value) 3763 3764 def StartMin(self, var): 3765 return _pywrapcp.Assignment_StartMin(self, var) 3766 3767 def StartMax(self, var): 3768 return _pywrapcp.Assignment_StartMax(self, var) 3769 3770 def StartValue(self, var): 3771 return _pywrapcp.Assignment_StartValue(self, var) 3772 3773 def DurationMin(self, var): 3774 return _pywrapcp.Assignment_DurationMin(self, var) 3775 3776 def DurationMax(self, var): 3777 return _pywrapcp.Assignment_DurationMax(self, var) 3778 3779 def DurationValue(self, var): 3780 return _pywrapcp.Assignment_DurationValue(self, var) 3781 3782 def EndMin(self, var): 3783 return _pywrapcp.Assignment_EndMin(self, var) 3784 3785 def EndMax(self, var): 3786 return _pywrapcp.Assignment_EndMax(self, var) 3787 3788 def EndValue(self, var): 3789 return _pywrapcp.Assignment_EndValue(self, var) 3790 3791 def PerformedMin(self, var): 3792 return _pywrapcp.Assignment_PerformedMin(self, var) 3793 3794 def PerformedMax(self, var): 3795 return _pywrapcp.Assignment_PerformedMax(self, var) 3796 3797 def PerformedValue(self, var): 3798 return _pywrapcp.Assignment_PerformedValue(self, var) 3799 3800 def SetStartMin(self, var, m): 3801 return _pywrapcp.Assignment_SetStartMin(self, var, m) 3802 3803 def SetStartMax(self, var, m): 3804 return _pywrapcp.Assignment_SetStartMax(self, var, m) 3805 3806 def SetStartRange(self, var, mi, ma): 3807 return _pywrapcp.Assignment_SetStartRange(self, var, mi, ma) 3808 3809 def SetStartValue(self, var, value): 3810 return _pywrapcp.Assignment_SetStartValue(self, var, value) 3811 3812 def SetDurationMin(self, var, m): 3813 return _pywrapcp.Assignment_SetDurationMin(self, var, m) 3814 3815 def SetDurationMax(self, var, m): 3816 return _pywrapcp.Assignment_SetDurationMax(self, var, m) 3817 3818 def SetDurationRange(self, var, mi, ma): 3819 return _pywrapcp.Assignment_SetDurationRange(self, var, mi, ma) 3820 3821 def SetDurationValue(self, var, value): 3822 return _pywrapcp.Assignment_SetDurationValue(self, var, value) 3823 3824 def SetEndMin(self, var, m): 3825 return _pywrapcp.Assignment_SetEndMin(self, var, m) 3826 3827 def SetEndMax(self, var, m): 3828 return _pywrapcp.Assignment_SetEndMax(self, var, m) 3829 3830 def SetEndRange(self, var, mi, ma): 3831 return _pywrapcp.Assignment_SetEndRange(self, var, mi, ma) 3832 3833 def SetEndValue(self, var, value): 3834 return _pywrapcp.Assignment_SetEndValue(self, var, value) 3835 3836 def SetPerformedMin(self, var, m): 3837 return _pywrapcp.Assignment_SetPerformedMin(self, var, m) 3838 3839 def SetPerformedMax(self, var, m): 3840 return _pywrapcp.Assignment_SetPerformedMax(self, var, m) 3841 3842 def SetPerformedRange(self, var, mi, ma): 3843 return _pywrapcp.Assignment_SetPerformedRange(self, var, mi, ma) 3844 3845 def SetPerformedValue(self, var, value): 3846 return _pywrapcp.Assignment_SetPerformedValue(self, var, value) 3847 3848 def Add(self, *args): 3849 return _pywrapcp.Assignment_Add(self, *args) 3850 3851 def ForwardSequence(self, var): 3852 return _pywrapcp.Assignment_ForwardSequence(self, var) 3853 3854 def BackwardSequence(self, var): 3855 return _pywrapcp.Assignment_BackwardSequence(self, var) 3856 3857 def Unperformed(self, var): 3858 return _pywrapcp.Assignment_Unperformed(self, var) 3859 3860 def SetSequence(self, var, forward_sequence, backward_sequence, unperformed): 3861 return _pywrapcp.Assignment_SetSequence(self, var, forward_sequence, backward_sequence, unperformed) 3862 3863 def SetForwardSequence(self, var, forward_sequence): 3864 return _pywrapcp.Assignment_SetForwardSequence(self, var, forward_sequence) 3865 3866 def SetBackwardSequence(self, var, backward_sequence): 3867 return _pywrapcp.Assignment_SetBackwardSequence(self, var, backward_sequence) 3868 3869 def SetUnperformed(self, var, unperformed): 3870 return _pywrapcp.Assignment_SetUnperformed(self, var, unperformed) 3871 3872 def Activate(self, *args): 3873 return _pywrapcp.Assignment_Activate(self, *args) 3874 3875 def Deactivate(self, *args): 3876 return _pywrapcp.Assignment_Deactivate(self, *args) 3877 3878 def Activated(self, *args): 3879 return _pywrapcp.Assignment_Activated(self, *args) 3880 3881 def DebugString(self): 3882 return _pywrapcp.Assignment_DebugString(self) 3883 3884 def IntVarContainer(self): 3885 return _pywrapcp.Assignment_IntVarContainer(self) 3886 3887 def MutableIntVarContainer(self): 3888 return _pywrapcp.Assignment_MutableIntVarContainer(self) 3889 3890 def IntervalVarContainer(self): 3891 return _pywrapcp.Assignment_IntervalVarContainer(self) 3892 3893 def MutableIntervalVarContainer(self): 3894 return _pywrapcp.Assignment_MutableIntervalVarContainer(self) 3895 3896 def SequenceVarContainer(self): 3897 return _pywrapcp.Assignment_SequenceVarContainer(self) 3898 3899 def MutableSequenceVarContainer(self): 3900 return _pywrapcp.Assignment_MutableSequenceVarContainer(self) 3901 3902 def __eq__(self, assignment): 3903 return _pywrapcp.Assignment___eq__(self, assignment) 3904 3905 def __ne__(self, assignment): 3906 return _pywrapcp.Assignment___ne__(self, assignment)
An Assignment is a variable -> domains mapping, used to report solutions to the user.
3666 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
3696 def Load(self, *args): 3697 r""" 3698 Loads an assignment from a file; does not add variables to the 3699 assignment (only the variables contained in the assignment are modified). 3700 """ 3701 return _pywrapcp.Assignment_Load(self, *args)
Loads an assignment from a file; does not add variables to the assignment (only the variables contained in the assignment are modified).
3703 def Save(self, *args): 3704 r"""Saves the assignment to a file.""" 3705 return _pywrapcp.Assignment_Save(self, *args)
Saves the assignment to a file.
Inherited Members
3913class Pack(Constraint): 3914 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 3915 3916 def __init__(self, *args, **kwargs): 3917 raise AttributeError("No constructor defined") 3918 __repr__ = _swig_repr 3919 3920 def AddWeightedSumLessOrEqualConstantDimension(self, *args): 3921 r""" 3922 *Overload 1:* 3923 Dimensions are additional constraints than can restrict what is 3924 possible with the pack constraint. It can be used to set capacity 3925 limits, to count objects per bin, to compute unassigned 3926 penalties... 3927 This dimension imposes that for all bins b, the weighted sum 3928 (weights[i]) of all objects i assigned to 'b' is less or equal 3929 'bounds[b]'. 3930 3931 | 3932 3933 *Overload 2:* 3934 This dimension imposes that for all bins b, the weighted sum 3935 (weights->Run(i)) of all objects i assigned to 'b' is less or 3936 equal to 'bounds[b]'. Ownership of the callback is transferred to 3937 the pack constraint. 3938 3939 | 3940 3941 *Overload 3:* 3942 This dimension imposes that for all bins b, the weighted sum 3943 (weights->Run(i, b) of all objects i assigned to 'b' is less or 3944 equal to 'bounds[b]'. Ownership of the callback is transferred to 3945 the pack constraint. 3946 """ 3947 return _pywrapcp.Pack_AddWeightedSumLessOrEqualConstantDimension(self, *args) 3948 3949 def AddWeightedSumEqualVarDimension(self, *args): 3950 r""" 3951 *Overload 1:* 3952 This dimension imposes that for all bins b, the weighted sum 3953 (weights[i]) of all objects i assigned to 'b' is equal to loads[b]. 3954 3955 | 3956 3957 *Overload 2:* 3958 This dimension imposes that for all bins b, the weighted sum 3959 (weights->Run(i, b)) of all objects i assigned to 'b' is equal to 3960 loads[b]. 3961 """ 3962 return _pywrapcp.Pack_AddWeightedSumEqualVarDimension(self, *args) 3963 3964 def AddSumVariableWeightsLessOrEqualConstantDimension(self, usage, capacity): 3965 r""" 3966 This dimension imposes: 3967 forall b in bins, 3968 sum (i in items: usage[i] * is_assigned(i, b)) <= capacity[b] 3969 where is_assigned(i, b) is true if and only if item i is assigned 3970 to the bin b. 3971 3972 This can be used to model shapes of items by linking variables of 3973 the same item on parallel dimensions with an allowed assignment 3974 constraint. 3975 """ 3976 return _pywrapcp.Pack_AddSumVariableWeightsLessOrEqualConstantDimension(self, usage, capacity) 3977 3978 def AddWeightedSumOfAssignedDimension(self, weights, cost_var): 3979 r""" 3980 This dimension enforces that cost_var == sum of weights[i] for 3981 all objects 'i' assigned to a bin. 3982 """ 3983 return _pywrapcp.Pack_AddWeightedSumOfAssignedDimension(self, weights, cost_var) 3984 3985 def AddCountUsedBinDimension(self, count_var): 3986 r""" 3987 This dimension links 'count_var' to the actual number of bins used in the 3988 pack. 3989 """ 3990 return _pywrapcp.Pack_AddCountUsedBinDimension(self, count_var) 3991 3992 def AddCountAssignedItemsDimension(self, count_var): 3993 r""" 3994 This dimension links 'count_var' to the actual number of items 3995 assigned to a bin in the pack. 3996 """ 3997 return _pywrapcp.Pack_AddCountAssignedItemsDimension(self, count_var) 3998 3999 def Post(self): 4000 return _pywrapcp.Pack_Post(self) 4001 4002 def InitialPropagateWrapper(self): 4003 return _pywrapcp.Pack_InitialPropagateWrapper(self) 4004 4005 def DebugString(self): 4006 return _pywrapcp.Pack_DebugString(self)
A constraint is the main modeling object. It provides two methods:
- Post() is responsible for creating the demons and attaching them to immediate demons().
- InitialPropagate() is called once just after Post and performs the initial propagation. The subsequent propagations will be performed by the demons Posted during the post() method.
3914 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
3920 def AddWeightedSumLessOrEqualConstantDimension(self, *args): 3921 r""" 3922 *Overload 1:* 3923 Dimensions are additional constraints than can restrict what is 3924 possible with the pack constraint. It can be used to set capacity 3925 limits, to count objects per bin, to compute unassigned 3926 penalties... 3927 This dimension imposes that for all bins b, the weighted sum 3928 (weights[i]) of all objects i assigned to 'b' is less or equal 3929 'bounds[b]'. 3930 3931 | 3932 3933 *Overload 2:* 3934 This dimension imposes that for all bins b, the weighted sum 3935 (weights->Run(i)) of all objects i assigned to 'b' is less or 3936 equal to 'bounds[b]'. Ownership of the callback is transferred to 3937 the pack constraint. 3938 3939 | 3940 3941 *Overload 3:* 3942 This dimension imposes that for all bins b, the weighted sum 3943 (weights->Run(i, b) of all objects i assigned to 'b' is less or 3944 equal to 'bounds[b]'. Ownership of the callback is transferred to 3945 the pack constraint. 3946 """ 3947 return _pywrapcp.Pack_AddWeightedSumLessOrEqualConstantDimension(self, *args)
Overload 1: Dimensions are additional constraints than can restrict what is possible with the pack constraint. It can be used to set capacity limits, to count objects per bin, to compute unassigned penalties... This dimension imposes that for all bins b, the weighted sum (weights[i]) of all objects i assigned to 'b' is less or equal 'bounds[b]'.
|
Overload 2: This dimension imposes that for all bins b, the weighted sum (weights->Run(i)) of all objects i assigned to 'b' is less or equal to 'bounds[b]'. Ownership of the callback is transferred to the pack constraint.
|
Overload 3: This dimension imposes that for all bins b, the weighted sum (weights->Run(i, b) of all objects i assigned to 'b' is less or equal to 'bounds[b]'. Ownership of the callback is transferred to the pack constraint.
3949 def AddWeightedSumEqualVarDimension(self, *args): 3950 r""" 3951 *Overload 1:* 3952 This dimension imposes that for all bins b, the weighted sum 3953 (weights[i]) of all objects i assigned to 'b' is equal to loads[b]. 3954 3955 | 3956 3957 *Overload 2:* 3958 This dimension imposes that for all bins b, the weighted sum 3959 (weights->Run(i, b)) of all objects i assigned to 'b' is equal to 3960 loads[b]. 3961 """ 3962 return _pywrapcp.Pack_AddWeightedSumEqualVarDimension(self, *args)
Overload 1: This dimension imposes that for all bins b, the weighted sum (weights[i]) of all objects i assigned to 'b' is equal to loads[b].
|
Overload 2: This dimension imposes that for all bins b, the weighted sum (weights->Run(i, b)) of all objects i assigned to 'b' is equal to loads[b].
3964 def AddSumVariableWeightsLessOrEqualConstantDimension(self, usage, capacity): 3965 r""" 3966 This dimension imposes: 3967 forall b in bins, 3968 sum (i in items: usage[i] * is_assigned(i, b)) <= capacity[b] 3969 where is_assigned(i, b) is true if and only if item i is assigned 3970 to the bin b. 3971 3972 This can be used to model shapes of items by linking variables of 3973 the same item on parallel dimensions with an allowed assignment 3974 constraint. 3975 """ 3976 return _pywrapcp.Pack_AddSumVariableWeightsLessOrEqualConstantDimension(self, usage, capacity)
This dimension imposes: forall b in bins, sum (i in items: usage[i] * is_assigned(i, b)) <= capacity[b] where is_assigned(i, b) is true if and only if item i is assigned to the bin b.
This can be used to model shapes of items by linking variables of the same item on parallel dimensions with an allowed assignment constraint.
3978 def AddWeightedSumOfAssignedDimension(self, weights, cost_var): 3979 r""" 3980 This dimension enforces that cost_var == sum of weights[i] for 3981 all objects 'i' assigned to a bin. 3982 """ 3983 return _pywrapcp.Pack_AddWeightedSumOfAssignedDimension(self, weights, cost_var)
This dimension enforces that cost_var == sum of weights[i] for all objects 'i' assigned to a bin.
3985 def AddCountUsedBinDimension(self, count_var): 3986 r""" 3987 This dimension links 'count_var' to the actual number of bins used in the 3988 pack. 3989 """ 3990 return _pywrapcp.Pack_AddCountUsedBinDimension(self, count_var)
This dimension links 'count_var' to the actual number of bins used in the pack.
3992 def AddCountAssignedItemsDimension(self, count_var): 3993 r""" 3994 This dimension links 'count_var' to the actual number of items 3995 assigned to a bin in the pack. 3996 """ 3997 return _pywrapcp.Pack_AddCountAssignedItemsDimension(self, count_var)
This dimension links 'count_var' to the actual number of items assigned to a bin in the pack.
This method is called when the constraint is processed by the solver. Its main usage is to attach demons to variables.
This method performs the initial propagation of the constraint. It is called just after the post.
Inherited Members
4010class DisjunctiveConstraint(Constraint): 4011 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4012 4013 def __init__(self, *args, **kwargs): 4014 raise AttributeError("No constructor defined - class is abstract") 4015 __repr__ = _swig_repr 4016 4017 def SequenceVar(self): 4018 r"""Creates a sequence variable from the constraint.""" 4019 return _pywrapcp.DisjunctiveConstraint_SequenceVar(self) 4020 4021 def SetTransitionTime(self, transition_time): 4022 r""" 4023 Add a transition time between intervals. It forces the distance between 4024 the end of interval a and start of interval b that follows it to be at 4025 least transition_time(a, b). This function must always return 4026 a positive or null value. 4027 """ 4028 return _pywrapcp.DisjunctiveConstraint_SetTransitionTime(self, transition_time) 4029 4030 def TransitionTime(self, before_index, after_index): 4031 return _pywrapcp.DisjunctiveConstraint_TransitionTime(self, before_index, after_index)
A constraint is the main modeling object. It provides two methods:
- Post() is responsible for creating the demons and attaching them to immediate demons().
- InitialPropagate() is called once just after Post and performs the initial propagation. The subsequent propagations will be performed by the demons Posted during the post() method.
4011 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4017 def SequenceVar(self): 4018 r"""Creates a sequence variable from the constraint.""" 4019 return _pywrapcp.DisjunctiveConstraint_SequenceVar(self)
Creates a sequence variable from the constraint.
4021 def SetTransitionTime(self, transition_time): 4022 r""" 4023 Add a transition time between intervals. It forces the distance between 4024 the end of interval a and start of interval b that follows it to be at 4025 least transition_time(a, b). This function must always return 4026 a positive or null value. 4027 """ 4028 return _pywrapcp.DisjunctiveConstraint_SetTransitionTime(self, transition_time)
Add a transition time between intervals. It forces the distance between the end of interval a and start of interval b that follows it to be at least transition_time(a, b). This function must always return a positive or null value.
Inherited Members
4035class RevInteger(object): 4036 r""" 4037 This class adds reversibility to a POD type. 4038 It contains the stamp optimization. i.e. the SaveValue call is done 4039 only once per node of the search tree. Please note that actual 4040 stamps always starts at 1, thus an initial value of 0 will always 4041 trigger the first SaveValue. 4042 """ 4043 4044 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4045 __repr__ = _swig_repr 4046 4047 def __init__(self, val): 4048 _pywrapcp.RevInteger_swiginit(self, _pywrapcp.new_RevInteger(val)) 4049 4050 def Value(self): 4051 return _pywrapcp.RevInteger_Value(self) 4052 4053 def SetValue(self, s, val): 4054 return _pywrapcp.RevInteger_SetValue(self, s, val) 4055 __swig_destroy__ = _pywrapcp.delete_RevInteger
This class adds reversibility to a POD type. It contains the stamp optimization. i.e. the SaveValue call is done only once per node of the search tree. Please note that actual stamps always starts at 1, thus an initial value of 0 will always trigger the first SaveValue.
4044 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4059class NumericalRevInteger(RevInteger): 4060 r"""Subclass of Rev<T> which adds numerical operations.""" 4061 4062 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4063 __repr__ = _swig_repr 4064 4065 def __init__(self, val): 4066 _pywrapcp.NumericalRevInteger_swiginit(self, _pywrapcp.new_NumericalRevInteger(val)) 4067 4068 def Add(self, s, to_add): 4069 return _pywrapcp.NumericalRevInteger_Add(self, s, to_add) 4070 4071 def Incr(self, s): 4072 return _pywrapcp.NumericalRevInteger_Incr(self, s) 4073 4074 def Decr(self, s): 4075 return _pywrapcp.NumericalRevInteger_Decr(self, s) 4076 __swig_destroy__ = _pywrapcp.delete_NumericalRevInteger
Subclass of Rev
4062 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Inherited Members
4080class RevBool(object): 4081 r""" 4082 This class adds reversibility to a POD type. 4083 It contains the stamp optimization. i.e. the SaveValue call is done 4084 only once per node of the search tree. Please note that actual 4085 stamps always starts at 1, thus an initial value of 0 will always 4086 trigger the first SaveValue. 4087 """ 4088 4089 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4090 __repr__ = _swig_repr 4091 4092 def __init__(self, val): 4093 _pywrapcp.RevBool_swiginit(self, _pywrapcp.new_RevBool(val)) 4094 4095 def Value(self): 4096 return _pywrapcp.RevBool_Value(self) 4097 4098 def SetValue(self, s, val): 4099 return _pywrapcp.RevBool_SetValue(self, s, val) 4100 __swig_destroy__ = _pywrapcp.delete_RevBool
This class adds reversibility to a POD type. It contains the stamp optimization. i.e. the SaveValue call is done only once per node of the search tree. Please note that actual stamps always starts at 1, thus an initial value of 0 will always trigger the first SaveValue.
4089 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4104class IntVarContainer(object): 4105 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4106 4107 def __init__(self, *args, **kwargs): 4108 raise AttributeError("No constructor defined") 4109 __repr__ = _swig_repr 4110 4111 def Contains(self, var): 4112 return _pywrapcp.IntVarContainer_Contains(self, var) 4113 4114 def Element(self, index): 4115 return _pywrapcp.IntVarContainer_Element(self, index) 4116 4117 def Size(self): 4118 return _pywrapcp.IntVarContainer_Size(self) 4119 4120 def Store(self): 4121 return _pywrapcp.IntVarContainer_Store(self) 4122 4123 def Restore(self): 4124 return _pywrapcp.IntVarContainer_Restore(self) 4125 4126 def __eq__(self, container): 4127 r""" 4128 Returns true if this and 'container' both represent the same V* -> E map. 4129 Runs in linear time; requires that the == operator on the type E is well 4130 defined. 4131 """ 4132 return _pywrapcp.IntVarContainer___eq__(self, container) 4133 4134 def __ne__(self, container): 4135 return _pywrapcp.IntVarContainer___ne__(self, container) 4136 __swig_destroy__ = _pywrapcp.delete_IntVarContainer
4105 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4140class IntervalVarContainer(object): 4141 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4142 4143 def __init__(self, *args, **kwargs): 4144 raise AttributeError("No constructor defined") 4145 __repr__ = _swig_repr 4146 4147 def Contains(self, var): 4148 return _pywrapcp.IntervalVarContainer_Contains(self, var) 4149 4150 def Element(self, index): 4151 return _pywrapcp.IntervalVarContainer_Element(self, index) 4152 4153 def Size(self): 4154 return _pywrapcp.IntervalVarContainer_Size(self) 4155 4156 def Store(self): 4157 return _pywrapcp.IntervalVarContainer_Store(self) 4158 4159 def Restore(self): 4160 return _pywrapcp.IntervalVarContainer_Restore(self) 4161 4162 def __eq__(self, container): 4163 r""" 4164 Returns true if this and 'container' both represent the same V* -> E map. 4165 Runs in linear time; requires that the == operator on the type E is well 4166 defined. 4167 """ 4168 return _pywrapcp.IntervalVarContainer___eq__(self, container) 4169 4170 def __ne__(self, container): 4171 return _pywrapcp.IntervalVarContainer___ne__(self, container) 4172 __swig_destroy__ = _pywrapcp.delete_IntervalVarContainer
4141 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4176class SequenceVarContainer(object): 4177 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4178 4179 def __init__(self, *args, **kwargs): 4180 raise AttributeError("No constructor defined") 4181 __repr__ = _swig_repr 4182 4183 def Contains(self, var): 4184 return _pywrapcp.SequenceVarContainer_Contains(self, var) 4185 4186 def Element(self, index): 4187 return _pywrapcp.SequenceVarContainer_Element(self, index) 4188 4189 def Size(self): 4190 return _pywrapcp.SequenceVarContainer_Size(self) 4191 4192 def Store(self): 4193 return _pywrapcp.SequenceVarContainer_Store(self) 4194 4195 def Restore(self): 4196 return _pywrapcp.SequenceVarContainer_Restore(self) 4197 4198 def __eq__(self, container): 4199 r""" 4200 Returns true if this and 'container' both represent the same V* -> E map. 4201 Runs in linear time; requires that the == operator on the type E is well 4202 defined. 4203 """ 4204 return _pywrapcp.SequenceVarContainer___eq__(self, container) 4205 4206 def __ne__(self, container): 4207 return _pywrapcp.SequenceVarContainer___ne__(self, container) 4208 __swig_destroy__ = _pywrapcp.delete_SequenceVarContainer
4177 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4212class LocalSearchOperator(BaseObject): 4213 r""" 4214 The base class for all local search operators. 4215 4216 A local search operator is an object that defines the neighborhood of a 4217 solution. In other words, a neighborhood is the set of solutions which can 4218 be reached from a given solution using an operator. 4219 4220 The behavior of the LocalSearchOperator class is similar to iterators. 4221 The operator is synchronized with an assignment (gives the 4222 current values of the variables); this is done in the Start() method. 4223 4224 Then one can iterate over the neighbors using the MakeNextNeighbor method. 4225 This method returns an assignment which represents the incremental changes 4226 to the current solution. It also returns a second assignment representing 4227 the changes to the last solution defined by the neighborhood operator; this 4228 assignment is empty if the neighborhood operator cannot track this 4229 information. 4230 """ 4231 4232 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4233 4234 def __init__(self, *args, **kwargs): 4235 raise AttributeError("No constructor defined - class is abstract") 4236 __repr__ = _swig_repr 4237 4238 def NextNeighbor(self, delta, deltadelta): 4239 return _pywrapcp.LocalSearchOperator_NextNeighbor(self, delta, deltadelta) 4240 4241 def Start(self, assignment): 4242 return _pywrapcp.LocalSearchOperator_Start(self, assignment) 4243 def __disown__(self): 4244 self.this.disown() 4245 _pywrapcp.disown_LocalSearchOperator(self) 4246 return weakref.proxy(self)
The base class for all local search operators.
A local search operator is an object that defines the neighborhood of a solution. In other words, a neighborhood is the set of solutions which can be reached from a given solution using an operator.
The behavior of the LocalSearchOperator class is similar to iterators. The operator is synchronized with an assignment (gives the current values of the variables); this is done in the Start() method.
Then one can iterate over the neighbors using the MakeNextNeighbor method. This method returns an assignment which represents the incremental changes to the current solution. It also returns a second assignment representing the changes to the last solution defined by the neighborhood operator; this assignment is empty if the neighborhood operator cannot track this information.
4232 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Inherited Members
4250class IntVarLocalSearchOperator(LocalSearchOperator): 4251 r""" 4252 Specialization of LocalSearchOperator built from an array of IntVars 4253 which specifies the scope of the operator. 4254 This class also takes care of storing current variable values in Start(), 4255 keeps track of changes done by the operator and builds the delta. 4256 The Deactivate() method can be used to perform Large Neighborhood Search. 4257 """ 4258 4259 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4260 __repr__ = _swig_repr 4261 4262 def __init__(self, vars, keep_inverse_values=False): 4263 if self.__class__ == IntVarLocalSearchOperator: 4264 _self = None 4265 else: 4266 _self = self 4267 _pywrapcp.IntVarLocalSearchOperator_swiginit(self, _pywrapcp.new_IntVarLocalSearchOperator(_self, vars, keep_inverse_values)) 4268 __swig_destroy__ = _pywrapcp.delete_IntVarLocalSearchOperator 4269 4270 def Start(self, assignment): 4271 r""" 4272 This method should not be overridden. Override OnStart() instead which is 4273 called before exiting this method. 4274 """ 4275 return _pywrapcp.IntVarLocalSearchOperator_Start(self, assignment) 4276 4277 def IsIncremental(self): 4278 return _pywrapcp.IntVarLocalSearchOperator_IsIncremental(self) 4279 4280 def Size(self): 4281 return _pywrapcp.IntVarLocalSearchOperator_Size(self) 4282 4283 def Value(self, index): 4284 r""" 4285 Returns the value in the current assignment of the variable of given 4286 index. 4287 """ 4288 return _pywrapcp.IntVarLocalSearchOperator_Value(self, index) 4289 4290 def Var(self, index): 4291 r"""Returns the variable of given index.""" 4292 return _pywrapcp.IntVarLocalSearchOperator_Var(self, index) 4293 4294 def OldValue(self, index): 4295 return _pywrapcp.IntVarLocalSearchOperator_OldValue(self, index) 4296 4297 def PrevValue(self, index): 4298 return _pywrapcp.IntVarLocalSearchOperator_PrevValue(self, index) 4299 4300 def SetValue(self, index, value): 4301 return _pywrapcp.IntVarLocalSearchOperator_SetValue(self, index, value) 4302 4303 def Activated(self, index): 4304 return _pywrapcp.IntVarLocalSearchOperator_Activated(self, index) 4305 4306 def Activate(self, index): 4307 return _pywrapcp.IntVarLocalSearchOperator_Activate(self, index) 4308 4309 def Deactivate(self, index): 4310 return _pywrapcp.IntVarLocalSearchOperator_Deactivate(self, index) 4311 4312 def AddVars(self, vars): 4313 return _pywrapcp.IntVarLocalSearchOperator_AddVars(self, vars) 4314 4315 def OnStart(self): 4316 r""" 4317 Called by Start() after synchronizing the operator with the current 4318 assignment. Should be overridden instead of Start() to avoid calling 4319 IntVarLocalSearchOperator::Start explicitly. 4320 """ 4321 return _pywrapcp.IntVarLocalSearchOperator_OnStart(self) 4322 4323 def NextNeighbor(self, delta, deltadelta): 4324 r""" 4325 OnStart() should really be protected, but then SWIG doesn't see it. So we 4326 make it public, but only subclasses should access to it (to override it). 4327 Redefines MakeNextNeighbor to export a simpler interface. The calls to 4328 ApplyChanges() and RevertChanges() are factored in this method, hiding 4329 both delta and deltadelta from subclasses which only need to override 4330 MakeOneNeighbor(). 4331 Therefore this method should not be overridden. Override MakeOneNeighbor() 4332 instead. 4333 """ 4334 return _pywrapcp.IntVarLocalSearchOperator_NextNeighbor(self, delta, deltadelta) 4335 4336 def OneNeighbor(self): 4337 r""" 4338 Creates a new neighbor. It returns false when the neighborhood is 4339 completely explored. 4340 MakeNextNeighbor() in a subclass of IntVarLocalSearchOperator. 4341 """ 4342 return _pywrapcp.IntVarLocalSearchOperator_OneNeighbor(self) 4343 def __disown__(self): 4344 self.this.disown() 4345 _pywrapcp.disown_IntVarLocalSearchOperator(self) 4346 return weakref.proxy(self)
Specialization of LocalSearchOperator built from an array of IntVars which specifies the scope of the operator. This class also takes care of storing current variable values in Start(), keeps track of changes done by the operator and builds the delta. The Deactivate() method can be used to perform Large Neighborhood Search.
4259 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4270 def Start(self, assignment): 4271 r""" 4272 This method should not be overridden. Override OnStart() instead which is 4273 called before exiting this method. 4274 """ 4275 return _pywrapcp.IntVarLocalSearchOperator_Start(self, assignment)
This method should not be overridden. Override OnStart() instead which is called before exiting this method.
4283 def Value(self, index): 4284 r""" 4285 Returns the value in the current assignment of the variable of given 4286 index. 4287 """ 4288 return _pywrapcp.IntVarLocalSearchOperator_Value(self, index)
Returns the value in the current assignment of the variable of given index.
4290 def Var(self, index): 4291 r"""Returns the variable of given index.""" 4292 return _pywrapcp.IntVarLocalSearchOperator_Var(self, index)
Returns the variable of given index.
4315 def OnStart(self): 4316 r""" 4317 Called by Start() after synchronizing the operator with the current 4318 assignment. Should be overridden instead of Start() to avoid calling 4319 IntVarLocalSearchOperator::Start explicitly. 4320 """ 4321 return _pywrapcp.IntVarLocalSearchOperator_OnStart(self)
Called by Start() after synchronizing the operator with the current assignment. Should be overridden instead of Start() to avoid calling IntVarLocalSearchOperator::Start explicitly.
4323 def NextNeighbor(self, delta, deltadelta): 4324 r""" 4325 OnStart() should really be protected, but then SWIG doesn't see it. So we 4326 make it public, but only subclasses should access to it (to override it). 4327 Redefines MakeNextNeighbor to export a simpler interface. The calls to 4328 ApplyChanges() and RevertChanges() are factored in this method, hiding 4329 both delta and deltadelta from subclasses which only need to override 4330 MakeOneNeighbor(). 4331 Therefore this method should not be overridden. Override MakeOneNeighbor() 4332 instead. 4333 """ 4334 return _pywrapcp.IntVarLocalSearchOperator_NextNeighbor(self, delta, deltadelta)
OnStart() should really be protected, but then SWIG doesn't see it. So we make it public, but only subclasses should access to it (to override it). Redefines MakeNextNeighbor to export a simpler interface. The calls to ApplyChanges() and RevertChanges() are factored in this method, hiding both delta and deltadelta from subclasses which only need to override MakeOneNeighbor(). Therefore this method should not be overridden. Override MakeOneNeighbor() instead.
4336 def OneNeighbor(self): 4337 r""" 4338 Creates a new neighbor. It returns false when the neighborhood is 4339 completely explored. 4340 MakeNextNeighbor() in a subclass of IntVarLocalSearchOperator. 4341 """ 4342 return _pywrapcp.IntVarLocalSearchOperator_OneNeighbor(self)
Creates a new neighbor. It returns false when the neighborhood is completely explored. MakeNextNeighbor() in a subclass of IntVarLocalSearchOperator.
Inherited Members
4350class BaseLns(IntVarLocalSearchOperator): 4351 r""" 4352 This is the base class for building an Lns operator. An Lns fragment is a 4353 collection of variables which will be relaxed. Fragments are built with 4354 NextFragment(), which returns false if there are no more fragments to build. 4355 Optionally one can override InitFragments, which is called from 4356 LocalSearchOperator::Start to initialize fragment data. 4357 4358 Here's a sample relaxing one variable at a time: 4359 4360 class OneVarLns : public BaseLns { 4361 public: 4362 OneVarLns(const std::vector<IntVar*>& vars) : BaseLns(vars), index_(0) {} 4363 virtual ~OneVarLns() {} 4364 virtual void InitFragments() { index_ = 0; } 4365 virtual bool NextFragment() { 4366 const int size = Size(); 4367 if (index_ < size) { 4368 AppendToFragment(index_); 4369 ++index_; 4370 return true; 4371 } else { 4372 return false; 4373 } 4374 } 4375 4376 private: 4377 int index_; 4378 }; 4379 """ 4380 4381 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4382 __repr__ = _swig_repr 4383 4384 def __init__(self, vars): 4385 if self.__class__ == BaseLns: 4386 _self = None 4387 else: 4388 _self = self 4389 _pywrapcp.BaseLns_swiginit(self, _pywrapcp.new_BaseLns(_self, vars)) 4390 __swig_destroy__ = _pywrapcp.delete_BaseLns 4391 4392 def InitFragments(self): 4393 return _pywrapcp.BaseLns_InitFragments(self) 4394 4395 def NextFragment(self): 4396 return _pywrapcp.BaseLns_NextFragment(self) 4397 4398 def AppendToFragment(self, index): 4399 return _pywrapcp.BaseLns_AppendToFragment(self, index) 4400 4401 def FragmentSize(self): 4402 return _pywrapcp.BaseLns_FragmentSize(self) 4403 4404 def __getitem__(self, index): 4405 return _pywrapcp.BaseLns___getitem__(self, index) 4406 4407 def __len__(self): 4408 return _pywrapcp.BaseLns___len__(self) 4409 def __disown__(self): 4410 self.this.disown() 4411 _pywrapcp.disown_BaseLns(self) 4412 return weakref.proxy(self)
This is the base class for building an Lns operator. An Lns fragment is a collection of variables which will be relaxed. Fragments are built with NextFragment(), which returns false if there are no more fragments to build. Optionally one can override InitFragments, which is called from LocalSearchOperator::Start to initialize fragment data.
Here's a sample relaxing one variable at a time:
class OneVarLns : public BaseLns {
public:
OneVarLns(const std::vector
private: int index_; };
4381 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4416class ChangeValue(IntVarLocalSearchOperator): 4417 r""" 4418 Defines operators which change the value of variables; 4419 each neighbor corresponds to *one* modified variable. 4420 Sub-classes have to define ModifyValue which determines what the new 4421 variable value is going to be (given the current value and the variable). 4422 """ 4423 4424 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4425 __repr__ = _swig_repr 4426 4427 def __init__(self, vars): 4428 if self.__class__ == ChangeValue: 4429 _self = None 4430 else: 4431 _self = self 4432 _pywrapcp.ChangeValue_swiginit(self, _pywrapcp.new_ChangeValue(_self, vars)) 4433 __swig_destroy__ = _pywrapcp.delete_ChangeValue 4434 4435 def ModifyValue(self, index, value): 4436 return _pywrapcp.ChangeValue_ModifyValue(self, index, value) 4437 4438 def OneNeighbor(self): 4439 r"""This method should not be overridden. Override ModifyValue() instead.""" 4440 return _pywrapcp.ChangeValue_OneNeighbor(self) 4441 def __disown__(self): 4442 self.this.disown() 4443 _pywrapcp.disown_ChangeValue(self) 4444 return weakref.proxy(self)
Defines operators which change the value of variables; each neighbor corresponds to one modified variable. Sub-classes have to define ModifyValue which determines what the new variable value is going to be (given the current value and the variable).
4424 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4448class LocalSearchFilter(BaseObject): 4449 r""" 4450 Local Search Filters are used for fast neighbor pruning. 4451 Filtering a move is done in several phases: 4452 - in the Relax phase, filters determine which parts of their internals 4453 will be changed by the candidate, and modify intermediary State 4454 - in the Accept phase, filters check that the candidate is feasible, 4455 - if the Accept phase succeeds, the solver may decide to trigger a 4456 Synchronize phase that makes filters change their internal representation 4457 to the last candidate, 4458 - otherwise (Accept fails or the solver does not want to synchronize), 4459 a Revert phase makes filters erase any intermediary State generated by the 4460 Relax and Accept phases. 4461 A given filter has phases called with the following pattern: 4462 (Relax.Accept.Synchronize | Relax.Accept.Revert | Relax.Revert)*. 4463 Filters's Revert() is always called in the reverse order their Accept() was 4464 called, to allow late filters to use state done/undone by early filters' 4465 Accept()/Revert(). 4466 """ 4467 4468 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4469 4470 def __init__(self, *args, **kwargs): 4471 raise AttributeError("No constructor defined - class is abstract") 4472 __repr__ = _swig_repr 4473 4474 def Accept(self, delta, deltadelta, objective_min, objective_max): 4475 r""" 4476 Accepts a "delta" given the assignment with which the filter has been 4477 synchronized; the delta holds the variables which have been modified and 4478 their new value. 4479 If the filter represents a part of the global objective, its contribution 4480 must be between objective_min and objective_max. 4481 Sample: supposing one wants to maintain a[0,1] + b[0,1] <= 1, 4482 for the assignment (a,1), (b,0), the delta (b,1) will be rejected 4483 but the delta (a,0) will be accepted. 4484 TODO(user): Remove arguments when there are no more need for those. 4485 """ 4486 return _pywrapcp.LocalSearchFilter_Accept(self, delta, deltadelta, objective_min, objective_max) 4487 4488 def IsIncremental(self): 4489 return _pywrapcp.LocalSearchFilter_IsIncremental(self) 4490 4491 def Synchronize(self, assignment, delta): 4492 r""" 4493 Synchronizes the filter with the current solution, delta being the 4494 difference with the solution passed to the previous call to Synchronize() 4495 or IncrementalSynchronize(). 'delta' can be used to incrementally 4496 synchronizing the filter with the new solution by only considering the 4497 changes in delta. 4498 """ 4499 return _pywrapcp.LocalSearchFilter_Synchronize(self, assignment, delta) 4500 __swig_destroy__ = _pywrapcp.delete_LocalSearchFilter
Local Search Filters are used for fast neighbor pruning. Filtering a move is done in several phases:
- in the Relax phase, filters determine which parts of their internals will be changed by the candidate, and modify intermediary State
- in the Accept phase, filters check that the candidate is feasible,
- if the Accept phase succeeds, the solver may decide to trigger a Synchronize phase that makes filters change their internal representation to the last candidate,
- otherwise (Accept fails or the solver does not want to synchronize), a Revert phase makes filters erase any intermediary State generated by the Relax and Accept phases. A given filter has phases called with the following pattern: (Relax.Accept.Synchronize | Relax.Accept.Revert | Relax.Revert)*. Filters's Revert() is always called in the reverse order their Accept() was called, to allow late filters to use state done/undone by early filters' Accept()/Revert().
4468 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4474 def Accept(self, delta, deltadelta, objective_min, objective_max): 4475 r""" 4476 Accepts a "delta" given the assignment with which the filter has been 4477 synchronized; the delta holds the variables which have been modified and 4478 their new value. 4479 If the filter represents a part of the global objective, its contribution 4480 must be between objective_min and objective_max. 4481 Sample: supposing one wants to maintain a[0,1] + b[0,1] <= 1, 4482 for the assignment (a,1), (b,0), the delta (b,1) will be rejected 4483 but the delta (a,0) will be accepted. 4484 TODO(user): Remove arguments when there are no more need for those. 4485 """ 4486 return _pywrapcp.LocalSearchFilter_Accept(self, delta, deltadelta, objective_min, objective_max)
Accepts a "delta" given the assignment with which the filter has been synchronized; the delta holds the variables which have been modified and their new value. If the filter represents a part of the global objective, its contribution must be between objective_min and objective_max. Sample: supposing one wants to maintain a[0,1] + b[0,1] <= 1, for the assignment (a,1), (b,0), the delta (b,1) will be rejected but the delta (a,0) will be accepted. TODO(user): Remove arguments when there are no more need for those.
4491 def Synchronize(self, assignment, delta): 4492 r""" 4493 Synchronizes the filter with the current solution, delta being the 4494 difference with the solution passed to the previous call to Synchronize() 4495 or IncrementalSynchronize(). 'delta' can be used to incrementally 4496 synchronizing the filter with the new solution by only considering the 4497 changes in delta. 4498 """ 4499 return _pywrapcp.LocalSearchFilter_Synchronize(self, assignment, delta)
Synchronizes the filter with the current solution, delta being the difference with the solution passed to the previous call to Synchronize() or IncrementalSynchronize(). 'delta' can be used to incrementally synchronizing the filter with the new solution by only considering the changes in delta.
Inherited Members
4504class LocalSearchFilterManager(BaseObject): 4505 r""" 4506 Filter manager: when a move is made, filters are executed to decide whether 4507 the solution is feasible and compute parts of the new cost. This class 4508 schedules filter execution and composes costs as a sum. 4509 """ 4510 4511 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4512 __repr__ = _swig_repr 4513 4514 def DebugString(self): 4515 return _pywrapcp.LocalSearchFilterManager_DebugString(self) 4516 4517 def __init__(self, *args): 4518 _pywrapcp.LocalSearchFilterManager_swiginit(self, _pywrapcp.new_LocalSearchFilterManager(*args)) 4519 4520 def Accept(self, monitor, delta, deltadelta, objective_min, objective_max): 4521 r""" 4522 Returns true iff all filters return true, and the sum of their accepted 4523 objectives is between objective_min and objective_max. 4524 The monitor has its Begin/EndFiltering events triggered. 4525 """ 4526 return _pywrapcp.LocalSearchFilterManager_Accept(self, monitor, delta, deltadelta, objective_min, objective_max) 4527 4528 def Synchronize(self, assignment, delta): 4529 r"""Synchronizes all filters to assignment.""" 4530 return _pywrapcp.LocalSearchFilterManager_Synchronize(self, assignment, delta) 4531 __swig_destroy__ = _pywrapcp.delete_LocalSearchFilterManager
Filter manager: when a move is made, filters are executed to decide whether the solution is feasible and compute parts of the new cost. This class schedules filter execution and composes costs as a sum.
4511 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4520 def Accept(self, monitor, delta, deltadelta, objective_min, objective_max): 4521 r""" 4522 Returns true iff all filters return true, and the sum of their accepted 4523 objectives is between objective_min and objective_max. 4524 The monitor has its Begin/EndFiltering events triggered. 4525 """ 4526 return _pywrapcp.LocalSearchFilterManager_Accept(self, monitor, delta, deltadelta, objective_min, objective_max)
Returns true iff all filters return true, and the sum of their accepted objectives is between objective_min and objective_max. The monitor has its Begin/EndFiltering events triggered.
4535class IntVarLocalSearchFilter(LocalSearchFilter): 4536 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4537 __repr__ = _swig_repr 4538 4539 def __init__(self, vars): 4540 if self.__class__ == IntVarLocalSearchFilter: 4541 _self = None 4542 else: 4543 _self = self 4544 _pywrapcp.IntVarLocalSearchFilter_swiginit(self, _pywrapcp.new_IntVarLocalSearchFilter(_self, vars)) 4545 __swig_destroy__ = _pywrapcp.delete_IntVarLocalSearchFilter 4546 4547 def Synchronize(self, assignment, delta): 4548 r""" 4549 This method should not be overridden. Override OnSynchronize() instead 4550 which is called before exiting this method. 4551 """ 4552 return _pywrapcp.IntVarLocalSearchFilter_Synchronize(self, assignment, delta) 4553 4554 def Size(self): 4555 return _pywrapcp.IntVarLocalSearchFilter_Size(self) 4556 4557 def Value(self, index): 4558 return _pywrapcp.IntVarLocalSearchFilter_Value(self, index) 4559 4560 def IndexFromVar(self, var): 4561 return _pywrapcp.IntVarLocalSearchFilter_IndexFromVar(self, var) 4562 def __disown__(self): 4563 self.this.disown() 4564 _pywrapcp.disown_IntVarLocalSearchFilter(self) 4565 return weakref.proxy(self)
Local Search Filters are used for fast neighbor pruning. Filtering a move is done in several phases:
- in the Relax phase, filters determine which parts of their internals will be changed by the candidate, and modify intermediary State
- in the Accept phase, filters check that the candidate is feasible,
- if the Accept phase succeeds, the solver may decide to trigger a Synchronize phase that makes filters change their internal representation to the last candidate,
- otherwise (Accept fails or the solver does not want to synchronize), a Revert phase makes filters erase any intermediary State generated by the Relax and Accept phases. A given filter has phases called with the following pattern: (Relax.Accept.Synchronize | Relax.Accept.Revert | Relax.Revert)*. Filters's Revert() is always called in the reverse order their Accept() was called, to allow late filters to use state done/undone by early filters' Accept()/Revert().
4536 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4547 def Synchronize(self, assignment, delta): 4548 r""" 4549 This method should not be overridden. Override OnSynchronize() instead 4550 which is called before exiting this method. 4551 """ 4552 return _pywrapcp.IntVarLocalSearchFilter_Synchronize(self, assignment, delta)
This method should not be overridden. Override OnSynchronize() instead which is called before exiting this method.
Inherited Members
4569class BooleanVar(IntVar): 4570 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4571 4572 def __init__(self, *args, **kwargs): 4573 raise AttributeError("No constructor defined - class is abstract") 4574 __repr__ = _swig_repr 4575 4576 def Min(self): 4577 return _pywrapcp.BooleanVar_Min(self) 4578 4579 def SetMin(self, m): 4580 return _pywrapcp.BooleanVar_SetMin(self, m) 4581 4582 def Max(self): 4583 return _pywrapcp.BooleanVar_Max(self) 4584 4585 def SetMax(self, m): 4586 return _pywrapcp.BooleanVar_SetMax(self, m) 4587 4588 def SetRange(self, mi, ma): 4589 return _pywrapcp.BooleanVar_SetRange(self, mi, ma) 4590 4591 def Bound(self): 4592 return _pywrapcp.BooleanVar_Bound(self) 4593 4594 def Value(self): 4595 return _pywrapcp.BooleanVar_Value(self) 4596 4597 def RemoveValue(self, v): 4598 return _pywrapcp.BooleanVar_RemoveValue(self, v) 4599 4600 def RemoveInterval(self, l, u): 4601 return _pywrapcp.BooleanVar_RemoveInterval(self, l, u) 4602 4603 def WhenBound(self, d): 4604 return _pywrapcp.BooleanVar_WhenBound(self, d) 4605 4606 def WhenRange(self, d): 4607 return _pywrapcp.BooleanVar_WhenRange(self, d) 4608 4609 def WhenDomain(self, d): 4610 return _pywrapcp.BooleanVar_WhenDomain(self, d) 4611 4612 def Size(self): 4613 return _pywrapcp.BooleanVar_Size(self) 4614 4615 def Contains(self, v): 4616 return _pywrapcp.BooleanVar_Contains(self, v) 4617 4618 def HoleIteratorAux(self, reversible): 4619 return _pywrapcp.BooleanVar_HoleIteratorAux(self, reversible) 4620 4621 def DomainIteratorAux(self, reversible): 4622 return _pywrapcp.BooleanVar_DomainIteratorAux(self, reversible) 4623 4624 def DebugString(self): 4625 return _pywrapcp.BooleanVar_DebugString(self)
The class IntVar is a subset of IntExpr. In addition to the IntExpr protocol, it offers persistence, removing values from the domains, and a finer model for events.
4570 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
This method returns the value of the variable. This method checks before that the variable is bound.
This method removes the interval 'l' .. 'u' from the domain of the variable. It assumes that 'l' <= 'u'.
Overload 1: This method attaches a demon that will be awakened when the variable is bound.
|
Overload 2: This method attaches a closure that will be awakened when the variable is bound.
Overload 1: Attach a demon that will watch the min or the max of the expression.
|
Overload 2: Attach a demon that will watch the min or the max of the expression.
Overload 1: This method attaches a demon that will watch any domain modification of the domain of the variable.
|
Overload 2: This method attaches a closure that will watch any domain modification of the domain of the variable.
4618 def HoleIteratorAux(self, reversible): 4619 return _pywrapcp.BooleanVar_HoleIteratorAux(self, reversible)
Creates a hole iterator. When 'reversible' is false, the returned object is created on the normal C++ heap and the solver does NOT take ownership of the object.
4621 def DomainIteratorAux(self, reversible): 4622 return _pywrapcp.BooleanVar_DomainIteratorAux(self, reversible)
Creates a domain iterator. When 'reversible' is false, the returned object is created on the normal C++ heap and the solver does NOT take ownership of the object.
4630class PyDecision(Decision): 4631 def ApplyWrapper(self, solver): 4632 try: 4633 self.Apply(solver) 4634 except Exception as e: 4635 if 'CP Solver fail' in str(e): 4636 solver.ShouldFail() 4637 else: 4638 raise 4639 4640 def RefuteWrapper(self, solver): 4641 try: 4642 self.Refute(solver) 4643 except Exception as e: 4644 if 'CP Solver fail' in str(e): 4645 solver.ShouldFail() 4646 else: 4647 raise 4648 4649 def DebugString(self): 4650 return "PyDecision"
A Decision represents a choice point in the search tree. The two main methods are Apply() to go left, or Refute() to go right.
4631 def ApplyWrapper(self, solver): 4632 try: 4633 self.Apply(solver) 4634 except Exception as e: 4635 if 'CP Solver fail' in str(e): 4636 solver.ShouldFail() 4637 else: 4638 raise
Apply will be called first when the decision is executed.
4653class PyDecisionBuilder(DecisionBuilder): 4654 def NextWrapper(self, solver): 4655 try: 4656 return self.Next(solver) 4657 except Exception as e: 4658 if 'CP Solver fail' in str(e): 4659 return solver.FailDecision() 4660 else: 4661 raise 4662 4663 def DebugString(self): 4664 return "PyDecisionBuilder"
A DecisionBuilder is responsible for creating the search tree. The important method is Next(), which returns the next decision to execute.
4654 def NextWrapper(self, solver): 4655 try: 4656 return self.Next(solver) 4657 except Exception as e: 4658 if 'CP Solver fail' in str(e): 4659 return solver.FailDecision() 4660 else: 4661 raise
This is the main method of the decision builder class. It must return a decision (an instance of the class Decision). If it returns nullptr, this means that the decision builder has finished its work.
Inherited Members
4667class PyDemon(Demon): 4668 def RunWrapper(self, solver): 4669 try: 4670 self.Run(solver) 4671 except Exception as e: 4672 if 'CP Solver fail' in str(e): 4673 solver.ShouldFail() 4674 else: 4675 raise 4676 4677 def DebugString(self): 4678 return "PyDemon"
A Demon is the base element of a propagation queue. It is the main object responsible for implementing the actual propagation of the constraint and pruning the inconsistent values in the domains of the variables. The main concept is that demons are listeners that are attached to the variables and listen to their modifications.
There are two methods:
- Run() is the actual method called when the demon is processed.
- priority() returns its priority. Standard priorities are slow, normal or fast. "immediate" is reserved for variables and is treated separately.
4681class PyConstraintDemon(PyDemon): 4682 def __init__(self, ct, method, delayed, *args): 4683 super().__init__() 4684 self.__constraint = ct 4685 self.__method = method 4686 self.__delayed = delayed 4687 self.__args = args 4688 4689 def Run(self, solver): 4690 self.__method(self.__constraint, *self.__args) 4691 4692 def Priority(self): 4693 return Solver.DELAYED_PRIORITY if self.__delayed else Solver.NORMAL_PRIORITY 4694 4695 def DebugString(self): 4696 return 'PyConstraintDemon'
A Demon is the base element of a propagation queue. It is the main object responsible for implementing the actual propagation of the constraint and pruning the inconsistent values in the domains of the variables. The main concept is that demons are listeners that are attached to the variables and listen to their modifications.
There are two methods:
- Run() is the actual method called when the demon is processed.
- priority() returns its priority. Standard priorities are slow, normal or fast. "immediate" is reserved for variables and is treated separately.
4682 def __init__(self, ct, method, delayed, *args): 4683 super().__init__() 4684 self.__constraint = ct 4685 self.__method = method 4686 self.__delayed = delayed 4687 self.__args = args
This indicates the priority of a demon. Immediate demons are treated separately and corresponds to variables.
4692 def Priority(self): 4693 return Solver.DELAYED_PRIORITY if self.__delayed else Solver.NORMAL_PRIORITY
This method returns the priority of the demon. Usually a demon is fast, slow or normal. Immediate demons are reserved for internal use to maintain variables.
Inherited Members
4699class PyConstraint(Constraint): 4700 def __init__(self, solver): 4701 super().__init__(solver) 4702 self.__demons = [] 4703 4704 def Demon(self, method, *args): 4705 demon = PyConstraintDemon(self, method, False, *args) 4706 self.__demons.append(demon) 4707 return demon 4708 4709 def DelayedDemon(self, method, *args): 4710 demon = PyConstraintDemon(self, method, True, *args) 4711 self.__demons.append(demon) 4712 return demon 4713 4714 def InitialPropagateDemon(self): 4715 return self.solver().ConstraintInitialPropagateCallback(self) 4716 4717 def DelayedInitialPropagateDemon(self): 4718 return self.solver().DelayedConstraintInitialPropagateCallback(self) 4719 4720 def InitialPropagateWrapper(self): 4721 try: 4722 self.InitialPropagate() 4723 except Exception as e: 4724 if 'CP Solver fail' in str(e): 4725 self.solver().ShouldFail() 4726 else: 4727 raise 4728 4729 def DebugString(self): 4730 return "PyConstraint"
A constraint is the main modeling object. It provides two methods:
- Post() is responsible for creating the demons and attaching them to immediate demons().
- InitialPropagate() is called once just after Post and performs the initial propagation. The subsequent propagations will be performed by the demons Posted during the post() method.
4720 def InitialPropagateWrapper(self): 4721 try: 4722 self.InitialPropagate() 4723 except Exception as e: 4724 if 'CP Solver fail' in str(e): 4725 self.solver().ShouldFail() 4726 else: 4727 raise
This method performs the initial propagation of the constraint. It is called just after the post.
Inherited Members
4732class RoutingIndexManager(object): 4733 r""" 4734 Manager for any NodeIndex <-> variable index conversion. 4735 The routing solver uses variable indices internally and through 4736 its API. 4737 These variable indices are tricky to manage directly because one Node can 4738 correspond to a multitude of variables, depending on the number of times 4739 they appear in the model, and if they're used as start and/or end points. 4740 This class aims to simplify variable index usage, allowing users to use 4741 NodeIndex instead. 4742 4743 Usage: 4744 4745 .. code-block:: c++ 4746 4747 auto starts_ends = ...; /// These are NodeIndex. 4748 RoutingIndexManager manager(10, 4, starts_ends); // 10 nodes, 4 vehicles. 4749 RoutingModel model(manager); 4750 4751 Then, use 'manager.NodeToIndex(node)' whenever model requires a variable 4752 index. 4753 4754 Note: the mapping between node indices and variables indices is subject to 4755 change so no assumption should be made on it. The only guarantee is that 4756 indices range between 0 and n-1, where n = number of vehicles * 2 (for start 4757 and end nodes) + number of non-start or end nodes. 4758 """ 4759 4760 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4761 __repr__ = _swig_repr 4762 4763 def __init__(self, *args): 4764 r""" 4765 *Overload 1:* 4766 Creates a NodeIndex to variable index mapping for a problem 4767 containing 'num_nodes', 'num_vehicles' and the given starts and ends for 4768 each vehicle. If used, any start/end arrays have to have exactly 4769 'num_vehicles' elements. 4770 :type num_nodes: int 4771 :param num_nodes: Number of nodes in the problem. 4772 :type num_vehicles: int 4773 :param num_vehicles: Number of vehicles in the problem. 4774 :type depot: operations_research::RoutingIndexManager::NodeIndex 4775 :param depot: 'start' and 'end' 4776 NodeIndex for all vehicles. 4777 4778 | 4779 4780 *Overload 2:* 4781 Creates a NodeIndex to variable index mapping. 4782 :type num_nodes: int 4783 :param num_nodes: Number of nodes in the problem. 4784 :type num_vehicles: int 4785 :param num_vehicles: Number of vehicles in the problem. 4786 :type starts: std::vector< operations_research::RoutingIndexManager::NodeIndex > 4787 :param starts: Array containing the start NodeIndex for each vehicle. 4788 :type ends: std::vector< operations_research::RoutingIndexManager::NodeIndex > 4789 :param ends: Array containing the end NodeIndex for each vehicle. 4790 Notes: **starts** and **ends** arrays must have **exactly** 'num_vehicles' 4791 elements. 4792 """ 4793 _pywrapcp.RoutingIndexManager_swiginit(self, _pywrapcp.new_RoutingIndexManager(*args)) 4794 4795 def GetNumberOfNodes(self): 4796 return _pywrapcp.RoutingIndexManager_GetNumberOfNodes(self) 4797 4798 def GetNumberOfVehicles(self): 4799 return _pywrapcp.RoutingIndexManager_GetNumberOfVehicles(self) 4800 4801 def GetNumberOfIndices(self): 4802 return _pywrapcp.RoutingIndexManager_GetNumberOfIndices(self) 4803 4804 def GetStartIndex(self, vehicle): 4805 return _pywrapcp.RoutingIndexManager_GetStartIndex(self, vehicle) 4806 4807 def GetEndIndex(self, vehicle): 4808 return _pywrapcp.RoutingIndexManager_GetEndIndex(self, vehicle) 4809 4810 def NodeToIndex(self, node): 4811 return _pywrapcp.RoutingIndexManager_NodeToIndex(self, node) 4812 4813 def IndexToNode(self, index): 4814 return _pywrapcp.RoutingIndexManager_IndexToNode(self, index) 4815 __swig_destroy__ = _pywrapcp.delete_RoutingIndexManager
Manager for any NodeIndex <-> variable index conversion. The routing solver uses variable indices internally and through its API. These variable indices are tricky to manage directly because one Node can correspond to a multitude of variables, depending on the number of times they appear in the model, and if they're used as start and/or end points. This class aims to simplify variable index usage, allowing users to use NodeIndex instead.
Usage:
```c++
auto starts_ends = ...; /// These are NodeIndex. RoutingIndexManager manager(10, 4, starts_ends); // 10 nodes, 4 vehicles. RoutingModel model(manager); ```
Then, use 'manager.NodeToIndex(node)' whenever model requires a variable index.
Note: the mapping between node indices and variables indices is subject to change so no assumption should be made on it. The only guarantee is that indices range between 0 and n-1, where n = number of vehicles * 2 (for start and end nodes) + number of non-start or end nodes.
4763 def __init__(self, *args): 4764 r""" 4765 *Overload 1:* 4766 Creates a NodeIndex to variable index mapping for a problem 4767 containing 'num_nodes', 'num_vehicles' and the given starts and ends for 4768 each vehicle. If used, any start/end arrays have to have exactly 4769 'num_vehicles' elements. 4770 :type num_nodes: int 4771 :param num_nodes: Number of nodes in the problem. 4772 :type num_vehicles: int 4773 :param num_vehicles: Number of vehicles in the problem. 4774 :type depot: operations_research::RoutingIndexManager::NodeIndex 4775 :param depot: 'start' and 'end' 4776 NodeIndex for all vehicles. 4777 4778 | 4779 4780 *Overload 2:* 4781 Creates a NodeIndex to variable index mapping. 4782 :type num_nodes: int 4783 :param num_nodes: Number of nodes in the problem. 4784 :type num_vehicles: int 4785 :param num_vehicles: Number of vehicles in the problem. 4786 :type starts: std::vector< operations_research::RoutingIndexManager::NodeIndex > 4787 :param starts: Array containing the start NodeIndex for each vehicle. 4788 :type ends: std::vector< operations_research::RoutingIndexManager::NodeIndex > 4789 :param ends: Array containing the end NodeIndex for each vehicle. 4790 Notes: **starts** and **ends** arrays must have **exactly** 'num_vehicles' 4791 elements. 4792 """ 4793 _pywrapcp.RoutingIndexManager_swiginit(self, _pywrapcp.new_RoutingIndexManager(*args))
Overload 1: Creates a NodeIndex to variable index mapping for a problem containing 'num_nodes', 'num_vehicles' and the given starts and ends for each vehicle. If used, any start/end arrays have to have exactly 'num_vehicles' elements.
Parameters
- num_nodes: Number of nodes in the problem.
- num_vehicles: Number of vehicles in the problem.
- depot: 'start' and 'end' NodeIndex for all vehicles.
|
Overload 2: Creates a NodeIndex to variable index mapping.
- num_nodes: Number of nodes in the problem.
- num_vehicles: Number of vehicles in the problem.
- starts: Array containing the start NodeIndex for each vehicle.
- ends: Array containing the end NodeIndex for each vehicle. Notes: starts and ends arrays must have exactly 'num_vehicles' elements.
4760 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4826def FindErrorInRoutingSearchParameters(search_parameters): 4827 r""" 4828 Returns an empty std::string if the routing search parameters are valid, and 4829 a non-empty, human readable error description if they're not. 4830 """ 4831 return _pywrapcp.FindErrorInRoutingSearchParameters(search_parameters)
Returns an empty std::string if the routing search parameters are valid, and a non-empty, human readable error description if they're not.
4835class FirstSolutionStrategy(object): 4836 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4837 __repr__ = _swig_repr 4838 4839 def __init__(self): 4840 _pywrapcp.FirstSolutionStrategy_swiginit(self, _pywrapcp.new_FirstSolutionStrategy()) 4841 __swig_destroy__ = _pywrapcp.delete_FirstSolutionStrategy
4836 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4845class LocalSearchMetaheuristic(object): 4846 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4847 __repr__ = _swig_repr 4848 4849 def __init__(self): 4850 _pywrapcp.LocalSearchMetaheuristic_swiginit(self, _pywrapcp.new_LocalSearchMetaheuristic()) 4851 __swig_destroy__ = _pywrapcp.delete_LocalSearchMetaheuristic
4846 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4855class RoutingSearchStatus(object): 4856 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4857 __repr__ = _swig_repr 4858 4859 def __init__(self): 4860 _pywrapcp.RoutingSearchStatus_swiginit(self, _pywrapcp.new_RoutingSearchStatus()) 4861 __swig_destroy__ = _pywrapcp.delete_RoutingSearchStatus
4856 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4865class PathsMetadata(object): 4866 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4867 __repr__ = _swig_repr 4868 4869 def __init__(self, manager): 4870 _pywrapcp.PathsMetadata_swiginit(self, _pywrapcp.new_PathsMetadata(manager)) 4871 4872 def IsStart(self, node): 4873 return _pywrapcp.PathsMetadata_IsStart(self, node) 4874 4875 def IsEnd(self, node): 4876 return _pywrapcp.PathsMetadata_IsEnd(self, node) 4877 4878 def GetPath(self, start_or_end_node): 4879 return _pywrapcp.PathsMetadata_GetPath(self, start_or_end_node) 4880 4881 def NumPaths(self): 4882 return _pywrapcp.PathsMetadata_NumPaths(self) 4883 4884 def Paths(self): 4885 return _pywrapcp.PathsMetadata_Paths(self) 4886 4887 def Starts(self): 4888 return _pywrapcp.PathsMetadata_Starts(self) 4889 4890 def Start(self, path): 4891 return _pywrapcp.PathsMetadata_Start(self, path) 4892 4893 def End(self, path): 4894 return _pywrapcp.PathsMetadata_End(self, path) 4895 4896 def Ends(self): 4897 return _pywrapcp.PathsMetadata_Ends(self) 4898 __swig_destroy__ = _pywrapcp.delete_PathsMetadata
4866 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4902class RoutingSearchStats(object): 4903 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4904 __repr__ = _swig_repr 4905 num_cp_sat_calls_in_lp_scheduling = property(_pywrapcp.RoutingSearchStats_num_cp_sat_calls_in_lp_scheduling_get, _pywrapcp.RoutingSearchStats_num_cp_sat_calls_in_lp_scheduling_set) 4906 num_glop_calls_in_lp_scheduling = property(_pywrapcp.RoutingSearchStats_num_glop_calls_in_lp_scheduling_get, _pywrapcp.RoutingSearchStats_num_glop_calls_in_lp_scheduling_set) 4907 num_min_cost_flow_calls = property(_pywrapcp.RoutingSearchStats_num_min_cost_flow_calls_get, _pywrapcp.RoutingSearchStats_num_min_cost_flow_calls_set) 4908 num_cp_sat_calls_in_routing = property(_pywrapcp.RoutingSearchStats_num_cp_sat_calls_in_routing_get, _pywrapcp.RoutingSearchStats_num_cp_sat_calls_in_routing_set) 4909 num_generalized_cp_sat_calls_in_routing = property(_pywrapcp.RoutingSearchStats_num_generalized_cp_sat_calls_in_routing_get, _pywrapcp.RoutingSearchStats_num_generalized_cp_sat_calls_in_routing_set) 4910 4911 def __init__(self): 4912 _pywrapcp.RoutingSearchStats_swiginit(self, _pywrapcp.new_RoutingSearchStats()) 4913 __swig_destroy__ = _pywrapcp.delete_RoutingSearchStats
4903 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4917class RoutingModel(object): 4918 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 4919 __repr__ = _swig_repr 4920 PICKUP_AND_DELIVERY_NO_ORDER = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_NO_ORDER 4921 r"""Any precedence is accepted.""" 4922 PICKUP_AND_DELIVERY_LIFO = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_LIFO 4923 r"""Deliveries must be performed in reverse order of pickups.""" 4924 PICKUP_AND_DELIVERY_FIFO = _pywrapcp.RoutingModel_PICKUP_AND_DELIVERY_FIFO 4925 r"""Deliveries must be performed in the same order as pickups.""" 4926 4927 def __init__(self, *args): 4928 r""" 4929 Constructor taking an index manager. The version which does not take 4930 RoutingModelParameters is equivalent to passing 4931 DefaultRoutingModelParameters(). 4932 """ 4933 _pywrapcp.RoutingModel_swiginit(self, _pywrapcp.new_RoutingModel(*args)) 4934 __swig_destroy__ = _pywrapcp.delete_RoutingModel 4935 kTransitEvaluatorSignUnknown = _pywrapcp.RoutingModel_kTransitEvaluatorSignUnknown 4936 kTransitEvaluatorSignPositiveOrZero = _pywrapcp.RoutingModel_kTransitEvaluatorSignPositiveOrZero 4937 kTransitEvaluatorSignNegativeOrZero = _pywrapcp.RoutingModel_kTransitEvaluatorSignNegativeOrZero 4938 4939 def RegisterUnaryTransitVector(self, values): 4940 r""" 4941 Registers 'callback' and returns its index. 4942 The sign parameter allows to notify the solver that the callback only 4943 return values of the given sign. This can help the solver, but passing 4944 an incorrect sign may crash in non-opt compilation mode, and yield 4945 incorrect results in opt. 4946 """ 4947 return _pywrapcp.RoutingModel_RegisterUnaryTransitVector(self, values) 4948 4949 def RegisterUnaryTransitCallback(self, *args): 4950 return _pywrapcp.RoutingModel_RegisterUnaryTransitCallback(self, *args) 4951 4952 def RegisterTransitMatrix(self, values): 4953 return _pywrapcp.RoutingModel_RegisterTransitMatrix(self, values) 4954 4955 def RegisterTransitCallback(self, *args): 4956 return _pywrapcp.RoutingModel_RegisterTransitCallback(self, *args) 4957 4958 def RegisterCumulDependentTransitCallback(self, callback): 4959 return _pywrapcp.RoutingModel_RegisterCumulDependentTransitCallback(self, callback) 4960 4961 def TransitCallback(self, callback_index): 4962 return _pywrapcp.RoutingModel_TransitCallback(self, callback_index) 4963 4964 def UnaryTransitCallbackOrNull(self, callback_index): 4965 return _pywrapcp.RoutingModel_UnaryTransitCallbackOrNull(self, callback_index) 4966 4967 def CumulDependentTransitCallback(self, callback_index): 4968 return _pywrapcp.RoutingModel_CumulDependentTransitCallback(self, callback_index) 4969 4970 def AddDimension(self, evaluator_index, slack_max, capacity, fix_start_cumul_to_zero, name): 4971 r""" 4972 Model creation 4973 Methods to add dimensions to routes; dimensions represent quantities 4974 accumulated at nodes along the routes. They represent quantities such as 4975 weights or volumes carried along the route, or distance or times. 4976 Quantities at a node are represented by "cumul" variables and the increase 4977 or decrease of quantities between nodes are represented by "transit" 4978 variables. These variables are linked as follows: 4979 if j == next(i), cumul(j) = cumul(i) + transit(i, j) + slack(i) 4980 where slack is a positive slack variable (can represent waiting times for 4981 a time dimension). 4982 Setting the value of fix_start_cumul_to_zero to true will force the 4983 "cumul" variable of the start node of all vehicles to be equal to 0. 4984 Creates a dimension where the transit variable is constrained to be 4985 equal to evaluator(i, next(i)); 'slack_max' is the upper bound of the 4986 slack variable and 'capacity' is the upper bound of the cumul variables. 4987 'name' is the name used to reference the dimension; this name is used to 4988 get cumul and transit variables from the routing model. 4989 Returns false if a dimension with the same name has already been created 4990 (and doesn't create the new dimension). 4991 Takes ownership of the callback 'evaluator'. 4992 """ 4993 return _pywrapcp.RoutingModel_AddDimension(self, evaluator_index, slack_max, capacity, fix_start_cumul_to_zero, name) 4994 4995 def AddDimensionWithVehicleTransits(self, evaluator_indices, slack_max, capacity, fix_start_cumul_to_zero, name): 4996 return _pywrapcp.RoutingModel_AddDimensionWithVehicleTransits(self, evaluator_indices, slack_max, capacity, fix_start_cumul_to_zero, name) 4997 4998 def AddDimensionWithVehicleCapacity(self, evaluator_index, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name): 4999 return _pywrapcp.RoutingModel_AddDimensionWithVehicleCapacity(self, evaluator_index, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name) 5000 5001 def AddDimensionWithVehicleTransitAndCapacity(self, evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name): 5002 return _pywrapcp.RoutingModel_AddDimensionWithVehicleTransitAndCapacity(self, evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name) 5003 5004 def AddDimensionWithCumulDependentVehicleTransitAndCapacity(self, fixed_evaluator_indices, cumul_dependent_evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name): 5005 r""" 5006 Creates a dimension where the transit variable on arc i->j is the sum of: 5007 - A "fixed" transit value, obtained from the fixed_evaluator_index for 5008 this vehicle, referencing evaluators in transit_evaluators_, and 5009 - A FloatSlopePiecewiseLinearFunction of the cumul of node i, obtained 5010 from the cumul_dependent_evaluator_index of this vehicle, pointing to 5011 an evaluator in cumul_dependent_transit_evaluators_. 5012 """ 5013 return _pywrapcp.RoutingModel_AddDimensionWithCumulDependentVehicleTransitAndCapacity(self, fixed_evaluator_indices, cumul_dependent_evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name) 5014 5015 def AddConstantDimensionWithSlack(self, value, capacity, slack_max, fix_start_cumul_to_zero, name): 5016 r""" 5017 Creates a dimension where the transit variable is constrained to be 5018 equal to 'value'; 'capacity' is the upper bound of the cumul variables. 5019 'name' is the name used to reference the dimension; this name is used to 5020 get cumul and transit variables from the routing model. 5021 Returns a pair consisting of an index to the registered unary transit 5022 callback and a bool denoting whether the dimension has been created. 5023 It is false if a dimension with the same name has already been created 5024 (and doesn't create the new dimension but still register a new callback). 5025 """ 5026 return _pywrapcp.RoutingModel_AddConstantDimensionWithSlack(self, value, capacity, slack_max, fix_start_cumul_to_zero, name) 5027 5028 def AddConstantDimension(self, value, capacity, fix_start_cumul_to_zero, name): 5029 return _pywrapcp.RoutingModel_AddConstantDimension(self, value, capacity, fix_start_cumul_to_zero, name) 5030 5031 def AddVectorDimension(self, values, capacity, fix_start_cumul_to_zero, name): 5032 r""" 5033 Creates a dimension where the transit variable is constrained to be 5034 equal to 'values[i]' for node i; 'capacity' is the upper bound of 5035 the cumul variables. 'name' is the name used to reference the dimension; 5036 this name is used to get cumul and transit variables from the routing 5037 model. 5038 Returns a pair consisting of an index to the registered unary transit 5039 callback and a bool denoting whether the dimension has been created. 5040 It is false if a dimension with the same name has already been created 5041 (and doesn't create the new dimension but still register a new callback). 5042 """ 5043 return _pywrapcp.RoutingModel_AddVectorDimension(self, values, capacity, fix_start_cumul_to_zero, name) 5044 5045 def AddMatrixDimension(self, values, capacity, fix_start_cumul_to_zero, name): 5046 r""" 5047 Creates a dimension where the transit variable is constrained to be 5048 equal to 'values[i][next(i)]' for node i; 'capacity' is the upper bound of 5049 the cumul variables. 'name' is the name used to reference the dimension; 5050 this name is used to get cumul and transit variables from the routing 5051 model. 5052 Returns a pair consisting of an index to the registered transit callback 5053 and a bool denoting whether the dimension has been created. 5054 It is false if a dimension with the same name has already been created 5055 (and doesn't create the new dimension but still register a new callback). 5056 """ 5057 return _pywrapcp.RoutingModel_AddMatrixDimension(self, values, capacity, fix_start_cumul_to_zero, name) 5058 5059 def GetAllDimensionNames(self): 5060 r"""Outputs the names of all dimensions added to the routing engine.""" 5061 return _pywrapcp.RoutingModel_GetAllDimensionNames(self) 5062 5063 def GetDimensions(self): 5064 r"""Returns all dimensions of the model.""" 5065 return _pywrapcp.RoutingModel_GetDimensions(self) 5066 5067 def GetDimensionsWithSoftOrSpanCosts(self): 5068 r"""Returns dimensions with soft or vehicle span costs.""" 5069 return _pywrapcp.RoutingModel_GetDimensionsWithSoftOrSpanCosts(self) 5070 5071 def GetUnaryDimensions(self): 5072 r"""Returns dimensions for which all transit evaluators are unary.""" 5073 return _pywrapcp.RoutingModel_GetUnaryDimensions(self) 5074 5075 def GetDimensionsWithGlobalCumulOptimizers(self): 5076 r"""Returns the dimensions which have [global|local]_dimension_optimizers_.""" 5077 return _pywrapcp.RoutingModel_GetDimensionsWithGlobalCumulOptimizers(self) 5078 5079 def GetDimensionsWithLocalCumulOptimizers(self): 5080 return _pywrapcp.RoutingModel_GetDimensionsWithLocalCumulOptimizers(self) 5081 5082 def HasGlobalCumulOptimizer(self, dimension): 5083 r"""Returns whether the given dimension has global/local cumul optimizers.""" 5084 return _pywrapcp.RoutingModel_HasGlobalCumulOptimizer(self, dimension) 5085 5086 def HasLocalCumulOptimizer(self, dimension): 5087 return _pywrapcp.RoutingModel_HasLocalCumulOptimizer(self, dimension) 5088 5089 def GetMutableGlobalCumulLPOptimizer(self, dimension): 5090 r""" 5091 Returns the global/local dimension cumul optimizer for a given dimension, 5092 or nullptr if there is none. 5093 """ 5094 return _pywrapcp.RoutingModel_GetMutableGlobalCumulLPOptimizer(self, dimension) 5095 5096 def GetMutableGlobalCumulMPOptimizer(self, dimension): 5097 return _pywrapcp.RoutingModel_GetMutableGlobalCumulMPOptimizer(self, dimension) 5098 5099 def GetMutableLocalCumulLPOptimizer(self, dimension): 5100 return _pywrapcp.RoutingModel_GetMutableLocalCumulLPOptimizer(self, dimension) 5101 5102 def GetMutableLocalCumulMPOptimizer(self, dimension): 5103 return _pywrapcp.RoutingModel_GetMutableLocalCumulMPOptimizer(self, dimension) 5104 5105 def HasDimension(self, dimension_name): 5106 r"""Returns true if a dimension exists for a given dimension name.""" 5107 return _pywrapcp.RoutingModel_HasDimension(self, dimension_name) 5108 5109 def GetDimensionOrDie(self, dimension_name): 5110 r"""Returns a dimension from its name. Dies if the dimension does not exist.""" 5111 return _pywrapcp.RoutingModel_GetDimensionOrDie(self, dimension_name) 5112 5113 def GetMutableDimension(self, dimension_name): 5114 r""" 5115 Returns a dimension from its name. Returns nullptr if the dimension does 5116 not exist. 5117 """ 5118 return _pywrapcp.RoutingModel_GetMutableDimension(self, dimension_name) 5119 5120 def SetPrimaryConstrainedDimension(self, dimension_name): 5121 r""" 5122 Set the given dimension as "primary constrained". As of August 2013, this 5123 is only used by ArcIsMoreConstrainedThanArc(). 5124 "dimension" must be the name of an existing dimension, or be empty, in 5125 which case there will not be a primary dimension after this call. 5126 """ 5127 return _pywrapcp.RoutingModel_SetPrimaryConstrainedDimension(self, dimension_name) 5128 5129 def GetPrimaryConstrainedDimension(self): 5130 r"""Get the primary constrained dimension, or an empty string if it is unset.""" 5131 return _pywrapcp.RoutingModel_GetPrimaryConstrainedDimension(self) 5132 5133 def GetResourceGroup(self, rg_index): 5134 return _pywrapcp.RoutingModel_GetResourceGroup(self, rg_index) 5135 5136 def GetDimensionResourceGroupIndices(self, dimension): 5137 r""" 5138 Returns the indices of resource groups for this dimension. This method can 5139 only be called after the model has been closed. 5140 """ 5141 return _pywrapcp.RoutingModel_GetDimensionResourceGroupIndices(self, dimension) 5142 5143 def GetDimensionResourceGroupIndex(self, dimension): 5144 r""" 5145 Returns the index of the resource group attached to the dimension. 5146 DCHECKS that there's exactly one resource group for this dimension. 5147 """ 5148 return _pywrapcp.RoutingModel_GetDimensionResourceGroupIndex(self, dimension) 5149 PENALIZE_ONCE = _pywrapcp.RoutingModel_PENALIZE_ONCE 5150 PENALIZE_PER_INACTIVE = _pywrapcp.RoutingModel_PENALIZE_PER_INACTIVE 5151 5152 def AddDisjunction(self, *args): 5153 r""" 5154 Adds a disjunction constraint on the indices. 5155 Exactly 'max_cardinality' of the indices are active. 5156 5157 If a penalty is given, at most 'max_cardinality' of the indices can be 5158 active, and if less are active, 'penalty' is payed per inactive index if 5159 the penalty cost is set to `PENALIZE_PER_INACTIVE`. 5160 This is equivalent to adding the constraint: 5161 p + Sum(i)active[i] == max_cardinality 5162 where p is an integer variable. 5163 If the penalty cost is set to `PENALIZE_ONCE`, then 'penalty' is payed 5164 once if there are less than `max_cardinality` of the indices active. 5165 This is equivalent to adding the constraint: 5166 p == (Sum(i)active[i] != max_cardinality) 5167 where p is a boolean variable. 5168 The following cost is added to the cost function: p * penalty. 5169 :type penalty: int, in, optional 5170 :param penalty: must be positive to make the disjunction optional; a 5171 negative penalty will force 'max_cardinality' indices of the disjunction 5172 to be performed, and therefore p == 0. 5173 Note: passing a vector with a single index will model an optional index 5174 with a penalty cost if it is not visited. 5175 Warning: Start and end indices of any vehicle cannot be part of a 5176 disjunction. 5177 """ 5178 return _pywrapcp.RoutingModel_AddDisjunction(self, *args) 5179 5180 def GetDisjunctionIndices(self, index): 5181 r"""Returns the indices of the disjunctions to which an index belongs.""" 5182 return _pywrapcp.RoutingModel_GetDisjunctionIndices(self, index) 5183 5184 def GetDisjunctionPenalty(self, index): 5185 r"""Returns the penalty of the node disjunction of index 'index'.""" 5186 return _pywrapcp.RoutingModel_GetDisjunctionPenalty(self, index) 5187 5188 def GetDisjunctionMaxCardinality(self, index): 5189 r""" 5190 Returns the maximum number of possible active nodes of the node 5191 disjunction of index 'index'. 5192 """ 5193 return _pywrapcp.RoutingModel_GetDisjunctionMaxCardinality(self, index) 5194 5195 def GetDisjunctionPenaltyCostBehavior(self, index): 5196 r""" 5197 Returns the 'PenaltyCostBehavior' used by the disjunction of index 5198 'index'. 5199 """ 5200 return _pywrapcp.RoutingModel_GetDisjunctionPenaltyCostBehavior(self, index) 5201 5202 def GetNumberOfDisjunctions(self): 5203 r"""Returns the number of node disjunctions in the model.""" 5204 return _pywrapcp.RoutingModel_GetNumberOfDisjunctions(self) 5205 5206 def HasMandatoryDisjunctions(self): 5207 r""" 5208 Returns true if the model contains mandatory disjunctions (ones with 5209 kNoPenalty as penalty). 5210 """ 5211 return _pywrapcp.RoutingModel_HasMandatoryDisjunctions(self) 5212 5213 def HasMaxCardinalityConstrainedDisjunctions(self): 5214 r""" 5215 Returns true if the model contains at least one disjunction which is 5216 constrained by its max_cardinality. 5217 """ 5218 return _pywrapcp.RoutingModel_HasMaxCardinalityConstrainedDisjunctions(self) 5219 5220 def GetPerfectBinaryDisjunctions(self): 5221 r""" 5222 Returns the list of all perfect binary disjunctions, as pairs of variable 5223 indices: a disjunction is "perfect" when its variables do not appear in 5224 any other disjunction. Each pair is sorted (lowest variable index first), 5225 and the output vector is also sorted (lowest pairs first). 5226 """ 5227 return _pywrapcp.RoutingModel_GetPerfectBinaryDisjunctions(self) 5228 5229 def IgnoreDisjunctionsAlreadyForcedToZero(self): 5230 r""" 5231 SPECIAL: Makes the solver ignore all the disjunctions whose active 5232 variables are all trivially zero (i.e. Max() == 0), by setting their 5233 max_cardinality to 0. 5234 This can be useful when using the BaseBinaryDisjunctionNeighborhood 5235 operators, in the context of arc-based routing. 5236 """ 5237 return _pywrapcp.RoutingModel_IgnoreDisjunctionsAlreadyForcedToZero(self) 5238 5239 def AddSoftSameVehicleConstraint(self, indices, cost): 5240 r""" 5241 Adds a soft constraint to force a set of variable indices to be on the 5242 same vehicle. If all nodes are not on the same vehicle, each extra vehicle 5243 used adds 'cost' to the cost function. 5244 TODO(user): Extend this to allow nodes/indices to be on the same given 5245 set of vehicle. 5246 """ 5247 return _pywrapcp.RoutingModel_AddSoftSameVehicleConstraint(self, indices, cost) 5248 5249 def GetNumberOfSoftSameVehicleConstraints(self): 5250 r"""Returns the number of soft same vehicle constraints in the model.""" 5251 return _pywrapcp.RoutingModel_GetNumberOfSoftSameVehicleConstraints(self) 5252 5253 def GetSoftSameVehicleIndices(self, index): 5254 r""" 5255 Returns the indices of the nodes in the soft same vehicle constraint of 5256 index 'index'. 5257 """ 5258 return _pywrapcp.RoutingModel_GetSoftSameVehicleIndices(self, index) 5259 5260 def GetSoftSameVehicleCost(self, index): 5261 r"""Returns the cost of the soft same vehicle constraint of index 'index'.""" 5262 return _pywrapcp.RoutingModel_GetSoftSameVehicleCost(self, index) 5263 5264 def SetAllowedVehiclesForIndex(self, vehicles, index): 5265 r""" 5266 Sets the vehicles which can visit a given node. If the node is in a 5267 disjunction, this will not prevent it from being unperformed. 5268 Specifying an empty vector of vehicles has no effect (all vehicles 5269 will be allowed to visit the node). 5270 """ 5271 return _pywrapcp.RoutingModel_SetAllowedVehiclesForIndex(self, vehicles, index) 5272 5273 def IsVehicleAllowedForIndex(self, vehicle, index): 5274 r"""Returns true if a vehicle is allowed to visit a given node.""" 5275 return _pywrapcp.RoutingModel_IsVehicleAllowedForIndex(self, vehicle, index) 5276 5277 def AddPickupAndDelivery(self, pickup, delivery): 5278 r""" 5279 Notifies that index1 and index2 form a pair of nodes which should belong 5280 to the same route. This methods helps the search find better solutions, 5281 especially in the local search phase. 5282 It should be called each time you have an equality constraint linking 5283 the vehicle variables of two node (including for instance pickup and 5284 delivery problems): 5285 Solver* const solver = routing.solver(); 5286 int64_t index1 = manager.NodeToIndex(node1); 5287 int64_t index2 = manager.NodeToIndex(node2); 5288 solver->AddConstraint(solver->MakeEquality( 5289 routing.VehicleVar(index1), 5290 routing.VehicleVar(index2))); 5291 routing.AddPickupAndDelivery(index1, index2); 5292 """ 5293 return _pywrapcp.RoutingModel_AddPickupAndDelivery(self, pickup, delivery) 5294 5295 def AddPickupAndDeliverySets(self, pickup_disjunction, delivery_disjunction): 5296 r""" 5297 Same as AddPickupAndDelivery but notifying that the performed node from 5298 the disjunction of index 'pickup_disjunction' is on the same route as the 5299 performed node from the disjunction of index 'delivery_disjunction'. 5300 """ 5301 return _pywrapcp.RoutingModel_AddPickupAndDeliverySets(self, pickup_disjunction, delivery_disjunction) 5302 5303 def GetPickupPosition(self, node_index): 5304 r"""Returns the pickup and delivery positions where the node is a pickup.""" 5305 return _pywrapcp.RoutingModel_GetPickupPosition(self, node_index) 5306 5307 def GetDeliveryPosition(self, node_index): 5308 r"""Returns the pickup and delivery positions where the node is a delivery.""" 5309 return _pywrapcp.RoutingModel_GetDeliveryPosition(self, node_index) 5310 5311 def IsPickup(self, node_index): 5312 r"""Returns whether the node is a pickup (resp. delivery).""" 5313 return _pywrapcp.RoutingModel_IsPickup(self, node_index) 5314 5315 def IsDelivery(self, node_index): 5316 return _pywrapcp.RoutingModel_IsDelivery(self, node_index) 5317 5318 def SetPickupAndDeliveryPolicyOfAllVehicles(self, policy): 5319 r""" 5320 Sets the Pickup and delivery policy of all vehicles. It is equivalent to 5321 calling SetPickupAndDeliveryPolicyOfVehicle on all vehicles. 5322 """ 5323 return _pywrapcp.RoutingModel_SetPickupAndDeliveryPolicyOfAllVehicles(self, policy) 5324 5325 def SetPickupAndDeliveryPolicyOfVehicle(self, policy, vehicle): 5326 return _pywrapcp.RoutingModel_SetPickupAndDeliveryPolicyOfVehicle(self, policy, vehicle) 5327 5328 def GetPickupAndDeliveryPolicyOfVehicle(self, vehicle): 5329 return _pywrapcp.RoutingModel_GetPickupAndDeliveryPolicyOfVehicle(self, vehicle) 5330 5331 def GetNumOfSingletonNodes(self): 5332 r""" 5333 Returns the number of non-start/end nodes which do not appear in a 5334 pickup/delivery pair. 5335 """ 5336 return _pywrapcp.RoutingModel_GetNumOfSingletonNodes(self) 5337 5338 def GetFirstMatchingPickupDeliverySibling(self, node, is_match): 5339 return _pywrapcp.RoutingModel_GetFirstMatchingPickupDeliverySibling(self, node, is_match) 5340 TYPE_ADDED_TO_VEHICLE = _pywrapcp.RoutingModel_TYPE_ADDED_TO_VEHICLE 5341 r"""When visited, the number of types 'T' on the vehicle increases by one.""" 5342 ADDED_TYPE_REMOVED_FROM_VEHICLE = _pywrapcp.RoutingModel_ADDED_TYPE_REMOVED_FROM_VEHICLE 5343 r""" 5344 When visited, one instance of type 'T' previously added to the route 5345 (TYPE_ADDED_TO_VEHICLE), if any, is removed from the vehicle. 5346 If the type was not previously added to the route or all added instances 5347 have already been removed, this visit has no effect on the types. 5348 """ 5349 TYPE_ON_VEHICLE_UP_TO_VISIT = _pywrapcp.RoutingModel_TYPE_ON_VEHICLE_UP_TO_VISIT 5350 r""" 5351 With the following policy, the visit enforces that type 'T' is 5352 considered on the route from its start until this node is visited. 5353 """ 5354 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED = _pywrapcp.RoutingModel_TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED 5355 r""" 5356 The visit doesn't have an impact on the number of types 'T' on the 5357 route, as it's (virtually) added and removed directly. 5358 This policy can be used for visits which are part of an incompatibility 5359 or requirement set without affecting the type count on the route. 5360 """ 5361 5362 def SetVisitType(self, index, type, type_policy): 5363 return _pywrapcp.RoutingModel_SetVisitType(self, index, type, type_policy) 5364 5365 def GetVisitType(self, index): 5366 return _pywrapcp.RoutingModel_GetVisitType(self, index) 5367 5368 def GetSingleNodesOfType(self, type): 5369 return _pywrapcp.RoutingModel_GetSingleNodesOfType(self, type) 5370 5371 def GetPairIndicesOfType(self, type): 5372 return _pywrapcp.RoutingModel_GetPairIndicesOfType(self, type) 5373 5374 def GetVisitTypePolicy(self, index): 5375 return _pywrapcp.RoutingModel_GetVisitTypePolicy(self, index) 5376 5377 def GetNumberOfVisitTypes(self): 5378 return _pywrapcp.RoutingModel_GetNumberOfVisitTypes(self) 5379 5380 def AddHardTypeIncompatibility(self, type1, type2): 5381 r""" 5382 Incompatibilities: 5383 Two nodes with "hard" incompatible types cannot share the same route at 5384 all, while with a "temporal" incompatibility they can't be on the same 5385 route at the same time. 5386 NOTE: To avoid unnecessary memory reallocations, it is recommended to only 5387 add incompatibilities once all the existing types have been set with 5388 SetVisitType(). 5389 """ 5390 return _pywrapcp.RoutingModel_AddHardTypeIncompatibility(self, type1, type2) 5391 5392 def AddTemporalTypeIncompatibility(self, type1, type2): 5393 return _pywrapcp.RoutingModel_AddTemporalTypeIncompatibility(self, type1, type2) 5394 5395 def GetHardTypeIncompatibilitiesOfType(self, type): 5396 r"""Returns visit types incompatible with a given type.""" 5397 return _pywrapcp.RoutingModel_GetHardTypeIncompatibilitiesOfType(self, type) 5398 5399 def GetTemporalTypeIncompatibilitiesOfType(self, type): 5400 return _pywrapcp.RoutingModel_GetTemporalTypeIncompatibilitiesOfType(self, type) 5401 5402 def HasHardTypeIncompatibilities(self): 5403 r""" 5404 Returns true iff any hard (resp. temporal) type incompatibilities have 5405 been added to the model. 5406 """ 5407 return _pywrapcp.RoutingModel_HasHardTypeIncompatibilities(self) 5408 5409 def HasTemporalTypeIncompatibilities(self): 5410 return _pywrapcp.RoutingModel_HasTemporalTypeIncompatibilities(self) 5411 5412 def AddSameVehicleRequiredTypeAlternatives(self, dependent_type, required_type_alternatives): 5413 r""" 5414 Requirements: 5415 NOTE: As of 2019-04, cycles in the requirement graph are not supported, 5416 and lead to the dependent nodes being skipped if possible (otherwise 5417 the model is considered infeasible). 5418 The following functions specify that "dependent_type" requires at least 5419 one of the types in "required_type_alternatives". 5420 5421 For same-vehicle requirements, a node of dependent type type_D requires at 5422 least one node of type type_R among the required alternatives on the same 5423 route. 5424 NOTE: To avoid unnecessary memory reallocations, it is recommended to only 5425 add requirements once all the existing types have been set with 5426 SetVisitType(). 5427 """ 5428 return _pywrapcp.RoutingModel_AddSameVehicleRequiredTypeAlternatives(self, dependent_type, required_type_alternatives) 5429 5430 def AddRequiredTypeAlternativesWhenAddingType(self, dependent_type, required_type_alternatives): 5431 r""" 5432 If type_D depends on type_R when adding type_D, any node_D of type_D and 5433 VisitTypePolicy TYPE_ADDED_TO_VEHICLE or 5434 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED requires at least one type_R on its 5435 vehicle at the time node_D is visited. 5436 """ 5437 return _pywrapcp.RoutingModel_AddRequiredTypeAlternativesWhenAddingType(self, dependent_type, required_type_alternatives) 5438 5439 def AddRequiredTypeAlternativesWhenRemovingType(self, dependent_type, required_type_alternatives): 5440 r""" 5441 The following requirements apply when visiting dependent nodes that remove 5442 their type from the route, i.e. type_R must be on the vehicle when type_D 5443 of VisitTypePolicy ADDED_TYPE_REMOVED_FROM_VEHICLE, 5444 TYPE_ON_VEHICLE_UP_TO_VISIT or TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED is 5445 visited. 5446 """ 5447 return _pywrapcp.RoutingModel_AddRequiredTypeAlternativesWhenRemovingType(self, dependent_type, required_type_alternatives) 5448 5449 def GetSameVehicleRequiredTypeAlternativesOfType(self, type): 5450 r""" 5451 Returns the set of same-vehicle requirement alternatives for the given 5452 type. 5453 """ 5454 return _pywrapcp.RoutingModel_GetSameVehicleRequiredTypeAlternativesOfType(self, type) 5455 5456 def GetRequiredTypeAlternativesWhenAddingType(self, type): 5457 r"""Returns the set of requirement alternatives when adding the given type.""" 5458 return _pywrapcp.RoutingModel_GetRequiredTypeAlternativesWhenAddingType(self, type) 5459 5460 def GetRequiredTypeAlternativesWhenRemovingType(self, type): 5461 r"""Returns the set of requirement alternatives when removing the given type.""" 5462 return _pywrapcp.RoutingModel_GetRequiredTypeAlternativesWhenRemovingType(self, type) 5463 5464 def HasSameVehicleTypeRequirements(self): 5465 r""" 5466 Returns true iff any same-route (resp. temporal) type requirements have 5467 been added to the model. 5468 """ 5469 return _pywrapcp.RoutingModel_HasSameVehicleTypeRequirements(self) 5470 5471 def HasTemporalTypeRequirements(self): 5472 return _pywrapcp.RoutingModel_HasTemporalTypeRequirements(self) 5473 5474 def HasTypeRegulations(self): 5475 r""" 5476 Returns true iff the model has any incompatibilities or requirements set 5477 on node types. 5478 """ 5479 return _pywrapcp.RoutingModel_HasTypeRegulations(self) 5480 5481 def UnperformedPenalty(self, var_index): 5482 r""" 5483 Get the "unperformed" penalty of a node. This is only well defined if the 5484 node is only part of a single Disjunction, and that disjunction has a 5485 penalty. For forced active nodes returns max int64_t. In all other cases, 5486 this returns 0. 5487 """ 5488 return _pywrapcp.RoutingModel_UnperformedPenalty(self, var_index) 5489 5490 def UnperformedPenaltyOrValue(self, default_value, var_index): 5491 r""" 5492 Same as above except that it returns default_value instead of 0 when 5493 penalty is not well defined (default value is passed as first argument to 5494 simplify the usage of the method in a callback). 5495 """ 5496 return _pywrapcp.RoutingModel_UnperformedPenaltyOrValue(self, default_value, var_index) 5497 5498 def GetDepot(self): 5499 r""" 5500 Returns the variable index of the first starting or ending node of all 5501 routes. If all routes start and end at the same node (single depot), this 5502 is the node returned. 5503 """ 5504 return _pywrapcp.RoutingModel_GetDepot(self) 5505 5506 def SetMaximumNumberOfActiveVehicles(self, max_active_vehicles): 5507 r""" 5508 Constrains the maximum number of active vehicles, aka the number of 5509 vehicles which do not have an empty route. For instance, this can be used 5510 to limit the number of routes in the case where there are fewer drivers 5511 than vehicles and that the fleet of vehicle is heterogeneous. 5512 """ 5513 return _pywrapcp.RoutingModel_SetMaximumNumberOfActiveVehicles(self, max_active_vehicles) 5514 5515 def GetMaximumNumberOfActiveVehicles(self): 5516 r"""Returns the maximum number of active vehicles.""" 5517 return _pywrapcp.RoutingModel_GetMaximumNumberOfActiveVehicles(self) 5518 5519 def SetArcCostEvaluatorOfAllVehicles(self, evaluator_index): 5520 r""" 5521 Sets the cost function of the model such that the cost of a segment of a 5522 route between node 'from' and 'to' is evaluator(from, to), whatever the 5523 route or vehicle performing the route. 5524 """ 5525 return _pywrapcp.RoutingModel_SetArcCostEvaluatorOfAllVehicles(self, evaluator_index) 5526 5527 def SetArcCostEvaluatorOfVehicle(self, evaluator_index, vehicle): 5528 r"""Sets the cost function for a given vehicle route.""" 5529 return _pywrapcp.RoutingModel_SetArcCostEvaluatorOfVehicle(self, evaluator_index, vehicle) 5530 5531 def SetFixedCostOfAllVehicles(self, cost): 5532 r""" 5533 Sets the fixed cost of all vehicle routes. It is equivalent to calling 5534 SetFixedCostOfVehicle on all vehicle routes. 5535 """ 5536 return _pywrapcp.RoutingModel_SetFixedCostOfAllVehicles(self, cost) 5537 5538 def SetFixedCostOfVehicle(self, cost, vehicle): 5539 r"""Sets the fixed cost of one vehicle route.""" 5540 return _pywrapcp.RoutingModel_SetFixedCostOfVehicle(self, cost, vehicle) 5541 5542 def GetFixedCostOfVehicle(self, vehicle): 5543 r""" 5544 Returns the route fixed cost taken into account if the route of the 5545 vehicle is not empty, aka there's at least one node on the route other 5546 than the first and last nodes. 5547 """ 5548 return _pywrapcp.RoutingModel_GetFixedCostOfVehicle(self, vehicle) 5549 5550 def SetPathEnergyCostOfVehicle(self, force, distance, cost_per_unit, vehicle): 5551 return _pywrapcp.RoutingModel_SetPathEnergyCostOfVehicle(self, force, distance, cost_per_unit, vehicle) 5552 5553 def SetPathEnergyCostsOfVehicle(self, force, distance, threshold, cost_per_unit_below_threshold, cost_per_unit_above_threshold, vehicle): 5554 return _pywrapcp.RoutingModel_SetPathEnergyCostsOfVehicle(self, force, distance, threshold, cost_per_unit_below_threshold, cost_per_unit_above_threshold, vehicle) 5555 5556 def SetAmortizedCostFactorsOfAllVehicles(self, linear_cost_factor, quadratic_cost_factor): 5557 r""" 5558 The following methods set the linear and quadratic cost factors of 5559 vehicles (must be positive values). The default value of these parameters 5560 is zero for all vehicles. 5561 5562 When set, the cost_ of the model will contain terms aiming at reducing the 5563 number of vehicles used in the model, by adding the following to the 5564 objective for every vehicle v: 5565 INDICATOR(v used in the model) * 5566 [linear_cost_factor_of_vehicle_[v] 5567 - quadratic_cost_factor_of_vehicle_[v]*(square of length of route v)] 5568 i.e. for every used vehicle, we add the linear factor as fixed cost, and 5569 subtract the square of the route length multiplied by the quadratic 5570 factor. This second term aims at making the routes as dense as possible. 5571 5572 Sets the linear and quadratic cost factor of all vehicles. 5573 """ 5574 return _pywrapcp.RoutingModel_SetAmortizedCostFactorsOfAllVehicles(self, linear_cost_factor, quadratic_cost_factor) 5575 5576 def SetAmortizedCostFactorsOfVehicle(self, linear_cost_factor, quadratic_cost_factor, vehicle): 5577 r"""Sets the linear and quadratic cost factor of the given vehicle.""" 5578 return _pywrapcp.RoutingModel_SetAmortizedCostFactorsOfVehicle(self, linear_cost_factor, quadratic_cost_factor, vehicle) 5579 5580 def GetAmortizedLinearCostFactorOfVehicles(self): 5581 return _pywrapcp.RoutingModel_GetAmortizedLinearCostFactorOfVehicles(self) 5582 5583 def GetAmortizedQuadraticCostFactorOfVehicles(self): 5584 return _pywrapcp.RoutingModel_GetAmortizedQuadraticCostFactorOfVehicles(self) 5585 5586 def GetRouteCost(self, route): 5587 return _pywrapcp.RoutingModel_GetRouteCost(self, route) 5588 5589 def SetVehicleUsedWhenEmpty(self, is_used, vehicle): 5590 return _pywrapcp.RoutingModel_SetVehicleUsedWhenEmpty(self, is_used, vehicle) 5591 5592 def IsVehicleUsedWhenEmpty(self, vehicle): 5593 return _pywrapcp.RoutingModel_IsVehicleUsedWhenEmpty(self, vehicle) 5594 5595 def SetFirstSolutionEvaluator(self, evaluator): 5596 r""" 5597 Gets/sets the evaluator used during the search. Only relevant when 5598 RoutingSearchParameters.first_solution_strategy = EVALUATOR_STRATEGY. 5599 Takes ownership of evaluator. 5600 """ 5601 return _pywrapcp.RoutingModel_SetFirstSolutionEvaluator(self, evaluator) 5602 5603 def SetFirstSolutionHint(self, hint): 5604 r""" 5605 Adds a hint to be used by first solution strategies. The hint assignment 5606 must outlive the search. 5607 As of 2024-12, only used by LOCAL_CHEAPEST_INSERTION and 5608 LOCAL_CHEAPEST_COST_INSERTION. 5609 """ 5610 return _pywrapcp.RoutingModel_SetFirstSolutionHint(self, hint) 5611 5612 def GetFirstSolutionHint(self): 5613 r"""Returns the current hint assignment.""" 5614 return _pywrapcp.RoutingModel_GetFirstSolutionHint(self) 5615 5616 def AddLocalSearchOperator(self, ls_operator): 5617 r""" 5618 Adds a local search operator to the set of operators used to solve the 5619 vehicle routing problem. 5620 """ 5621 return _pywrapcp.RoutingModel_AddLocalSearchOperator(self, ls_operator) 5622 5623 def AddSearchMonitor(self, monitor): 5624 r"""Adds a search monitor to the search used to solve the routing model.""" 5625 return _pywrapcp.RoutingModel_AddSearchMonitor(self, monitor) 5626 5627 def AddEnterSearchCallback(self, callback): 5628 return _pywrapcp.RoutingModel_AddEnterSearchCallback(self, callback) 5629 5630 def AddAtSolutionCallback(self, callback, track_unchecked_neighbors=False): 5631 r""" 5632 Adds a callback called each time a solution is found during the search. 5633 This is a shortcut to creating a monitor to call the callback on 5634 AtSolution() and adding it with AddSearchMonitor. 5635 If track_unchecked_neighbors is true, the callback will also be called on 5636 AcceptUncheckedNeighbor() events, which is useful to grab solutions 5637 obtained when solver_parameters.check_solution_period > 1 (aka fastLS). 5638 """ 5639 return _pywrapcp.RoutingModel_AddAtSolutionCallback(self, callback, track_unchecked_neighbors) 5640 5641 def AddRestoreDimensionValuesResetCallback(self, callback): 5642 return _pywrapcp.RoutingModel_AddRestoreDimensionValuesResetCallback(self, callback) 5643 5644 def AddVariableMinimizedByFinalizer(self, var): 5645 r""" 5646 Adds a variable to minimize in the solution finalizer. The solution 5647 finalizer is called each time a solution is found during the search and 5648 allows to instantiate secondary variables (such as dimension cumul 5649 variables). 5650 """ 5651 return _pywrapcp.RoutingModel_AddVariableMinimizedByFinalizer(self, var) 5652 5653 def AddVariableMaximizedByFinalizer(self, var): 5654 r""" 5655 Adds a variable to maximize in the solution finalizer (see above for 5656 information on the solution finalizer). 5657 """ 5658 return _pywrapcp.RoutingModel_AddVariableMaximizedByFinalizer(self, var) 5659 5660 def AddWeightedVariableMinimizedByFinalizer(self, var, cost): 5661 r""" 5662 Adds a variable to minimize in the solution finalizer, with a weighted 5663 priority: the higher the more priority it has. 5664 """ 5665 return _pywrapcp.RoutingModel_AddWeightedVariableMinimizedByFinalizer(self, var, cost) 5666 5667 def AddWeightedVariableMaximizedByFinalizer(self, var, cost): 5668 r""" 5669 Adds a variable to maximize in the solution finalizer, with a weighted 5670 priority: the higher the more priority it has. 5671 """ 5672 return _pywrapcp.RoutingModel_AddWeightedVariableMaximizedByFinalizer(self, var, cost) 5673 5674 def AddVariableTargetToFinalizer(self, var, target): 5675 r""" 5676 Add a variable to set the closest possible to the target value in the 5677 solution finalizer. 5678 """ 5679 return _pywrapcp.RoutingModel_AddVariableTargetToFinalizer(self, var, target) 5680 5681 def AddWeightedVariableTargetToFinalizer(self, var, target, cost): 5682 r""" 5683 Same as above with a weighted priority: the higher the cost, the more 5684 priority it has to be set close to the target value. 5685 """ 5686 return _pywrapcp.RoutingModel_AddWeightedVariableTargetToFinalizer(self, var, target, cost) 5687 5688 def CloseModel(self): 5689 r""" 5690 Closes the current routing model; after this method is called, no 5691 modification to the model can be done, but RoutesToAssignment becomes 5692 available. Note that CloseModel() is automatically called by Solve() and 5693 other methods that produce solution. 5694 This is equivalent to calling 5695 CloseModelWithParameters(DefaultRoutingSearchParameters()). 5696 """ 5697 return _pywrapcp.RoutingModel_CloseModel(self) 5698 5699 def CloseModelWithParameters(self, search_parameters): 5700 r""" 5701 Same as above taking search parameters (as of 10/2015 some the parameters 5702 have to be set when closing the model). 5703 """ 5704 return _pywrapcp.RoutingModel_CloseModelWithParameters(self, search_parameters) 5705 5706 def Solve(self, assignment=None): 5707 r""" 5708 Solves the current routing model; closes the current model. 5709 This is equivalent to calling 5710 SolveWithParameters(DefaultRoutingSearchParameters()) 5711 or 5712 SolveFromAssignmentWithParameters(assignment, 5713 DefaultRoutingSearchParameters()). 5714 """ 5715 return _pywrapcp.RoutingModel_Solve(self, assignment) 5716 5717 def SolveWithParameters(self, search_parameters, solutions=None): 5718 r""" 5719 Solves the current routing model with the given parameters. If 'solutions' 5720 is specified, it will contain the k best solutions found during the search 5721 (from worst to best, including the one returned by this method), where k 5722 corresponds to the 'number_of_solutions_to_collect' in 5723 'search_parameters'. Note that the Assignment returned by the method and 5724 the ones in solutions are owned by the underlying solver and should not be 5725 deleted. 5726 """ 5727 return _pywrapcp.RoutingModel_SolveWithParameters(self, search_parameters, solutions) 5728 5729 def SolveFromAssignmentWithParameters(self, assignment, search_parameters, solutions=None): 5730 r""" 5731 Same as above, except that if assignment is not null, it will be used as 5732 the initial solution. 5733 """ 5734 return _pywrapcp.RoutingModel_SolveFromAssignmentWithParameters(self, assignment, search_parameters, solutions) 5735 5736 def FastSolveFromAssignmentWithParameters(self, assignment, search_parameters, check_solution_in_cp, touched=None): 5737 r""" 5738 Improves a given assignment using unchecked local search. 5739 If check_solution_in_cp is true the final solution will be checked with 5740 the CP solver. 5741 As of 11/2023, only works with greedy descent. 5742 """ 5743 return _pywrapcp.RoutingModel_FastSolveFromAssignmentWithParameters(self, assignment, search_parameters, check_solution_in_cp, touched) 5744 5745 def SolveFromAssignmentsWithParameters(self, assignments, search_parameters, solutions=None): 5746 r""" 5747 Same as above but will try all assignments in order as first solutions 5748 until one succeeds. 5749 """ 5750 return _pywrapcp.RoutingModel_SolveFromAssignmentsWithParameters(self, assignments, search_parameters, solutions) 5751 5752 def SolveWithIteratedLocalSearch(self, search_parameters): 5753 r""" 5754 Solves the current routing model by using an Iterated Local Search 5755 approach. 5756 """ 5757 return _pywrapcp.RoutingModel_SolveWithIteratedLocalSearch(self, search_parameters) 5758 5759 def SetAssignmentFromOtherModelAssignment(self, target_assignment, source_model, source_assignment): 5760 r""" 5761 Given a "source_model" and its "source_assignment", resets 5762 "target_assignment" with the IntVar variables (nexts_, and vehicle_vars_ 5763 if costs aren't homogeneous across vehicles) of "this" model, with the 5764 values set according to those in "other_assignment". 5765 The objective_element of target_assignment is set to this->cost_. 5766 """ 5767 return _pywrapcp.RoutingModel_SetAssignmentFromOtherModelAssignment(self, target_assignment, source_model, source_assignment) 5768 5769 def GetSubSolverStatistics(self): 5770 r"""Returns detailed search statistics.""" 5771 return _pywrapcp.RoutingModel_GetSubSolverStatistics(self) 5772 5773 def ComputeLowerBound(self): 5774 r""" 5775 Computes a lower bound to the routing problem solving a linear assignment 5776 problem. The routing model must be closed before calling this method. 5777 Note that problems with node disjunction constraints (including optional 5778 nodes) and non-homogenous costs are not supported (the method returns 0 in 5779 these cases). 5780 """ 5781 return _pywrapcp.RoutingModel_ComputeLowerBound(self) 5782 5783 def objective_lower_bound(self): 5784 r""" 5785 Returns the current lower bound found by internal solvers during the 5786 search. 5787 """ 5788 return _pywrapcp.RoutingModel_objective_lower_bound(self) 5789 5790 def status(self): 5791 r"""Returns the current status of the routing model.""" 5792 return _pywrapcp.RoutingModel_status(self) 5793 5794 def search_stats(self): 5795 r"""Returns search statistics.""" 5796 return _pywrapcp.RoutingModel_search_stats(self) 5797 5798 def enable_deep_serialization(self): 5799 r"""Returns the value of the internal enable_deep_serialization_ parameter.""" 5800 return _pywrapcp.RoutingModel_enable_deep_serialization(self) 5801 5802 def ApplyLocks(self, locks): 5803 r""" 5804 Applies a lock chain to the next search. 'locks' represents an ordered 5805 vector of nodes representing a partial route which will be fixed during 5806 the next search; it will constrain next variables such that: 5807 next[locks[i]] == locks[i+1]. 5808 5809 Returns the next variable at the end of the locked chain; this variable is 5810 not locked. An assignment containing the locks can be obtained by calling 5811 PreAssignment(). 5812 """ 5813 return _pywrapcp.RoutingModel_ApplyLocks(self, locks) 5814 5815 def ApplyLocksToAllVehicles(self, locks, close_routes): 5816 r""" 5817 Applies lock chains to all vehicles to the next search, such that locks[p] 5818 is the lock chain for route p. Returns false if the locks do not contain 5819 valid routes; expects that the routes do not contain the depots, 5820 i.e. there are empty vectors in place of empty routes. 5821 If close_routes is set to true, adds the end nodes to the route of each 5822 vehicle and deactivates other nodes. 5823 An assignment containing the locks can be obtained by calling 5824 PreAssignment(). 5825 """ 5826 return _pywrapcp.RoutingModel_ApplyLocksToAllVehicles(self, locks, close_routes) 5827 5828 def PreAssignment(self): 5829 r""" 5830 Returns an assignment used to fix some of the variables of the problem. 5831 In practice, this assignment locks partial routes of the problem. This 5832 can be used in the context of locking the parts of the routes which have 5833 already been driven in online routing problems. 5834 """ 5835 return _pywrapcp.RoutingModel_PreAssignment(self) 5836 5837 def MutablePreAssignment(self): 5838 return _pywrapcp.RoutingModel_MutablePreAssignment(self) 5839 5840 def WriteAssignment(self, file_name): 5841 r""" 5842 Writes the current solution to a file containing an AssignmentProto. 5843 Returns false if the file cannot be opened or if there is no current 5844 solution. 5845 """ 5846 return _pywrapcp.RoutingModel_WriteAssignment(self, file_name) 5847 5848 def ReadAssignment(self, file_name): 5849 r""" 5850 Reads an assignment from a file and returns the current solution. 5851 Returns nullptr if the file cannot be opened or if the assignment is not 5852 valid. 5853 """ 5854 return _pywrapcp.RoutingModel_ReadAssignment(self, file_name) 5855 5856 def RestoreAssignment(self, solution): 5857 r""" 5858 Restores an assignment as a solution in the routing model and returns the 5859 new solution. Returns nullptr if the assignment is not valid. 5860 """ 5861 return _pywrapcp.RoutingModel_RestoreAssignment(self, solution) 5862 5863 def ReadAssignmentFromRoutes(self, routes, ignore_inactive_indices): 5864 r""" 5865 Restores the routes as the current solution. Returns nullptr if the 5866 solution cannot be restored (routes do not contain a valid solution). Note 5867 that calling this method will run the solver to assign values to the 5868 dimension variables; this may take considerable amount of time, especially 5869 when using dimensions with slack. 5870 """ 5871 return _pywrapcp.RoutingModel_ReadAssignmentFromRoutes(self, routes, ignore_inactive_indices) 5872 5873 def RoutesToAssignment(self, routes, ignore_inactive_indices, close_routes, assignment): 5874 r""" 5875 Fills an assignment from a specification of the routes of the 5876 vehicles. The routes are specified as lists of variable indices that 5877 appear on the routes of the vehicles. The indices of the outer vector in 5878 'routes' correspond to vehicles IDs, the inner vector contains the 5879 variable indices on the routes for the given vehicle. The inner vectors 5880 must not contain the start and end indices, as these are determined by the 5881 routing model. Sets the value of NextVars in the assignment, adding the 5882 variables to the assignment if necessary. The method does not touch other 5883 variables in the assignment. The method can only be called after the model 5884 is closed. With ignore_inactive_indices set to false, this method will 5885 fail (return nullptr) in case some of the route contain indices that are 5886 deactivated in the model; when set to true, these indices will be 5887 skipped. Returns true if routes were successfully 5888 loaded. However, such assignment still might not be a valid 5889 solution to the routing problem due to more complex constraints; 5890 it is advisible to call solver()->CheckSolution() afterwards. 5891 """ 5892 return _pywrapcp.RoutingModel_RoutesToAssignment(self, routes, ignore_inactive_indices, close_routes, assignment) 5893 5894 def AssignmentToRoutes(self, assignment, routes): 5895 r""" 5896 Converts the solution in the given assignment to routes for all vehicles. 5897 Expects that assignment contains a valid solution (i.e. routes for all 5898 vehicles end with an end index for that vehicle). 5899 """ 5900 return _pywrapcp.RoutingModel_AssignmentToRoutes(self, assignment, routes) 5901 5902 def CompactAssignment(self, assignment): 5903 r""" 5904 Converts the solution in the given assignment to routes for all vehicles. 5905 If the returned vector is route_indices, route_indices[i][j] is the index 5906 for jth location visited on route i. Note that contrary to 5907 AssignmentToRoutes, the vectors do include start and end locations. 5908 Returns a compacted version of the given assignment, in which all vehicles 5909 with id lower or equal to some N have non-empty routes, and all vehicles 5910 with id greater than N have empty routes. Does not take ownership of the 5911 returned object. 5912 If found, the cost of the compact assignment is the same as in the 5913 original assignment and it preserves the values of 'active' variables. 5914 Returns nullptr if a compact assignment was not found. 5915 This method only works in homogenous mode, and it only swaps equivalent 5916 vehicles (vehicles with the same start and end nodes). When creating the 5917 compact assignment, the empty plan is replaced by the route assigned to 5918 the compatible vehicle with the highest id. Note that with more complex 5919 constraints on vehicle variables, this method might fail even if a compact 5920 solution exists. 5921 This method changes the vehicle and dimension variables as necessary. 5922 While compacting the solution, only basic checks on vehicle variables are 5923 performed; if one of these checks fails no attempts to repair it are made 5924 (instead, the method returns nullptr). 5925 """ 5926 return _pywrapcp.RoutingModel_CompactAssignment(self, assignment) 5927 5928 def CompactAndCheckAssignment(self, assignment): 5929 r""" 5930 Same as CompactAssignment() but also checks the validity of the final 5931 compact solution; if it is not valid, no attempts to repair it are made 5932 (instead, the method returns nullptr). 5933 """ 5934 return _pywrapcp.RoutingModel_CompactAndCheckAssignment(self, assignment) 5935 5936 def AddToAssignment(self, var): 5937 r"""Adds an extra variable to the vehicle routing assignment.""" 5938 return _pywrapcp.RoutingModel_AddToAssignment(self, var) 5939 5940 def AddIntervalToAssignment(self, interval): 5941 return _pywrapcp.RoutingModel_AddIntervalToAssignment(self, interval) 5942 5943 def PackCumulsOfOptimizerDimensionsFromAssignment(self, original_assignment, duration_limit, time_limit_was_reached=None): 5944 r""" 5945 For every dimension in the model with an optimizer in 5946 local/global_dimension_optimizers_, this method tries to pack the cumul 5947 values of the dimension, such that: 5948 - The cumul costs (span costs, soft lower and upper bound costs, etc) are 5949 minimized. 5950 - The cumuls of the ends of the routes are minimized for this given 5951 minimal cumul cost. 5952 - Given these minimal end cumuls, the route start cumuls are maximized. 5953 Returns the assignment resulting from allocating these packed cumuls with 5954 the solver, and nullptr if these cumuls could not be set by the solver. 5955 """ 5956 return _pywrapcp.RoutingModel_PackCumulsOfOptimizerDimensionsFromAssignment(self, original_assignment, duration_limit, time_limit_was_reached) 5957 5958 def GetOrCreateNodeNeighborsByCostClass(self, *args): 5959 r""" 5960 *Overload 1:* 5961 Returns neighbors of all nodes for every cost class. The result is cached 5962 and is computed once. The number of neighbors considered is based on a 5963 ratio of non-vehicle nodes, specified by neighbors_ratio, with a minimum 5964 of min-neighbors node considered. 5965 5966 | 5967 5968 *Overload 2:* 5969 Returns parameters.num_neighbors neighbors of all nodes for every cost 5970 class. The result is cached and is computed once. 5971 """ 5972 return _pywrapcp.RoutingModel_GetOrCreateNodeNeighborsByCostClass(self, *args) 5973 5974 def AddLocalSearchFilter(self, filter): 5975 r""" 5976 Adds a custom local search filter to the list of filters used to speed up 5977 local search by pruning unfeasible variable assignments. 5978 Calling this method after the routing model has been closed (CloseModel() 5979 or Solve() has been called) has no effect. 5980 The routing model does not take ownership of the filter. 5981 """ 5982 return _pywrapcp.RoutingModel_AddLocalSearchFilter(self, filter) 5983 5984 def Start(self, vehicle): 5985 r""" 5986 Model inspection. 5987 Returns the variable index of the starting node of a vehicle route. 5988 """ 5989 return _pywrapcp.RoutingModel_Start(self, vehicle) 5990 5991 def End(self, vehicle): 5992 r"""Returns the variable index of the ending node of a vehicle route.""" 5993 return _pywrapcp.RoutingModel_End(self, vehicle) 5994 5995 def IsStart(self, index): 5996 r"""Returns true if 'index' represents the first node of a route.""" 5997 return _pywrapcp.RoutingModel_IsStart(self, index) 5998 5999 def IsEnd(self, index): 6000 r"""Returns true if 'index' represents the last node of a route.""" 6001 return _pywrapcp.RoutingModel_IsEnd(self, index) 6002 6003 def VehicleIndex(self, index): 6004 r""" 6005 Returns the vehicle of the given start/end index, and -1 if the given 6006 index is not a vehicle start/end. 6007 """ 6008 return _pywrapcp.RoutingModel_VehicleIndex(self, index) 6009 6010 def Next(self, assignment, index): 6011 r""" 6012 Assignment inspection 6013 Returns the variable index of the node directly after the node 6014 corresponding to 'index' in 'assignment'. 6015 """ 6016 return _pywrapcp.RoutingModel_Next(self, assignment, index) 6017 6018 def IsVehicleUsed(self, assignment, vehicle): 6019 r"""Returns true if the route of 'vehicle' is non empty in 'assignment'.""" 6020 return _pywrapcp.RoutingModel_IsVehicleUsed(self, assignment, vehicle) 6021 6022 def NextVar(self, index): 6023 r""" 6024 Returns the next variable of the node corresponding to index. Note that 6025 NextVar(index) == index is equivalent to ActiveVar(index) == 0. 6026 """ 6027 return _pywrapcp.RoutingModel_NextVar(self, index) 6028 6029 def ActiveVar(self, index): 6030 r"""Returns the active variable of the node corresponding to index.""" 6031 return _pywrapcp.RoutingModel_ActiveVar(self, index) 6032 6033 def ActiveVehicleVar(self, vehicle): 6034 r""" 6035 Returns the active variable of the vehicle. It will be equal to 1 iff the 6036 route of the vehicle is not empty, 0 otherwise. 6037 """ 6038 return _pywrapcp.RoutingModel_ActiveVehicleVar(self, vehicle) 6039 6040 def VehicleRouteConsideredVar(self, vehicle): 6041 r""" 6042 Returns the variable specifying whether or not the given vehicle route is 6043 considered for costs and constraints. It will be equal to 1 iff the route 6044 of the vehicle is not empty OR vehicle_used_when_empty_[vehicle] is true. 6045 """ 6046 return _pywrapcp.RoutingModel_VehicleRouteConsideredVar(self, vehicle) 6047 6048 def VehicleVar(self, index): 6049 r""" 6050 Returns the vehicle variable of the node corresponding to index. Note that 6051 VehicleVar(index) == -1 is equivalent to ActiveVar(index) == 0. 6052 """ 6053 return _pywrapcp.RoutingModel_VehicleVar(self, index) 6054 6055 def ResourceVar(self, vehicle, resource_group): 6056 r""" 6057 Returns the resource variable for the given vehicle index in the given 6058 resource group. If a vehicle doesn't require a resource from the 6059 corresponding resource group, then ResourceVar(v, r_g) == -1. 6060 """ 6061 return _pywrapcp.RoutingModel_ResourceVar(self, vehicle, resource_group) 6062 6063 def CostVar(self): 6064 r"""Returns the global cost variable which is being minimized.""" 6065 return _pywrapcp.RoutingModel_CostVar(self) 6066 6067 def GetArcCostForVehicle(self, from_index, to_index, vehicle): 6068 r""" 6069 Returns the cost of the transit arc between two nodes for a given vehicle. 6070 Input are variable indices of node. This returns 0 if vehicle < 0. 6071 """ 6072 return _pywrapcp.RoutingModel_GetArcCostForVehicle(self, from_index, to_index, vehicle) 6073 6074 def CostsAreHomogeneousAcrossVehicles(self): 6075 r"""Whether costs are homogeneous across all vehicles.""" 6076 return _pywrapcp.RoutingModel_CostsAreHomogeneousAcrossVehicles(self) 6077 6078 def GetHomogeneousCost(self, from_index, to_index): 6079 r""" 6080 Returns the cost of the segment between two nodes supposing all vehicle 6081 costs are the same (returns the cost for the first vehicle otherwise). 6082 """ 6083 return _pywrapcp.RoutingModel_GetHomogeneousCost(self, from_index, to_index) 6084 6085 def GetArcCostForFirstSolution(self, from_index, to_index): 6086 r""" 6087 Returns the cost of the arc in the context of the first solution strategy. 6088 This is typically a simplification of the actual cost; see the .cc. 6089 """ 6090 return _pywrapcp.RoutingModel_GetArcCostForFirstSolution(self, from_index, to_index) 6091 6092 def GetArcCostForClass(self, from_index, to_index, cost_class_index): 6093 r""" 6094 Returns the cost of the segment between two nodes for a given cost 6095 class. Input are variable indices of nodes and the cost class. 6096 Unlike GetArcCostForVehicle(), if cost_class is kNoCost, then the 6097 returned cost won't necessarily be zero: only some of the components 6098 of the cost that depend on the cost class will be omited. See the code 6099 for details. 6100 """ 6101 return _pywrapcp.RoutingModel_GetArcCostForClass(self, from_index, to_index, cost_class_index) 6102 6103 def GetCostClassIndexOfVehicle(self, vehicle): 6104 r"""Get the cost class index of the given vehicle.""" 6105 return _pywrapcp.RoutingModel_GetCostClassIndexOfVehicle(self, vehicle) 6106 6107 def HasVehicleWithCostClassIndex(self, cost_class_index): 6108 r""" 6109 Returns true iff the model contains a vehicle with the given 6110 cost_class_index. 6111 """ 6112 return _pywrapcp.RoutingModel_HasVehicleWithCostClassIndex(self, cost_class_index) 6113 6114 def GetCostClassesCount(self): 6115 r"""Returns the number of different cost classes in the model.""" 6116 return _pywrapcp.RoutingModel_GetCostClassesCount(self) 6117 6118 def GetNonZeroCostClassesCount(self): 6119 r"""Ditto, minus the 'always zero', built-in cost class.""" 6120 return _pywrapcp.RoutingModel_GetNonZeroCostClassesCount(self) 6121 6122 def GetVehicleClassIndexOfVehicle(self, vehicle): 6123 return _pywrapcp.RoutingModel_GetVehicleClassIndexOfVehicle(self, vehicle) 6124 6125 def GetVehicleOfClass(self, vehicle_class): 6126 r""" 6127 Returns a vehicle of the given vehicle class, and -1 if there are no 6128 vehicles for this class. 6129 """ 6130 return _pywrapcp.RoutingModel_GetVehicleOfClass(self, vehicle_class) 6131 6132 def GetVehicleClassesCount(self): 6133 r"""Returns the number of different vehicle classes in the model.""" 6134 return _pywrapcp.RoutingModel_GetVehicleClassesCount(self) 6135 6136 def GetSameVehicleIndicesOfIndex(self, node): 6137 r"""Returns variable indices of nodes constrained to be on the same route.""" 6138 return _pywrapcp.RoutingModel_GetSameVehicleIndicesOfIndex(self, node) 6139 6140 def AddSameActivityGroup(self, nodes): 6141 return _pywrapcp.RoutingModel_AddSameActivityGroup(self, nodes) 6142 6143 def GetSameActivityIndicesOfIndex(self, node): 6144 r"""Returns variable indices of nodes constrained to have the same activity.""" 6145 return _pywrapcp.RoutingModel_GetSameActivityIndicesOfIndex(self, node) 6146 6147 def GetSameActivityGroupOfIndex(self, node): 6148 r"""Returns the same activity group of the node.""" 6149 return _pywrapcp.RoutingModel_GetSameActivityGroupOfIndex(self, node) 6150 6151 def GetSameActivityGroups(self): 6152 r"""Returns same activity groups of all nodes.""" 6153 return _pywrapcp.RoutingModel_GetSameActivityGroups(self) 6154 6155 def GetSameActivityGroupsCount(self): 6156 r"""Returns the number of same activity groups.""" 6157 return _pywrapcp.RoutingModel_GetSameActivityGroupsCount(self) 6158 6159 def GetSameActivityIndicesOfGroup(self, group): 6160 r"""Returns variable indices of nodes in the same activity group.""" 6161 return _pywrapcp.RoutingModel_GetSameActivityIndicesOfGroup(self, group) 6162 6163 def GetVehicleTypeContainer(self): 6164 return _pywrapcp.RoutingModel_GetVehicleTypeContainer(self) 6165 6166 def ArcIsMoreConstrainedThanArc(self, _from, to1, to2): 6167 r""" 6168 Returns whether the arc from->to1 is more constrained than from->to2, 6169 taking into account, in order: 6170 - whether the destination node isn't an end node 6171 - whether the destination node is mandatory 6172 - whether the destination node is bound to the same vehicle as the source 6173 - the "primary constrained" dimension (see SetPrimaryConstrainedDimension) 6174 It then breaks ties using, in order: 6175 - the arc cost (taking unperformed penalties into account) 6176 - the size of the vehicle vars of "to1" and "to2" (lowest size wins) 6177 - the value: the lowest value of the indices to1 and to2 wins. 6178 See the .cc for details. 6179 The more constrained arc is typically preferable when building a 6180 first solution. This method is intended to be used as a callback for the 6181 BestValueByComparisonSelector value selector. 6182 Args: 6183 from: the variable index of the source node 6184 to1: the variable index of the first candidate destination node. 6185 to2: the variable index of the second candidate destination node. 6186 """ 6187 return _pywrapcp.RoutingModel_ArcIsMoreConstrainedThanArc(self, _from, to1, to2) 6188 6189 def DebugOutputAssignment(self, solution_assignment, dimension_to_print): 6190 r""" 6191 Print some debugging information about an assignment, including the 6192 feasible intervals of the CumulVar for dimension "dimension_to_print" 6193 at each step of the routes. 6194 If "dimension_to_print" is omitted, all dimensions will be printed. 6195 """ 6196 return _pywrapcp.RoutingModel_DebugOutputAssignment(self, solution_assignment, dimension_to_print) 6197 6198 def CheckIfAssignmentIsFeasible(self, assignment, call_at_solution_monitors): 6199 r""" 6200 Returns a vector cumul_bounds, for which cumul_bounds[i][j] is a pair 6201 containing the minimum and maximum of the CumulVar of the jth node on 6202 route i. 6203 - cumul_bounds[i][j].first is the minimum. 6204 - cumul_bounds[i][j].second is the maximum. 6205 Checks if an assignment is feasible. 6206 """ 6207 return _pywrapcp.RoutingModel_CheckIfAssignmentIsFeasible(self, assignment, call_at_solution_monitors) 6208 6209 def solver(self): 6210 r""" 6211 Returns the underlying constraint solver. Can be used to add extra 6212 constraints and/or modify search algorithms. 6213 """ 6214 return _pywrapcp.RoutingModel_solver(self) 6215 6216 def CheckLimit(self, *args): 6217 r""" 6218 Returns true if the search limit has been crossed with the given time 6219 offset. 6220 """ 6221 return _pywrapcp.RoutingModel_CheckLimit(self, *args) 6222 6223 def RemainingTime(self): 6224 r"""Returns the time left in the search limit.""" 6225 return _pywrapcp.RoutingModel_RemainingTime(self) 6226 6227 def UpdateTimeLimit(self, time_limit): 6228 r"""Updates the time limit of the search limit.""" 6229 return _pywrapcp.RoutingModel_UpdateTimeLimit(self, time_limit) 6230 6231 def TimeBuffer(self): 6232 r"""Returns the time buffer to safely return a solution.""" 6233 return _pywrapcp.RoutingModel_TimeBuffer(self) 6234 6235 def GetMutableCPSatInterrupt(self): 6236 r"""Returns the atomic<bool> to stop the CP-SAT solver.""" 6237 return _pywrapcp.RoutingModel_GetMutableCPSatInterrupt(self) 6238 6239 def GetMutableCPInterrupt(self): 6240 r"""Returns the atomic<bool> to stop the CP solver.""" 6241 return _pywrapcp.RoutingModel_GetMutableCPInterrupt(self) 6242 6243 def CancelSearch(self): 6244 r"""Cancels the current search.""" 6245 return _pywrapcp.RoutingModel_CancelSearch(self) 6246 6247 def nodes(self): 6248 r""" 6249 Sizes and indices 6250 Returns the number of nodes in the model. 6251 """ 6252 return _pywrapcp.RoutingModel_nodes(self) 6253 6254 def vehicles(self): 6255 r"""Returns the number of vehicle routes in the model.""" 6256 return _pywrapcp.RoutingModel_vehicles(self) 6257 6258 def Size(self): 6259 r"""Returns the number of next variables in the model.""" 6260 return _pywrapcp.RoutingModel_Size(self) 6261 6262 def GetNumberOfDecisionsInFirstSolution(self, search_parameters): 6263 r""" 6264 Returns statistics on first solution search, number of decisions sent to 6265 filters, number of decisions rejected by filters. 6266 """ 6267 return _pywrapcp.RoutingModel_GetNumberOfDecisionsInFirstSolution(self, search_parameters) 6268 6269 def GetNumberOfRejectsInFirstSolution(self, search_parameters): 6270 return _pywrapcp.RoutingModel_GetNumberOfRejectsInFirstSolution(self, search_parameters) 6271 6272 def GetAutomaticFirstSolutionStrategy(self): 6273 r"""Returns the automatic first solution strategy selected.""" 6274 return _pywrapcp.RoutingModel_GetAutomaticFirstSolutionStrategy(self) 6275 6276 def IsMatchingModel(self): 6277 r"""Returns true if a vehicle/node matching problem is detected.""" 6278 return _pywrapcp.RoutingModel_IsMatchingModel(self) 6279 6280 def AreRoutesInterdependent(self, parameters): 6281 r""" 6282 Returns true if routes are interdependent. This means that any 6283 modification to a route might impact another. 6284 """ 6285 return _pywrapcp.RoutingModel_AreRoutesInterdependent(self, parameters) 6286 6287 def MakeGuidedSlackFinalizer(self, dimension, initializer): 6288 r""" 6289 The next few members are in the public section only for testing purposes. 6290 6291 MakeGuidedSlackFinalizer creates a DecisionBuilder for the slacks of a 6292 dimension using a callback to choose which values to start with. 6293 The finalizer works only when all next variables in the model have 6294 been fixed. It has the following two characteristics: 6295 1. It follows the routes defined by the nexts variables when choosing a 6296 variable to make a decision on. 6297 2. When it comes to choose a value for the slack of node i, the decision 6298 builder first calls the callback with argument i, and supposingly the 6299 returned value is x it creates decisions slack[i] = x, slack[i] = x + 6300 1, slack[i] = x - 1, slack[i] = x + 2, etc. 6301 """ 6302 return _pywrapcp.RoutingModel_MakeGuidedSlackFinalizer(self, dimension, initializer) 6303 6304 def MakeSelfDependentDimensionFinalizer(self, dimension): 6305 r""" 6306 MakeSelfDependentDimensionFinalizer is a finalizer for the slacks of a 6307 self-dependent dimension. It makes an extensive use of the caches of the 6308 state dependent transits. 6309 In detail, MakeSelfDependentDimensionFinalizer returns a composition of a 6310 local search decision builder with a greedy descent operator for the cumul 6311 of the start of each route and a guided slack finalizer. Provided there 6312 are no time windows and the maximum slacks are large enough, once the 6313 cumul of the start of route is fixed, the guided finalizer can find 6314 optimal values of the slacks for the rest of the route in time 6315 proportional to the length of the route. Therefore the composed finalizer 6316 generally works in time O(log(t)*n*m), where t is the latest possible 6317 departute time, n is the number of nodes in the network and m is the 6318 number of vehicles. 6319 """ 6320 return _pywrapcp.RoutingModel_MakeSelfDependentDimensionFinalizer(self, dimension) 6321 6322 def GetPathsMetadata(self): 6323 return _pywrapcp.RoutingModel_GetPathsMetadata(self) 6324 6325 def GetVehiclesOfSameClass(self, start_end_index): 6326 r""" 6327 Returns indices of the vehicles which are in the same vehicle class as the 6328 vehicle starting or ending at start_end_index. 6329 """ 6330 return _pywrapcp.RoutingModel_GetVehiclesOfSameClass(self, start_end_index) 6331 6332 def GetSameVehicleClassArcs(self, from_index, to_index): 6333 r""" 6334 Returns all arcs which are equivalent to the {from_index, to_index} arc 6335 wrt vehicle classes. Arcs will be returned only if from_index is the 6336 start of a vehicle or if to_index is the end of a vehicle. The returned 6337 arcs will then be starting or ending at start or end nodes of vehicles in 6338 the same vehicle class. The input arc is included in the returned vector. 6339 """ 6340 return _pywrapcp.RoutingModel_GetSameVehicleClassArcs(self, from_index, to_index)
4927 def __init__(self, *args): 4928 r""" 4929 Constructor taking an index manager. The version which does not take 4930 RoutingModelParameters is equivalent to passing 4931 DefaultRoutingModelParameters(). 4932 """ 4933 _pywrapcp.RoutingModel_swiginit(self, _pywrapcp.new_RoutingModel(*args))
Constructor taking an index manager. The version which does not take RoutingModelParameters is equivalent to passing DefaultRoutingModelParameters().
4918 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
4939 def RegisterUnaryTransitVector(self, values): 4940 r""" 4941 Registers 'callback' and returns its index. 4942 The sign parameter allows to notify the solver that the callback only 4943 return values of the given sign. This can help the solver, but passing 4944 an incorrect sign may crash in non-opt compilation mode, and yield 4945 incorrect results in opt. 4946 """ 4947 return _pywrapcp.RoutingModel_RegisterUnaryTransitVector(self, values)
Registers 'callback' and returns its index. The sign parameter allows to notify the solver that the callback only return values of the given sign. This can help the solver, but passing an incorrect sign may crash in non-opt compilation mode, and yield incorrect results in opt.
4970 def AddDimension(self, evaluator_index, slack_max, capacity, fix_start_cumul_to_zero, name): 4971 r""" 4972 Model creation 4973 Methods to add dimensions to routes; dimensions represent quantities 4974 accumulated at nodes along the routes. They represent quantities such as 4975 weights or volumes carried along the route, or distance or times. 4976 Quantities at a node are represented by "cumul" variables and the increase 4977 or decrease of quantities between nodes are represented by "transit" 4978 variables. These variables are linked as follows: 4979 if j == next(i), cumul(j) = cumul(i) + transit(i, j) + slack(i) 4980 where slack is a positive slack variable (can represent waiting times for 4981 a time dimension). 4982 Setting the value of fix_start_cumul_to_zero to true will force the 4983 "cumul" variable of the start node of all vehicles to be equal to 0. 4984 Creates a dimension where the transit variable is constrained to be 4985 equal to evaluator(i, next(i)); 'slack_max' is the upper bound of the 4986 slack variable and 'capacity' is the upper bound of the cumul variables. 4987 'name' is the name used to reference the dimension; this name is used to 4988 get cumul and transit variables from the routing model. 4989 Returns false if a dimension with the same name has already been created 4990 (and doesn't create the new dimension). 4991 Takes ownership of the callback 'evaluator'. 4992 """ 4993 return _pywrapcp.RoutingModel_AddDimension(self, evaluator_index, slack_max, capacity, fix_start_cumul_to_zero, name)
Model creation Methods to add dimensions to routes; dimensions represent quantities accumulated at nodes along the routes. They represent quantities such as weights or volumes carried along the route, or distance or times. Quantities at a node are represented by "cumul" variables and the increase or decrease of quantities between nodes are represented by "transit" variables. These variables are linked as follows: if j == next(i), cumul(j) = cumul(i) + transit(i, j) + slack(i) where slack is a positive slack variable (can represent waiting times for a time dimension). Setting the value of fix_start_cumul_to_zero to true will force the "cumul" variable of the start node of all vehicles to be equal to 0. Creates a dimension where the transit variable is constrained to be equal to evaluator(i, next(i)); 'slack_max' is the upper bound of the slack variable and 'capacity' is the upper bound of the cumul variables. 'name' is the name used to reference the dimension; this name is used to get cumul and transit variables from the routing model. Returns false if a dimension with the same name has already been created (and doesn't create the new dimension). Takes ownership of the callback 'evaluator'.
5001 def AddDimensionWithVehicleTransitAndCapacity(self, evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name): 5002 return _pywrapcp.RoutingModel_AddDimensionWithVehicleTransitAndCapacity(self, evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name)
5004 def AddDimensionWithCumulDependentVehicleTransitAndCapacity(self, fixed_evaluator_indices, cumul_dependent_evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name): 5005 r""" 5006 Creates a dimension where the transit variable on arc i->j is the sum of: 5007 - A "fixed" transit value, obtained from the fixed_evaluator_index for 5008 this vehicle, referencing evaluators in transit_evaluators_, and 5009 - A FloatSlopePiecewiseLinearFunction of the cumul of node i, obtained 5010 from the cumul_dependent_evaluator_index of this vehicle, pointing to 5011 an evaluator in cumul_dependent_transit_evaluators_. 5012 """ 5013 return _pywrapcp.RoutingModel_AddDimensionWithCumulDependentVehicleTransitAndCapacity(self, fixed_evaluator_indices, cumul_dependent_evaluator_indices, slack_max, vehicle_capacities, fix_start_cumul_to_zero, name)
Creates a dimension where the transit variable on arc i->j is the sum of:
- A "fixed" transit value, obtained from the fixed_evaluator_index for this vehicle, referencing evaluators in transit_evaluators_, and
- A FloatSlopePiecewiseLinearFunction of the cumul of node i, obtained from the cumul_dependent_evaluator_index of this vehicle, pointing to an evaluator in cumul_dependent_transit_evaluators_.
5015 def AddConstantDimensionWithSlack(self, value, capacity, slack_max, fix_start_cumul_to_zero, name): 5016 r""" 5017 Creates a dimension where the transit variable is constrained to be 5018 equal to 'value'; 'capacity' is the upper bound of the cumul variables. 5019 'name' is the name used to reference the dimension; this name is used to 5020 get cumul and transit variables from the routing model. 5021 Returns a pair consisting of an index to the registered unary transit 5022 callback and a bool denoting whether the dimension has been created. 5023 It is false if a dimension with the same name has already been created 5024 (and doesn't create the new dimension but still register a new callback). 5025 """ 5026 return _pywrapcp.RoutingModel_AddConstantDimensionWithSlack(self, value, capacity, slack_max, fix_start_cumul_to_zero, name)
Creates a dimension where the transit variable is constrained to be equal to 'value'; 'capacity' is the upper bound of the cumul variables. 'name' is the name used to reference the dimension; this name is used to get cumul and transit variables from the routing model. Returns a pair consisting of an index to the registered unary transit callback and a bool denoting whether the dimension has been created. It is false if a dimension with the same name has already been created (and doesn't create the new dimension but still register a new callback).
5031 def AddVectorDimension(self, values, capacity, fix_start_cumul_to_zero, name): 5032 r""" 5033 Creates a dimension where the transit variable is constrained to be 5034 equal to 'values[i]' for node i; 'capacity' is the upper bound of 5035 the cumul variables. 'name' is the name used to reference the dimension; 5036 this name is used to get cumul and transit variables from the routing 5037 model. 5038 Returns a pair consisting of an index to the registered unary transit 5039 callback and a bool denoting whether the dimension has been created. 5040 It is false if a dimension with the same name has already been created 5041 (and doesn't create the new dimension but still register a new callback). 5042 """ 5043 return _pywrapcp.RoutingModel_AddVectorDimension(self, values, capacity, fix_start_cumul_to_zero, name)
Creates a dimension where the transit variable is constrained to be equal to 'values[i]' for node i; 'capacity' is the upper bound of the cumul variables. 'name' is the name used to reference the dimension; this name is used to get cumul and transit variables from the routing model. Returns a pair consisting of an index to the registered unary transit callback and a bool denoting whether the dimension has been created. It is false if a dimension with the same name has already been created (and doesn't create the new dimension but still register a new callback).
5045 def AddMatrixDimension(self, values, capacity, fix_start_cumul_to_zero, name): 5046 r""" 5047 Creates a dimension where the transit variable is constrained to be 5048 equal to 'values[i][next(i)]' for node i; 'capacity' is the upper bound of 5049 the cumul variables. 'name' is the name used to reference the dimension; 5050 this name is used to get cumul and transit variables from the routing 5051 model. 5052 Returns a pair consisting of an index to the registered transit callback 5053 and a bool denoting whether the dimension has been created. 5054 It is false if a dimension with the same name has already been created 5055 (and doesn't create the new dimension but still register a new callback). 5056 """ 5057 return _pywrapcp.RoutingModel_AddMatrixDimension(self, values, capacity, fix_start_cumul_to_zero, name)
Creates a dimension where the transit variable is constrained to be equal to 'values[i][next(i)]' for node i; 'capacity' is the upper bound of the cumul variables. 'name' is the name used to reference the dimension; this name is used to get cumul and transit variables from the routing model. Returns a pair consisting of an index to the registered transit callback and a bool denoting whether the dimension has been created. It is false if a dimension with the same name has already been created (and doesn't create the new dimension but still register a new callback).
5059 def GetAllDimensionNames(self): 5060 r"""Outputs the names of all dimensions added to the routing engine.""" 5061 return _pywrapcp.RoutingModel_GetAllDimensionNames(self)
Outputs the names of all dimensions added to the routing engine.
5063 def GetDimensions(self): 5064 r"""Returns all dimensions of the model.""" 5065 return _pywrapcp.RoutingModel_GetDimensions(self)
Returns all dimensions of the model.
5067 def GetDimensionsWithSoftOrSpanCosts(self): 5068 r"""Returns dimensions with soft or vehicle span costs.""" 5069 return _pywrapcp.RoutingModel_GetDimensionsWithSoftOrSpanCosts(self)
Returns dimensions with soft or vehicle span costs.
5071 def GetUnaryDimensions(self): 5072 r"""Returns dimensions for which all transit evaluators are unary.""" 5073 return _pywrapcp.RoutingModel_GetUnaryDimensions(self)
Returns dimensions for which all transit evaluators are unary.
5075 def GetDimensionsWithGlobalCumulOptimizers(self): 5076 r"""Returns the dimensions which have [global|local]_dimension_optimizers_.""" 5077 return _pywrapcp.RoutingModel_GetDimensionsWithGlobalCumulOptimizers(self)
Returns the dimensions which have [global|local]_dimension_optimizers_.
5082 def HasGlobalCumulOptimizer(self, dimension): 5083 r"""Returns whether the given dimension has global/local cumul optimizers.""" 5084 return _pywrapcp.RoutingModel_HasGlobalCumulOptimizer(self, dimension)
Returns whether the given dimension has global/local cumul optimizers.
5089 def GetMutableGlobalCumulLPOptimizer(self, dimension): 5090 r""" 5091 Returns the global/local dimension cumul optimizer for a given dimension, 5092 or nullptr if there is none. 5093 """ 5094 return _pywrapcp.RoutingModel_GetMutableGlobalCumulLPOptimizer(self, dimension)
Returns the global/local dimension cumul optimizer for a given dimension, or nullptr if there is none.
5105 def HasDimension(self, dimension_name): 5106 r"""Returns true if a dimension exists for a given dimension name.""" 5107 return _pywrapcp.RoutingModel_HasDimension(self, dimension_name)
Returns true if a dimension exists for a given dimension name.
5109 def GetDimensionOrDie(self, dimension_name): 5110 r"""Returns a dimension from its name. Dies if the dimension does not exist.""" 5111 return _pywrapcp.RoutingModel_GetDimensionOrDie(self, dimension_name)
Returns a dimension from its name. Dies if the dimension does not exist.
5113 def GetMutableDimension(self, dimension_name): 5114 r""" 5115 Returns a dimension from its name. Returns nullptr if the dimension does 5116 not exist. 5117 """ 5118 return _pywrapcp.RoutingModel_GetMutableDimension(self, dimension_name)
Returns a dimension from its name. Returns nullptr if the dimension does not exist.
5120 def SetPrimaryConstrainedDimension(self, dimension_name): 5121 r""" 5122 Set the given dimension as "primary constrained". As of August 2013, this 5123 is only used by ArcIsMoreConstrainedThanArc(). 5124 "dimension" must be the name of an existing dimension, or be empty, in 5125 which case there will not be a primary dimension after this call. 5126 """ 5127 return _pywrapcp.RoutingModel_SetPrimaryConstrainedDimension(self, dimension_name)
Set the given dimension as "primary constrained". As of August 2013, this is only used by ArcIsMoreConstrainedThanArc(). "dimension" must be the name of an existing dimension, or be empty, in which case there will not be a primary dimension after this call.
5129 def GetPrimaryConstrainedDimension(self): 5130 r"""Get the primary constrained dimension, or an empty string if it is unset.""" 5131 return _pywrapcp.RoutingModel_GetPrimaryConstrainedDimension(self)
Get the primary constrained dimension, or an empty string if it is unset.
5136 def GetDimensionResourceGroupIndices(self, dimension): 5137 r""" 5138 Returns the indices of resource groups for this dimension. This method can 5139 only be called after the model has been closed. 5140 """ 5141 return _pywrapcp.RoutingModel_GetDimensionResourceGroupIndices(self, dimension)
Returns the indices of resource groups for this dimension. This method can only be called after the model has been closed.
5143 def GetDimensionResourceGroupIndex(self, dimension): 5144 r""" 5145 Returns the index of the resource group attached to the dimension. 5146 DCHECKS that there's exactly one resource group for this dimension. 5147 """ 5148 return _pywrapcp.RoutingModel_GetDimensionResourceGroupIndex(self, dimension)
Returns the index of the resource group attached to the dimension. DCHECKS that there's exactly one resource group for this dimension.
5152 def AddDisjunction(self, *args): 5153 r""" 5154 Adds a disjunction constraint on the indices. 5155 Exactly 'max_cardinality' of the indices are active. 5156 5157 If a penalty is given, at most 'max_cardinality' of the indices can be 5158 active, and if less are active, 'penalty' is payed per inactive index if 5159 the penalty cost is set to `PENALIZE_PER_INACTIVE`. 5160 This is equivalent to adding the constraint: 5161 p + Sum(i)active[i] == max_cardinality 5162 where p is an integer variable. 5163 If the penalty cost is set to `PENALIZE_ONCE`, then 'penalty' is payed 5164 once if there are less than `max_cardinality` of the indices active. 5165 This is equivalent to adding the constraint: 5166 p == (Sum(i)active[i] != max_cardinality) 5167 where p is a boolean variable. 5168 The following cost is added to the cost function: p * penalty. 5169 :type penalty: int, in, optional 5170 :param penalty: must be positive to make the disjunction optional; a 5171 negative penalty will force 'max_cardinality' indices of the disjunction 5172 to be performed, and therefore p == 0. 5173 Note: passing a vector with a single index will model an optional index 5174 with a penalty cost if it is not visited. 5175 Warning: Start and end indices of any vehicle cannot be part of a 5176 disjunction. 5177 """ 5178 return _pywrapcp.RoutingModel_AddDisjunction(self, *args)
Adds a disjunction constraint on the indices. Exactly 'max_cardinality' of the indices are active.
If a penalty is given, at most 'max_cardinality' of the indices can be
active, and if less are active, 'penalty' is payed per inactive index if
the penalty cost is set to PENALIZE_PER_INACTIVE.
This is equivalent to adding the constraint:
p + Sum(i)active[i] == max_cardinality
where p is an integer variable.
If the penalty cost is set to PENALIZE_ONCE, then 'penalty' is payed
once if there are less than max_cardinality of the indices active.
This is equivalent to adding the constraint:
p == (Sum(i)active[i] != max_cardinality)
where p is a boolean variable. The following cost is added to the cost function: p * penalty.
Parameters
- penalty: must be positive to make the disjunction optional; a negative penalty will force 'max_cardinality' indices of the disjunction to be performed, and therefore p == 0. Note: passing a vector with a single index will model an optional index with a penalty cost if it is not visited. Warning: Start and end indices of any vehicle cannot be part of a disjunction.
5180 def GetDisjunctionIndices(self, index): 5181 r"""Returns the indices of the disjunctions to which an index belongs.""" 5182 return _pywrapcp.RoutingModel_GetDisjunctionIndices(self, index)
Returns the indices of the disjunctions to which an index belongs.
5184 def GetDisjunctionPenalty(self, index): 5185 r"""Returns the penalty of the node disjunction of index 'index'.""" 5186 return _pywrapcp.RoutingModel_GetDisjunctionPenalty(self, index)
Returns the penalty of the node disjunction of index 'index'.
5188 def GetDisjunctionMaxCardinality(self, index): 5189 r""" 5190 Returns the maximum number of possible active nodes of the node 5191 disjunction of index 'index'. 5192 """ 5193 return _pywrapcp.RoutingModel_GetDisjunctionMaxCardinality(self, index)
Returns the maximum number of possible active nodes of the node disjunction of index 'index'.
5195 def GetDisjunctionPenaltyCostBehavior(self, index): 5196 r""" 5197 Returns the 'PenaltyCostBehavior' used by the disjunction of index 5198 'index'. 5199 """ 5200 return _pywrapcp.RoutingModel_GetDisjunctionPenaltyCostBehavior(self, index)
Returns the 'PenaltyCostBehavior' used by the disjunction of index 'index'.
5202 def GetNumberOfDisjunctions(self): 5203 r"""Returns the number of node disjunctions in the model.""" 5204 return _pywrapcp.RoutingModel_GetNumberOfDisjunctions(self)
Returns the number of node disjunctions in the model.
5206 def HasMandatoryDisjunctions(self): 5207 r""" 5208 Returns true if the model contains mandatory disjunctions (ones with 5209 kNoPenalty as penalty). 5210 """ 5211 return _pywrapcp.RoutingModel_HasMandatoryDisjunctions(self)
Returns true if the model contains mandatory disjunctions (ones with kNoPenalty as penalty).
5213 def HasMaxCardinalityConstrainedDisjunctions(self): 5214 r""" 5215 Returns true if the model contains at least one disjunction which is 5216 constrained by its max_cardinality. 5217 """ 5218 return _pywrapcp.RoutingModel_HasMaxCardinalityConstrainedDisjunctions(self)
Returns true if the model contains at least one disjunction which is constrained by its max_cardinality.
5220 def GetPerfectBinaryDisjunctions(self): 5221 r""" 5222 Returns the list of all perfect binary disjunctions, as pairs of variable 5223 indices: a disjunction is "perfect" when its variables do not appear in 5224 any other disjunction. Each pair is sorted (lowest variable index first), 5225 and the output vector is also sorted (lowest pairs first). 5226 """ 5227 return _pywrapcp.RoutingModel_GetPerfectBinaryDisjunctions(self)
Returns the list of all perfect binary disjunctions, as pairs of variable indices: a disjunction is "perfect" when its variables do not appear in any other disjunction. Each pair is sorted (lowest variable index first), and the output vector is also sorted (lowest pairs first).
5229 def IgnoreDisjunctionsAlreadyForcedToZero(self): 5230 r""" 5231 SPECIAL: Makes the solver ignore all the disjunctions whose active 5232 variables are all trivially zero (i.e. Max() == 0), by setting their 5233 max_cardinality to 0. 5234 This can be useful when using the BaseBinaryDisjunctionNeighborhood 5235 operators, in the context of arc-based routing. 5236 """ 5237 return _pywrapcp.RoutingModel_IgnoreDisjunctionsAlreadyForcedToZero(self)
SPECIAL: Makes the solver ignore all the disjunctions whose active variables are all trivially zero (i.e. Max() == 0), by setting their max_cardinality to 0. This can be useful when using the BaseBinaryDisjunctionNeighborhood operators, in the context of arc-based routing.
5239 def AddSoftSameVehicleConstraint(self, indices, cost): 5240 r""" 5241 Adds a soft constraint to force a set of variable indices to be on the 5242 same vehicle. If all nodes are not on the same vehicle, each extra vehicle 5243 used adds 'cost' to the cost function. 5244 TODO(user): Extend this to allow nodes/indices to be on the same given 5245 set of vehicle. 5246 """ 5247 return _pywrapcp.RoutingModel_AddSoftSameVehicleConstraint(self, indices, cost)
Adds a soft constraint to force a set of variable indices to be on the same vehicle. If all nodes are not on the same vehicle, each extra vehicle used adds 'cost' to the cost function. TODO(user): Extend this to allow nodes/indices to be on the same given set of vehicle.
5249 def GetNumberOfSoftSameVehicleConstraints(self): 5250 r"""Returns the number of soft same vehicle constraints in the model.""" 5251 return _pywrapcp.RoutingModel_GetNumberOfSoftSameVehicleConstraints(self)
Returns the number of soft same vehicle constraints in the model.
5253 def GetSoftSameVehicleIndices(self, index): 5254 r""" 5255 Returns the indices of the nodes in the soft same vehicle constraint of 5256 index 'index'. 5257 """ 5258 return _pywrapcp.RoutingModel_GetSoftSameVehicleIndices(self, index)
Returns the indices of the nodes in the soft same vehicle constraint of index 'index'.
5260 def GetSoftSameVehicleCost(self, index): 5261 r"""Returns the cost of the soft same vehicle constraint of index 'index'.""" 5262 return _pywrapcp.RoutingModel_GetSoftSameVehicleCost(self, index)
Returns the cost of the soft same vehicle constraint of index 'index'.
5264 def SetAllowedVehiclesForIndex(self, vehicles, index): 5265 r""" 5266 Sets the vehicles which can visit a given node. If the node is in a 5267 disjunction, this will not prevent it from being unperformed. 5268 Specifying an empty vector of vehicles has no effect (all vehicles 5269 will be allowed to visit the node). 5270 """ 5271 return _pywrapcp.RoutingModel_SetAllowedVehiclesForIndex(self, vehicles, index)
Sets the vehicles which can visit a given node. If the node is in a disjunction, this will not prevent it from being unperformed. Specifying an empty vector of vehicles has no effect (all vehicles will be allowed to visit the node).
5273 def IsVehicleAllowedForIndex(self, vehicle, index): 5274 r"""Returns true if a vehicle is allowed to visit a given node.""" 5275 return _pywrapcp.RoutingModel_IsVehicleAllowedForIndex(self, vehicle, index)
Returns true if a vehicle is allowed to visit a given node.
5277 def AddPickupAndDelivery(self, pickup, delivery): 5278 r""" 5279 Notifies that index1 and index2 form a pair of nodes which should belong 5280 to the same route. This methods helps the search find better solutions, 5281 especially in the local search phase. 5282 It should be called each time you have an equality constraint linking 5283 the vehicle variables of two node (including for instance pickup and 5284 delivery problems): 5285 Solver* const solver = routing.solver(); 5286 int64_t index1 = manager.NodeToIndex(node1); 5287 int64_t index2 = manager.NodeToIndex(node2); 5288 solver->AddConstraint(solver->MakeEquality( 5289 routing.VehicleVar(index1), 5290 routing.VehicleVar(index2))); 5291 routing.AddPickupAndDelivery(index1, index2); 5292 """ 5293 return _pywrapcp.RoutingModel_AddPickupAndDelivery(self, pickup, delivery)
Notifies that index1 and index2 form a pair of nodes which should belong to the same route. This methods helps the search find better solutions, especially in the local search phase. It should be called each time you have an equality constraint linking the vehicle variables of two node (including for instance pickup and delivery problems): Solver* const solver = routing.solver(); int64_t index1 = manager.NodeToIndex(node1); int64_t index2 = manager.NodeToIndex(node2); solver->AddConstraint(solver->MakeEquality( routing.VehicleVar(index1), routing.VehicleVar(index2))); routing.AddPickupAndDelivery(index1, index2);
5295 def AddPickupAndDeliverySets(self, pickup_disjunction, delivery_disjunction): 5296 r""" 5297 Same as AddPickupAndDelivery but notifying that the performed node from 5298 the disjunction of index 'pickup_disjunction' is on the same route as the 5299 performed node from the disjunction of index 'delivery_disjunction'. 5300 """ 5301 return _pywrapcp.RoutingModel_AddPickupAndDeliverySets(self, pickup_disjunction, delivery_disjunction)
Same as AddPickupAndDelivery but notifying that the performed node from the disjunction of index 'pickup_disjunction' is on the same route as the performed node from the disjunction of index 'delivery_disjunction'.
5303 def GetPickupPosition(self, node_index): 5304 r"""Returns the pickup and delivery positions where the node is a pickup.""" 5305 return _pywrapcp.RoutingModel_GetPickupPosition(self, node_index)
Returns the pickup and delivery positions where the node is a pickup.
5307 def GetDeliveryPosition(self, node_index): 5308 r"""Returns the pickup and delivery positions where the node is a delivery.""" 5309 return _pywrapcp.RoutingModel_GetDeliveryPosition(self, node_index)
Returns the pickup and delivery positions where the node is a delivery.
5311 def IsPickup(self, node_index): 5312 r"""Returns whether the node is a pickup (resp. delivery).""" 5313 return _pywrapcp.RoutingModel_IsPickup(self, node_index)
Returns whether the node is a pickup (resp. delivery).
5318 def SetPickupAndDeliveryPolicyOfAllVehicles(self, policy): 5319 r""" 5320 Sets the Pickup and delivery policy of all vehicles. It is equivalent to 5321 calling SetPickupAndDeliveryPolicyOfVehicle on all vehicles. 5322 """ 5323 return _pywrapcp.RoutingModel_SetPickupAndDeliveryPolicyOfAllVehicles(self, policy)
Sets the Pickup and delivery policy of all vehicles. It is equivalent to calling SetPickupAndDeliveryPolicyOfVehicle on all vehicles.
5331 def GetNumOfSingletonNodes(self): 5332 r""" 5333 Returns the number of non-start/end nodes which do not appear in a 5334 pickup/delivery pair. 5335 """ 5336 return _pywrapcp.RoutingModel_GetNumOfSingletonNodes(self)
Returns the number of non-start/end nodes which do not appear in a pickup/delivery pair.
When visited, one instance of type 'T' previously added to the route (TYPE_ADDED_TO_VEHICLE), if any, is removed from the vehicle. If the type was not previously added to the route or all added instances have already been removed, this visit has no effect on the types.
With the following policy, the visit enforces that type 'T' is considered on the route from its start until this node is visited.
The visit doesn't have an impact on the number of types 'T' on the route, as it's (virtually) added and removed directly. This policy can be used for visits which are part of an incompatibility or requirement set without affecting the type count on the route.
5380 def AddHardTypeIncompatibility(self, type1, type2): 5381 r""" 5382 Incompatibilities: 5383 Two nodes with "hard" incompatible types cannot share the same route at 5384 all, while with a "temporal" incompatibility they can't be on the same 5385 route at the same time. 5386 NOTE: To avoid unnecessary memory reallocations, it is recommended to only 5387 add incompatibilities once all the existing types have been set with 5388 SetVisitType(). 5389 """ 5390 return _pywrapcp.RoutingModel_AddHardTypeIncompatibility(self, type1, type2)
Incompatibilities: Two nodes with "hard" incompatible types cannot share the same route at all, while with a "temporal" incompatibility they can't be on the same route at the same time. NOTE: To avoid unnecessary memory reallocations, it is recommended to only add incompatibilities once all the existing types have been set with SetVisitType().
5395 def GetHardTypeIncompatibilitiesOfType(self, type): 5396 r"""Returns visit types incompatible with a given type.""" 5397 return _pywrapcp.RoutingModel_GetHardTypeIncompatibilitiesOfType(self, type)
Returns visit types incompatible with a given type.
5402 def HasHardTypeIncompatibilities(self): 5403 r""" 5404 Returns true iff any hard (resp. temporal) type incompatibilities have 5405 been added to the model. 5406 """ 5407 return _pywrapcp.RoutingModel_HasHardTypeIncompatibilities(self)
Returns true iff any hard (resp. temporal) type incompatibilities have been added to the model.
5412 def AddSameVehicleRequiredTypeAlternatives(self, dependent_type, required_type_alternatives): 5413 r""" 5414 Requirements: 5415 NOTE: As of 2019-04, cycles in the requirement graph are not supported, 5416 and lead to the dependent nodes being skipped if possible (otherwise 5417 the model is considered infeasible). 5418 The following functions specify that "dependent_type" requires at least 5419 one of the types in "required_type_alternatives". 5420 5421 For same-vehicle requirements, a node of dependent type type_D requires at 5422 least one node of type type_R among the required alternatives on the same 5423 route. 5424 NOTE: To avoid unnecessary memory reallocations, it is recommended to only 5425 add requirements once all the existing types have been set with 5426 SetVisitType(). 5427 """ 5428 return _pywrapcp.RoutingModel_AddSameVehicleRequiredTypeAlternatives(self, dependent_type, required_type_alternatives)
Requirements: NOTE: As of 2019-04, cycles in the requirement graph are not supported, and lead to the dependent nodes being skipped if possible (otherwise the model is considered infeasible). The following functions specify that "dependent_type" requires at least one of the types in "required_type_alternatives".
For same-vehicle requirements, a node of dependent type type_D requires at least one node of type type_R among the required alternatives on the same route. NOTE: To avoid unnecessary memory reallocations, it is recommended to only add requirements once all the existing types have been set with SetVisitType().
5430 def AddRequiredTypeAlternativesWhenAddingType(self, dependent_type, required_type_alternatives): 5431 r""" 5432 If type_D depends on type_R when adding type_D, any node_D of type_D and 5433 VisitTypePolicy TYPE_ADDED_TO_VEHICLE or 5434 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED requires at least one type_R on its 5435 vehicle at the time node_D is visited. 5436 """ 5437 return _pywrapcp.RoutingModel_AddRequiredTypeAlternativesWhenAddingType(self, dependent_type, required_type_alternatives)
If type_D depends on type_R when adding type_D, any node_D of type_D and VisitTypePolicy TYPE_ADDED_TO_VEHICLE or TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED requires at least one type_R on its vehicle at the time node_D is visited.
5439 def AddRequiredTypeAlternativesWhenRemovingType(self, dependent_type, required_type_alternatives): 5440 r""" 5441 The following requirements apply when visiting dependent nodes that remove 5442 their type from the route, i.e. type_R must be on the vehicle when type_D 5443 of VisitTypePolicy ADDED_TYPE_REMOVED_FROM_VEHICLE, 5444 TYPE_ON_VEHICLE_UP_TO_VISIT or TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED is 5445 visited. 5446 """ 5447 return _pywrapcp.RoutingModel_AddRequiredTypeAlternativesWhenRemovingType(self, dependent_type, required_type_alternatives)
The following requirements apply when visiting dependent nodes that remove their type from the route, i.e. type_R must be on the vehicle when type_D of VisitTypePolicy ADDED_TYPE_REMOVED_FROM_VEHICLE, TYPE_ON_VEHICLE_UP_TO_VISIT or TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED is visited.
5449 def GetSameVehicleRequiredTypeAlternativesOfType(self, type): 5450 r""" 5451 Returns the set of same-vehicle requirement alternatives for the given 5452 type. 5453 """ 5454 return _pywrapcp.RoutingModel_GetSameVehicleRequiredTypeAlternativesOfType(self, type)
Returns the set of same-vehicle requirement alternatives for the given type.
5456 def GetRequiredTypeAlternativesWhenAddingType(self, type): 5457 r"""Returns the set of requirement alternatives when adding the given type.""" 5458 return _pywrapcp.RoutingModel_GetRequiredTypeAlternativesWhenAddingType(self, type)
Returns the set of requirement alternatives when adding the given type.
5460 def GetRequiredTypeAlternativesWhenRemovingType(self, type): 5461 r"""Returns the set of requirement alternatives when removing the given type.""" 5462 return _pywrapcp.RoutingModel_GetRequiredTypeAlternativesWhenRemovingType(self, type)
Returns the set of requirement alternatives when removing the given type.
5464 def HasSameVehicleTypeRequirements(self): 5465 r""" 5466 Returns true iff any same-route (resp. temporal) type requirements have 5467 been added to the model. 5468 """ 5469 return _pywrapcp.RoutingModel_HasSameVehicleTypeRequirements(self)
Returns true iff any same-route (resp. temporal) type requirements have been added to the model.
5474 def HasTypeRegulations(self): 5475 r""" 5476 Returns true iff the model has any incompatibilities or requirements set 5477 on node types. 5478 """ 5479 return _pywrapcp.RoutingModel_HasTypeRegulations(self)
Returns true iff the model has any incompatibilities or requirements set on node types.
5481 def UnperformedPenalty(self, var_index): 5482 r""" 5483 Get the "unperformed" penalty of a node. This is only well defined if the 5484 node is only part of a single Disjunction, and that disjunction has a 5485 penalty. For forced active nodes returns max int64_t. In all other cases, 5486 this returns 0. 5487 """ 5488 return _pywrapcp.RoutingModel_UnperformedPenalty(self, var_index)
Get the "unperformed" penalty of a node. This is only well defined if the node is only part of a single Disjunction, and that disjunction has a penalty. For forced active nodes returns max int64_t. In all other cases, this returns 0.
5490 def UnperformedPenaltyOrValue(self, default_value, var_index): 5491 r""" 5492 Same as above except that it returns default_value instead of 0 when 5493 penalty is not well defined (default value is passed as first argument to 5494 simplify the usage of the method in a callback). 5495 """ 5496 return _pywrapcp.RoutingModel_UnperformedPenaltyOrValue(self, default_value, var_index)
Same as above except that it returns default_value instead of 0 when penalty is not well defined (default value is passed as first argument to simplify the usage of the method in a callback).
5498 def GetDepot(self): 5499 r""" 5500 Returns the variable index of the first starting or ending node of all 5501 routes. If all routes start and end at the same node (single depot), this 5502 is the node returned. 5503 """ 5504 return _pywrapcp.RoutingModel_GetDepot(self)
Returns the variable index of the first starting or ending node of all routes. If all routes start and end at the same node (single depot), this is the node returned.
5506 def SetMaximumNumberOfActiveVehicles(self, max_active_vehicles): 5507 r""" 5508 Constrains the maximum number of active vehicles, aka the number of 5509 vehicles which do not have an empty route. For instance, this can be used 5510 to limit the number of routes in the case where there are fewer drivers 5511 than vehicles and that the fleet of vehicle is heterogeneous. 5512 """ 5513 return _pywrapcp.RoutingModel_SetMaximumNumberOfActiveVehicles(self, max_active_vehicles)
Constrains the maximum number of active vehicles, aka the number of vehicles which do not have an empty route. For instance, this can be used to limit the number of routes in the case where there are fewer drivers than vehicles and that the fleet of vehicle is heterogeneous.
5515 def GetMaximumNumberOfActiveVehicles(self): 5516 r"""Returns the maximum number of active vehicles.""" 5517 return _pywrapcp.RoutingModel_GetMaximumNumberOfActiveVehicles(self)
Returns the maximum number of active vehicles.
5519 def SetArcCostEvaluatorOfAllVehicles(self, evaluator_index): 5520 r""" 5521 Sets the cost function of the model such that the cost of a segment of a 5522 route between node 'from' and 'to' is evaluator(from, to), whatever the 5523 route or vehicle performing the route. 5524 """ 5525 return _pywrapcp.RoutingModel_SetArcCostEvaluatorOfAllVehicles(self, evaluator_index)
Sets the cost function of the model such that the cost of a segment of a route between node 'from' and 'to' is evaluator(from, to), whatever the route or vehicle performing the route.
5527 def SetArcCostEvaluatorOfVehicle(self, evaluator_index, vehicle): 5528 r"""Sets the cost function for a given vehicle route.""" 5529 return _pywrapcp.RoutingModel_SetArcCostEvaluatorOfVehicle(self, evaluator_index, vehicle)
Sets the cost function for a given vehicle route.
5531 def SetFixedCostOfAllVehicles(self, cost): 5532 r""" 5533 Sets the fixed cost of all vehicle routes. It is equivalent to calling 5534 SetFixedCostOfVehicle on all vehicle routes. 5535 """ 5536 return _pywrapcp.RoutingModel_SetFixedCostOfAllVehicles(self, cost)
Sets the fixed cost of all vehicle routes. It is equivalent to calling SetFixedCostOfVehicle on all vehicle routes.
5538 def SetFixedCostOfVehicle(self, cost, vehicle): 5539 r"""Sets the fixed cost of one vehicle route.""" 5540 return _pywrapcp.RoutingModel_SetFixedCostOfVehicle(self, cost, vehicle)
Sets the fixed cost of one vehicle route.
5542 def GetFixedCostOfVehicle(self, vehicle): 5543 r""" 5544 Returns the route fixed cost taken into account if the route of the 5545 vehicle is not empty, aka there's at least one node on the route other 5546 than the first and last nodes. 5547 """ 5548 return _pywrapcp.RoutingModel_GetFixedCostOfVehicle(self, vehicle)
Returns the route fixed cost taken into account if the route of the vehicle is not empty, aka there's at least one node on the route other than the first and last nodes.
5553 def SetPathEnergyCostsOfVehicle(self, force, distance, threshold, cost_per_unit_below_threshold, cost_per_unit_above_threshold, vehicle): 5554 return _pywrapcp.RoutingModel_SetPathEnergyCostsOfVehicle(self, force, distance, threshold, cost_per_unit_below_threshold, cost_per_unit_above_threshold, vehicle)
5556 def SetAmortizedCostFactorsOfAllVehicles(self, linear_cost_factor, quadratic_cost_factor): 5557 r""" 5558 The following methods set the linear and quadratic cost factors of 5559 vehicles (must be positive values). The default value of these parameters 5560 is zero for all vehicles. 5561 5562 When set, the cost_ of the model will contain terms aiming at reducing the 5563 number of vehicles used in the model, by adding the following to the 5564 objective for every vehicle v: 5565 INDICATOR(v used in the model) * 5566 [linear_cost_factor_of_vehicle_[v] 5567 - quadratic_cost_factor_of_vehicle_[v]*(square of length of route v)] 5568 i.e. for every used vehicle, we add the linear factor as fixed cost, and 5569 subtract the square of the route length multiplied by the quadratic 5570 factor. This second term aims at making the routes as dense as possible. 5571 5572 Sets the linear and quadratic cost factor of all vehicles. 5573 """ 5574 return _pywrapcp.RoutingModel_SetAmortizedCostFactorsOfAllVehicles(self, linear_cost_factor, quadratic_cost_factor)
The following methods set the linear and quadratic cost factors of vehicles (must be positive values). The default value of these parameters is zero for all vehicles.
When set, the cost_ of the model will contain terms aiming at reducing the number of vehicles used in the model, by adding the following to the objective for every vehicle v: INDICATOR(v used in the model) * [linear_cost_factor_of_vehicle_[v]
- quadratic_cost_factor_of_vehicle_[v]*(square of length of route v)] i.e. for every used vehicle, we add the linear factor as fixed cost, and subtract the square of the route length multiplied by the quadratic factor. This second term aims at making the routes as dense as possible.
Sets the linear and quadratic cost factor of all vehicles.
5576 def SetAmortizedCostFactorsOfVehicle(self, linear_cost_factor, quadratic_cost_factor, vehicle): 5577 r"""Sets the linear and quadratic cost factor of the given vehicle.""" 5578 return _pywrapcp.RoutingModel_SetAmortizedCostFactorsOfVehicle(self, linear_cost_factor, quadratic_cost_factor, vehicle)
Sets the linear and quadratic cost factor of the given vehicle.
5595 def SetFirstSolutionEvaluator(self, evaluator): 5596 r""" 5597 Gets/sets the evaluator used during the search. Only relevant when 5598 RoutingSearchParameters.first_solution_strategy = EVALUATOR_STRATEGY. 5599 Takes ownership of evaluator. 5600 """ 5601 return _pywrapcp.RoutingModel_SetFirstSolutionEvaluator(self, evaluator)
Gets/sets the evaluator used during the search. Only relevant when RoutingSearchParameters.first_solution_strategy = EVALUATOR_STRATEGY. Takes ownership of evaluator.
5603 def SetFirstSolutionHint(self, hint): 5604 r""" 5605 Adds a hint to be used by first solution strategies. The hint assignment 5606 must outlive the search. 5607 As of 2024-12, only used by LOCAL_CHEAPEST_INSERTION and 5608 LOCAL_CHEAPEST_COST_INSERTION. 5609 """ 5610 return _pywrapcp.RoutingModel_SetFirstSolutionHint(self, hint)
Adds a hint to be used by first solution strategies. The hint assignment must outlive the search. As of 2024-12, only used by LOCAL_CHEAPEST_INSERTION and LOCAL_CHEAPEST_COST_INSERTION.
5612 def GetFirstSolutionHint(self): 5613 r"""Returns the current hint assignment.""" 5614 return _pywrapcp.RoutingModel_GetFirstSolutionHint(self)
Returns the current hint assignment.
5616 def AddLocalSearchOperator(self, ls_operator): 5617 r""" 5618 Adds a local search operator to the set of operators used to solve the 5619 vehicle routing problem. 5620 """ 5621 return _pywrapcp.RoutingModel_AddLocalSearchOperator(self, ls_operator)
Adds a local search operator to the set of operators used to solve the vehicle routing problem.
5623 def AddSearchMonitor(self, monitor): 5624 r"""Adds a search monitor to the search used to solve the routing model.""" 5625 return _pywrapcp.RoutingModel_AddSearchMonitor(self, monitor)
Adds a search monitor to the search used to solve the routing model.
5630 def AddAtSolutionCallback(self, callback, track_unchecked_neighbors=False): 5631 r""" 5632 Adds a callback called each time a solution is found during the search. 5633 This is a shortcut to creating a monitor to call the callback on 5634 AtSolution() and adding it with AddSearchMonitor. 5635 If track_unchecked_neighbors is true, the callback will also be called on 5636 AcceptUncheckedNeighbor() events, which is useful to grab solutions 5637 obtained when solver_parameters.check_solution_period > 1 (aka fastLS). 5638 """ 5639 return _pywrapcp.RoutingModel_AddAtSolutionCallback(self, callback, track_unchecked_neighbors)
Adds a callback called each time a solution is found during the search. This is a shortcut to creating a monitor to call the callback on AtSolution() and adding it with AddSearchMonitor. If track_unchecked_neighbors is true, the callback will also be called on AcceptUncheckedNeighbor() events, which is useful to grab solutions obtained when solver_parameters.check_solution_period > 1 (aka fastLS).
5644 def AddVariableMinimizedByFinalizer(self, var): 5645 r""" 5646 Adds a variable to minimize in the solution finalizer. The solution 5647 finalizer is called each time a solution is found during the search and 5648 allows to instantiate secondary variables (such as dimension cumul 5649 variables). 5650 """ 5651 return _pywrapcp.RoutingModel_AddVariableMinimizedByFinalizer(self, var)
Adds a variable to minimize in the solution finalizer. The solution finalizer is called each time a solution is found during the search and allows to instantiate secondary variables (such as dimension cumul variables).
5653 def AddVariableMaximizedByFinalizer(self, var): 5654 r""" 5655 Adds a variable to maximize in the solution finalizer (see above for 5656 information on the solution finalizer). 5657 """ 5658 return _pywrapcp.RoutingModel_AddVariableMaximizedByFinalizer(self, var)
Adds a variable to maximize in the solution finalizer (see above for information on the solution finalizer).
5660 def AddWeightedVariableMinimizedByFinalizer(self, var, cost): 5661 r""" 5662 Adds a variable to minimize in the solution finalizer, with a weighted 5663 priority: the higher the more priority it has. 5664 """ 5665 return _pywrapcp.RoutingModel_AddWeightedVariableMinimizedByFinalizer(self, var, cost)
Adds a variable to minimize in the solution finalizer, with a weighted priority: the higher the more priority it has.
5667 def AddWeightedVariableMaximizedByFinalizer(self, var, cost): 5668 r""" 5669 Adds a variable to maximize in the solution finalizer, with a weighted 5670 priority: the higher the more priority it has. 5671 """ 5672 return _pywrapcp.RoutingModel_AddWeightedVariableMaximizedByFinalizer(self, var, cost)
Adds a variable to maximize in the solution finalizer, with a weighted priority: the higher the more priority it has.
5674 def AddVariableTargetToFinalizer(self, var, target): 5675 r""" 5676 Add a variable to set the closest possible to the target value in the 5677 solution finalizer. 5678 """ 5679 return _pywrapcp.RoutingModel_AddVariableTargetToFinalizer(self, var, target)
Add a variable to set the closest possible to the target value in the solution finalizer.
5681 def AddWeightedVariableTargetToFinalizer(self, var, target, cost): 5682 r""" 5683 Same as above with a weighted priority: the higher the cost, the more 5684 priority it has to be set close to the target value. 5685 """ 5686 return _pywrapcp.RoutingModel_AddWeightedVariableTargetToFinalizer(self, var, target, cost)
Same as above with a weighted priority: the higher the cost, the more priority it has to be set close to the target value.
5688 def CloseModel(self): 5689 r""" 5690 Closes the current routing model; after this method is called, no 5691 modification to the model can be done, but RoutesToAssignment becomes 5692 available. Note that CloseModel() is automatically called by Solve() and 5693 other methods that produce solution. 5694 This is equivalent to calling 5695 CloseModelWithParameters(DefaultRoutingSearchParameters()). 5696 """ 5697 return _pywrapcp.RoutingModel_CloseModel(self)
Closes the current routing model; after this method is called, no modification to the model can be done, but RoutesToAssignment becomes available. Note that CloseModel() is automatically called by Solve() and other methods that produce solution. This is equivalent to calling CloseModelWithParameters(DefaultRoutingSearchParameters()).
5699 def CloseModelWithParameters(self, search_parameters): 5700 r""" 5701 Same as above taking search parameters (as of 10/2015 some the parameters 5702 have to be set when closing the model). 5703 """ 5704 return _pywrapcp.RoutingModel_CloseModelWithParameters(self, search_parameters)
Same as above taking search parameters (as of 10/2015 some the parameters have to be set when closing the model).
5706 def Solve(self, assignment=None): 5707 r""" 5708 Solves the current routing model; closes the current model. 5709 This is equivalent to calling 5710 SolveWithParameters(DefaultRoutingSearchParameters()) 5711 or 5712 SolveFromAssignmentWithParameters(assignment, 5713 DefaultRoutingSearchParameters()). 5714 """ 5715 return _pywrapcp.RoutingModel_Solve(self, assignment)
Solves the current routing model; closes the current model. This is equivalent to calling SolveWithParameters(DefaultRoutingSearchParameters()) or SolveFromAssignmentWithParameters(assignment, DefaultRoutingSearchParameters()).
5717 def SolveWithParameters(self, search_parameters, solutions=None): 5718 r""" 5719 Solves the current routing model with the given parameters. If 'solutions' 5720 is specified, it will contain the k best solutions found during the search 5721 (from worst to best, including the one returned by this method), where k 5722 corresponds to the 'number_of_solutions_to_collect' in 5723 'search_parameters'. Note that the Assignment returned by the method and 5724 the ones in solutions are owned by the underlying solver and should not be 5725 deleted. 5726 """ 5727 return _pywrapcp.RoutingModel_SolveWithParameters(self, search_parameters, solutions)
Solves the current routing model with the given parameters. If 'solutions' is specified, it will contain the k best solutions found during the search (from worst to best, including the one returned by this method), where k corresponds to the 'number_of_solutions_to_collect' in 'search_parameters'. Note that the Assignment returned by the method and the ones in solutions are owned by the underlying solver and should not be deleted.
5729 def SolveFromAssignmentWithParameters(self, assignment, search_parameters, solutions=None): 5730 r""" 5731 Same as above, except that if assignment is not null, it will be used as 5732 the initial solution. 5733 """ 5734 return _pywrapcp.RoutingModel_SolveFromAssignmentWithParameters(self, assignment, search_parameters, solutions)
Same as above, except that if assignment is not null, it will be used as the initial solution.
5736 def FastSolveFromAssignmentWithParameters(self, assignment, search_parameters, check_solution_in_cp, touched=None): 5737 r""" 5738 Improves a given assignment using unchecked local search. 5739 If check_solution_in_cp is true the final solution will be checked with 5740 the CP solver. 5741 As of 11/2023, only works with greedy descent. 5742 """ 5743 return _pywrapcp.RoutingModel_FastSolveFromAssignmentWithParameters(self, assignment, search_parameters, check_solution_in_cp, touched)
Improves a given assignment using unchecked local search. If check_solution_in_cp is true the final solution will be checked with the CP solver. As of 11/2023, only works with greedy descent.
5745 def SolveFromAssignmentsWithParameters(self, assignments, search_parameters, solutions=None): 5746 r""" 5747 Same as above but will try all assignments in order as first solutions 5748 until one succeeds. 5749 """ 5750 return _pywrapcp.RoutingModel_SolveFromAssignmentsWithParameters(self, assignments, search_parameters, solutions)
Same as above but will try all assignments in order as first solutions until one succeeds.
5752 def SolveWithIteratedLocalSearch(self, search_parameters): 5753 r""" 5754 Solves the current routing model by using an Iterated Local Search 5755 approach. 5756 """ 5757 return _pywrapcp.RoutingModel_SolveWithIteratedLocalSearch(self, search_parameters)
Solves the current routing model by using an Iterated Local Search approach.
5759 def SetAssignmentFromOtherModelAssignment(self, target_assignment, source_model, source_assignment): 5760 r""" 5761 Given a "source_model" and its "source_assignment", resets 5762 "target_assignment" with the IntVar variables (nexts_, and vehicle_vars_ 5763 if costs aren't homogeneous across vehicles) of "this" model, with the 5764 values set according to those in "other_assignment". 5765 The objective_element of target_assignment is set to this->cost_. 5766 """ 5767 return _pywrapcp.RoutingModel_SetAssignmentFromOtherModelAssignment(self, target_assignment, source_model, source_assignment)
Given a "source_model" and its "source_assignment", resets "target_assignment" with the IntVar variables (nexts_, and vehicle_vars_ if costs aren't homogeneous across vehicles) of "this" model, with the values set according to those in "other_assignment". The objective_element of target_assignment is set to this->cost_.
5769 def GetSubSolverStatistics(self): 5770 r"""Returns detailed search statistics.""" 5771 return _pywrapcp.RoutingModel_GetSubSolverStatistics(self)
Returns detailed search statistics.
5773 def ComputeLowerBound(self): 5774 r""" 5775 Computes a lower bound to the routing problem solving a linear assignment 5776 problem. The routing model must be closed before calling this method. 5777 Note that problems with node disjunction constraints (including optional 5778 nodes) and non-homogenous costs are not supported (the method returns 0 in 5779 these cases). 5780 """ 5781 return _pywrapcp.RoutingModel_ComputeLowerBound(self)
Computes a lower bound to the routing problem solving a linear assignment problem. The routing model must be closed before calling this method. Note that problems with node disjunction constraints (including optional nodes) and non-homogenous costs are not supported (the method returns 0 in these cases).
5783 def objective_lower_bound(self): 5784 r""" 5785 Returns the current lower bound found by internal solvers during the 5786 search. 5787 """ 5788 return _pywrapcp.RoutingModel_objective_lower_bound(self)
Returns the current lower bound found by internal solvers during the search.
5790 def status(self): 5791 r"""Returns the current status of the routing model.""" 5792 return _pywrapcp.RoutingModel_status(self)
Returns the current status of the routing model.
5794 def search_stats(self): 5795 r"""Returns search statistics.""" 5796 return _pywrapcp.RoutingModel_search_stats(self)
Returns search statistics.
5798 def enable_deep_serialization(self): 5799 r"""Returns the value of the internal enable_deep_serialization_ parameter.""" 5800 return _pywrapcp.RoutingModel_enable_deep_serialization(self)
Returns the value of the internal enable_deep_serialization_ parameter.
5802 def ApplyLocks(self, locks): 5803 r""" 5804 Applies a lock chain to the next search. 'locks' represents an ordered 5805 vector of nodes representing a partial route which will be fixed during 5806 the next search; it will constrain next variables such that: 5807 next[locks[i]] == locks[i+1]. 5808 5809 Returns the next variable at the end of the locked chain; this variable is 5810 not locked. An assignment containing the locks can be obtained by calling 5811 PreAssignment(). 5812 """ 5813 return _pywrapcp.RoutingModel_ApplyLocks(self, locks)
Applies a lock chain to the next search. 'locks' represents an ordered vector of nodes representing a partial route which will be fixed during the next search; it will constrain next variables such that: next[locks[i]] == locks[i+1].
Returns the next variable at the end of the locked chain; this variable is not locked. An assignment containing the locks can be obtained by calling PreAssignment().
5815 def ApplyLocksToAllVehicles(self, locks, close_routes): 5816 r""" 5817 Applies lock chains to all vehicles to the next search, such that locks[p] 5818 is the lock chain for route p. Returns false if the locks do not contain 5819 valid routes; expects that the routes do not contain the depots, 5820 i.e. there are empty vectors in place of empty routes. 5821 If close_routes is set to true, adds the end nodes to the route of each 5822 vehicle and deactivates other nodes. 5823 An assignment containing the locks can be obtained by calling 5824 PreAssignment(). 5825 """ 5826 return _pywrapcp.RoutingModel_ApplyLocksToAllVehicles(self, locks, close_routes)
Applies lock chains to all vehicles to the next search, such that locks[p] is the lock chain for route p. Returns false if the locks do not contain valid routes; expects that the routes do not contain the depots, i.e. there are empty vectors in place of empty routes. If close_routes is set to true, adds the end nodes to the route of each vehicle and deactivates other nodes. An assignment containing the locks can be obtained by calling PreAssignment().
5828 def PreAssignment(self): 5829 r""" 5830 Returns an assignment used to fix some of the variables of the problem. 5831 In practice, this assignment locks partial routes of the problem. This 5832 can be used in the context of locking the parts of the routes which have 5833 already been driven in online routing problems. 5834 """ 5835 return _pywrapcp.RoutingModel_PreAssignment(self)
Returns an assignment used to fix some of the variables of the problem. In practice, this assignment locks partial routes of the problem. This can be used in the context of locking the parts of the routes which have already been driven in online routing problems.
5840 def WriteAssignment(self, file_name): 5841 r""" 5842 Writes the current solution to a file containing an AssignmentProto. 5843 Returns false if the file cannot be opened or if there is no current 5844 solution. 5845 """ 5846 return _pywrapcp.RoutingModel_WriteAssignment(self, file_name)
Writes the current solution to a file containing an AssignmentProto. Returns false if the file cannot be opened or if there is no current solution.
5848 def ReadAssignment(self, file_name): 5849 r""" 5850 Reads an assignment from a file and returns the current solution. 5851 Returns nullptr if the file cannot be opened or if the assignment is not 5852 valid. 5853 """ 5854 return _pywrapcp.RoutingModel_ReadAssignment(self, file_name)
Reads an assignment from a file and returns the current solution. Returns nullptr if the file cannot be opened or if the assignment is not valid.
5856 def RestoreAssignment(self, solution): 5857 r""" 5858 Restores an assignment as a solution in the routing model and returns the 5859 new solution. Returns nullptr if the assignment is not valid. 5860 """ 5861 return _pywrapcp.RoutingModel_RestoreAssignment(self, solution)
Restores an assignment as a solution in the routing model and returns the new solution. Returns nullptr if the assignment is not valid.
5863 def ReadAssignmentFromRoutes(self, routes, ignore_inactive_indices): 5864 r""" 5865 Restores the routes as the current solution. Returns nullptr if the 5866 solution cannot be restored (routes do not contain a valid solution). Note 5867 that calling this method will run the solver to assign values to the 5868 dimension variables; this may take considerable amount of time, especially 5869 when using dimensions with slack. 5870 """ 5871 return _pywrapcp.RoutingModel_ReadAssignmentFromRoutes(self, routes, ignore_inactive_indices)
Restores the routes as the current solution. Returns nullptr if the solution cannot be restored (routes do not contain a valid solution). Note that calling this method will run the solver to assign values to the dimension variables; this may take considerable amount of time, especially when using dimensions with slack.
5873 def RoutesToAssignment(self, routes, ignore_inactive_indices, close_routes, assignment): 5874 r""" 5875 Fills an assignment from a specification of the routes of the 5876 vehicles. The routes are specified as lists of variable indices that 5877 appear on the routes of the vehicles. The indices of the outer vector in 5878 'routes' correspond to vehicles IDs, the inner vector contains the 5879 variable indices on the routes for the given vehicle. The inner vectors 5880 must not contain the start and end indices, as these are determined by the 5881 routing model. Sets the value of NextVars in the assignment, adding the 5882 variables to the assignment if necessary. The method does not touch other 5883 variables in the assignment. The method can only be called after the model 5884 is closed. With ignore_inactive_indices set to false, this method will 5885 fail (return nullptr) in case some of the route contain indices that are 5886 deactivated in the model; when set to true, these indices will be 5887 skipped. Returns true if routes were successfully 5888 loaded. However, such assignment still might not be a valid 5889 solution to the routing problem due to more complex constraints; 5890 it is advisible to call solver()->CheckSolution() afterwards. 5891 """ 5892 return _pywrapcp.RoutingModel_RoutesToAssignment(self, routes, ignore_inactive_indices, close_routes, assignment)
Fills an assignment from a specification of the routes of the vehicles. The routes are specified as lists of variable indices that appear on the routes of the vehicles. The indices of the outer vector in 'routes' correspond to vehicles IDs, the inner vector contains the variable indices on the routes for the given vehicle. The inner vectors must not contain the start and end indices, as these are determined by the routing model. Sets the value of NextVars in the assignment, adding the variables to the assignment if necessary. The method does not touch other variables in the assignment. The method can only be called after the model is closed. With ignore_inactive_indices set to false, this method will fail (return nullptr) in case some of the route contain indices that are deactivated in the model; when set to true, these indices will be skipped. Returns true if routes were successfully loaded. However, such assignment still might not be a valid solution to the routing problem due to more complex constraints; it is advisible to call solver()->CheckSolution() afterwards.
5894 def AssignmentToRoutes(self, assignment, routes): 5895 r""" 5896 Converts the solution in the given assignment to routes for all vehicles. 5897 Expects that assignment contains a valid solution (i.e. routes for all 5898 vehicles end with an end index for that vehicle). 5899 """ 5900 return _pywrapcp.RoutingModel_AssignmentToRoutes(self, assignment, routes)
Converts the solution in the given assignment to routes for all vehicles. Expects that assignment contains a valid solution (i.e. routes for all vehicles end with an end index for that vehicle).
5902 def CompactAssignment(self, assignment): 5903 r""" 5904 Converts the solution in the given assignment to routes for all vehicles. 5905 If the returned vector is route_indices, route_indices[i][j] is the index 5906 for jth location visited on route i. Note that contrary to 5907 AssignmentToRoutes, the vectors do include start and end locations. 5908 Returns a compacted version of the given assignment, in which all vehicles 5909 with id lower or equal to some N have non-empty routes, and all vehicles 5910 with id greater than N have empty routes. Does not take ownership of the 5911 returned object. 5912 If found, the cost of the compact assignment is the same as in the 5913 original assignment and it preserves the values of 'active' variables. 5914 Returns nullptr if a compact assignment was not found. 5915 This method only works in homogenous mode, and it only swaps equivalent 5916 vehicles (vehicles with the same start and end nodes). When creating the 5917 compact assignment, the empty plan is replaced by the route assigned to 5918 the compatible vehicle with the highest id. Note that with more complex 5919 constraints on vehicle variables, this method might fail even if a compact 5920 solution exists. 5921 This method changes the vehicle and dimension variables as necessary. 5922 While compacting the solution, only basic checks on vehicle variables are 5923 performed; if one of these checks fails no attempts to repair it are made 5924 (instead, the method returns nullptr). 5925 """ 5926 return _pywrapcp.RoutingModel_CompactAssignment(self, assignment)
Converts the solution in the given assignment to routes for all vehicles. If the returned vector is route_indices, route_indices[i][j] is the index for jth location visited on route i. Note that contrary to AssignmentToRoutes, the vectors do include start and end locations. Returns a compacted version of the given assignment, in which all vehicles with id lower or equal to some N have non-empty routes, and all vehicles with id greater than N have empty routes. Does not take ownership of the returned object. If found, the cost of the compact assignment is the same as in the original assignment and it preserves the values of 'active' variables. Returns nullptr if a compact assignment was not found. This method only works in homogenous mode, and it only swaps equivalent vehicles (vehicles with the same start and end nodes). When creating the compact assignment, the empty plan is replaced by the route assigned to the compatible vehicle with the highest id. Note that with more complex constraints on vehicle variables, this method might fail even if a compact solution exists. This method changes the vehicle and dimension variables as necessary. While compacting the solution, only basic checks on vehicle variables are performed; if one of these checks fails no attempts to repair it are made (instead, the method returns nullptr).
5928 def CompactAndCheckAssignment(self, assignment): 5929 r""" 5930 Same as CompactAssignment() but also checks the validity of the final 5931 compact solution; if it is not valid, no attempts to repair it are made 5932 (instead, the method returns nullptr). 5933 """ 5934 return _pywrapcp.RoutingModel_CompactAndCheckAssignment(self, assignment)
Same as CompactAssignment() but also checks the validity of the final compact solution; if it is not valid, no attempts to repair it are made (instead, the method returns nullptr).
5936 def AddToAssignment(self, var): 5937 r"""Adds an extra variable to the vehicle routing assignment.""" 5938 return _pywrapcp.RoutingModel_AddToAssignment(self, var)
Adds an extra variable to the vehicle routing assignment.
5943 def PackCumulsOfOptimizerDimensionsFromAssignment(self, original_assignment, duration_limit, time_limit_was_reached=None): 5944 r""" 5945 For every dimension in the model with an optimizer in 5946 local/global_dimension_optimizers_, this method tries to pack the cumul 5947 values of the dimension, such that: 5948 - The cumul costs (span costs, soft lower and upper bound costs, etc) are 5949 minimized. 5950 - The cumuls of the ends of the routes are minimized for this given 5951 minimal cumul cost. 5952 - Given these minimal end cumuls, the route start cumuls are maximized. 5953 Returns the assignment resulting from allocating these packed cumuls with 5954 the solver, and nullptr if these cumuls could not be set by the solver. 5955 """ 5956 return _pywrapcp.RoutingModel_PackCumulsOfOptimizerDimensionsFromAssignment(self, original_assignment, duration_limit, time_limit_was_reached)
For every dimension in the model with an optimizer in local/global_dimension_optimizers_, this method tries to pack the cumul values of the dimension, such that:
- The cumul costs (span costs, soft lower and upper bound costs, etc) are minimized.
- The cumuls of the ends of the routes are minimized for this given minimal cumul cost.
- Given these minimal end cumuls, the route start cumuls are maximized. Returns the assignment resulting from allocating these packed cumuls with the solver, and nullptr if these cumuls could not be set by the solver.
5958 def GetOrCreateNodeNeighborsByCostClass(self, *args): 5959 r""" 5960 *Overload 1:* 5961 Returns neighbors of all nodes for every cost class. The result is cached 5962 and is computed once. The number of neighbors considered is based on a 5963 ratio of non-vehicle nodes, specified by neighbors_ratio, with a minimum 5964 of min-neighbors node considered. 5965 5966 | 5967 5968 *Overload 2:* 5969 Returns parameters.num_neighbors neighbors of all nodes for every cost 5970 class. The result is cached and is computed once. 5971 """ 5972 return _pywrapcp.RoutingModel_GetOrCreateNodeNeighborsByCostClass(self, *args)
Overload 1: Returns neighbors of all nodes for every cost class. The result is cached and is computed once. The number of neighbors considered is based on a ratio of non-vehicle nodes, specified by neighbors_ratio, with a minimum of min-neighbors node considered.
|
Overload 2: Returns parameters.num_neighbors neighbors of all nodes for every cost class. The result is cached and is computed once.
5974 def AddLocalSearchFilter(self, filter): 5975 r""" 5976 Adds a custom local search filter to the list of filters used to speed up 5977 local search by pruning unfeasible variable assignments. 5978 Calling this method after the routing model has been closed (CloseModel() 5979 or Solve() has been called) has no effect. 5980 The routing model does not take ownership of the filter. 5981 """ 5982 return _pywrapcp.RoutingModel_AddLocalSearchFilter(self, filter)
Adds a custom local search filter to the list of filters used to speed up local search by pruning unfeasible variable assignments. Calling this method after the routing model has been closed (CloseModel() or Solve() has been called) has no effect. The routing model does not take ownership of the filter.
5984 def Start(self, vehicle): 5985 r""" 5986 Model inspection. 5987 Returns the variable index of the starting node of a vehicle route. 5988 """ 5989 return _pywrapcp.RoutingModel_Start(self, vehicle)
Model inspection. Returns the variable index of the starting node of a vehicle route.
5991 def End(self, vehicle): 5992 r"""Returns the variable index of the ending node of a vehicle route.""" 5993 return _pywrapcp.RoutingModel_End(self, vehicle)
Returns the variable index of the ending node of a vehicle route.
5995 def IsStart(self, index): 5996 r"""Returns true if 'index' represents the first node of a route.""" 5997 return _pywrapcp.RoutingModel_IsStart(self, index)
Returns true if 'index' represents the first node of a route.
5999 def IsEnd(self, index): 6000 r"""Returns true if 'index' represents the last node of a route.""" 6001 return _pywrapcp.RoutingModel_IsEnd(self, index)
Returns true if 'index' represents the last node of a route.
6003 def VehicleIndex(self, index): 6004 r""" 6005 Returns the vehicle of the given start/end index, and -1 if the given 6006 index is not a vehicle start/end. 6007 """ 6008 return _pywrapcp.RoutingModel_VehicleIndex(self, index)
Returns the vehicle of the given start/end index, and -1 if the given index is not a vehicle start/end.
6010 def Next(self, assignment, index): 6011 r""" 6012 Assignment inspection 6013 Returns the variable index of the node directly after the node 6014 corresponding to 'index' in 'assignment'. 6015 """ 6016 return _pywrapcp.RoutingModel_Next(self, assignment, index)
Assignment inspection Returns the variable index of the node directly after the node corresponding to 'index' in 'assignment'.
6018 def IsVehicleUsed(self, assignment, vehicle): 6019 r"""Returns true if the route of 'vehicle' is non empty in 'assignment'.""" 6020 return _pywrapcp.RoutingModel_IsVehicleUsed(self, assignment, vehicle)
Returns true if the route of 'vehicle' is non empty in 'assignment'.
6022 def NextVar(self, index): 6023 r""" 6024 Returns the next variable of the node corresponding to index. Note that 6025 NextVar(index) == index is equivalent to ActiveVar(index) == 0. 6026 """ 6027 return _pywrapcp.RoutingModel_NextVar(self, index)
Returns the next variable of the node corresponding to index. Note that NextVar(index) == index is equivalent to ActiveVar(index) == 0.
6029 def ActiveVar(self, index): 6030 r"""Returns the active variable of the node corresponding to index.""" 6031 return _pywrapcp.RoutingModel_ActiveVar(self, index)
Returns the active variable of the node corresponding to index.
6033 def ActiveVehicleVar(self, vehicle): 6034 r""" 6035 Returns the active variable of the vehicle. It will be equal to 1 iff the 6036 route of the vehicle is not empty, 0 otherwise. 6037 """ 6038 return _pywrapcp.RoutingModel_ActiveVehicleVar(self, vehicle)
Returns the active variable of the vehicle. It will be equal to 1 iff the route of the vehicle is not empty, 0 otherwise.
6040 def VehicleRouteConsideredVar(self, vehicle): 6041 r""" 6042 Returns the variable specifying whether or not the given vehicle route is 6043 considered for costs and constraints. It will be equal to 1 iff the route 6044 of the vehicle is not empty OR vehicle_used_when_empty_[vehicle] is true. 6045 """ 6046 return _pywrapcp.RoutingModel_VehicleRouteConsideredVar(self, vehicle)
Returns the variable specifying whether or not the given vehicle route is considered for costs and constraints. It will be equal to 1 iff the route of the vehicle is not empty OR vehicle_used_when_empty_[vehicle] is true.
6048 def VehicleVar(self, index): 6049 r""" 6050 Returns the vehicle variable of the node corresponding to index. Note that 6051 VehicleVar(index) == -1 is equivalent to ActiveVar(index) == 0. 6052 """ 6053 return _pywrapcp.RoutingModel_VehicleVar(self, index)
Returns the vehicle variable of the node corresponding to index. Note that VehicleVar(index) == -1 is equivalent to ActiveVar(index) == 0.
6055 def ResourceVar(self, vehicle, resource_group): 6056 r""" 6057 Returns the resource variable for the given vehicle index in the given 6058 resource group. If a vehicle doesn't require a resource from the 6059 corresponding resource group, then ResourceVar(v, r_g) == -1. 6060 """ 6061 return _pywrapcp.RoutingModel_ResourceVar(self, vehicle, resource_group)
Returns the resource variable for the given vehicle index in the given resource group. If a vehicle doesn't require a resource from the corresponding resource group, then ResourceVar(v, r_g) == -1.
6063 def CostVar(self): 6064 r"""Returns the global cost variable which is being minimized.""" 6065 return _pywrapcp.RoutingModel_CostVar(self)
Returns the global cost variable which is being minimized.
6067 def GetArcCostForVehicle(self, from_index, to_index, vehicle): 6068 r""" 6069 Returns the cost of the transit arc between two nodes for a given vehicle. 6070 Input are variable indices of node. This returns 0 if vehicle < 0. 6071 """ 6072 return _pywrapcp.RoutingModel_GetArcCostForVehicle(self, from_index, to_index, vehicle)
Returns the cost of the transit arc between two nodes for a given vehicle. Input are variable indices of node. This returns 0 if vehicle < 0.
6074 def CostsAreHomogeneousAcrossVehicles(self): 6075 r"""Whether costs are homogeneous across all vehicles.""" 6076 return _pywrapcp.RoutingModel_CostsAreHomogeneousAcrossVehicles(self)
Whether costs are homogeneous across all vehicles.
6078 def GetHomogeneousCost(self, from_index, to_index): 6079 r""" 6080 Returns the cost of the segment between two nodes supposing all vehicle 6081 costs are the same (returns the cost for the first vehicle otherwise). 6082 """ 6083 return _pywrapcp.RoutingModel_GetHomogeneousCost(self, from_index, to_index)
Returns the cost of the segment between two nodes supposing all vehicle costs are the same (returns the cost for the first vehicle otherwise).
6085 def GetArcCostForFirstSolution(self, from_index, to_index): 6086 r""" 6087 Returns the cost of the arc in the context of the first solution strategy. 6088 This is typically a simplification of the actual cost; see the .cc. 6089 """ 6090 return _pywrapcp.RoutingModel_GetArcCostForFirstSolution(self, from_index, to_index)
Returns the cost of the arc in the context of the first solution strategy. This is typically a simplification of the actual cost; see the .cc.
6092 def GetArcCostForClass(self, from_index, to_index, cost_class_index): 6093 r""" 6094 Returns the cost of the segment between two nodes for a given cost 6095 class. Input are variable indices of nodes and the cost class. 6096 Unlike GetArcCostForVehicle(), if cost_class is kNoCost, then the 6097 returned cost won't necessarily be zero: only some of the components 6098 of the cost that depend on the cost class will be omited. See the code 6099 for details. 6100 """ 6101 return _pywrapcp.RoutingModel_GetArcCostForClass(self, from_index, to_index, cost_class_index)
Returns the cost of the segment between two nodes for a given cost class. Input are variable indices of nodes and the cost class. Unlike GetArcCostForVehicle(), if cost_class is kNoCost, then the returned cost won't necessarily be zero: only some of the components of the cost that depend on the cost class will be omited. See the code for details.
6103 def GetCostClassIndexOfVehicle(self, vehicle): 6104 r"""Get the cost class index of the given vehicle.""" 6105 return _pywrapcp.RoutingModel_GetCostClassIndexOfVehicle(self, vehicle)
Get the cost class index of the given vehicle.
6107 def HasVehicleWithCostClassIndex(self, cost_class_index): 6108 r""" 6109 Returns true iff the model contains a vehicle with the given 6110 cost_class_index. 6111 """ 6112 return _pywrapcp.RoutingModel_HasVehicleWithCostClassIndex(self, cost_class_index)
Returns true iff the model contains a vehicle with the given cost_class_index.
6114 def GetCostClassesCount(self): 6115 r"""Returns the number of different cost classes in the model.""" 6116 return _pywrapcp.RoutingModel_GetCostClassesCount(self)
Returns the number of different cost classes in the model.
6118 def GetNonZeroCostClassesCount(self): 6119 r"""Ditto, minus the 'always zero', built-in cost class.""" 6120 return _pywrapcp.RoutingModel_GetNonZeroCostClassesCount(self)
Ditto, minus the 'always zero', built-in cost class.
6125 def GetVehicleOfClass(self, vehicle_class): 6126 r""" 6127 Returns a vehicle of the given vehicle class, and -1 if there are no 6128 vehicles for this class. 6129 """ 6130 return _pywrapcp.RoutingModel_GetVehicleOfClass(self, vehicle_class)
Returns a vehicle of the given vehicle class, and -1 if there are no vehicles for this class.
6132 def GetVehicleClassesCount(self): 6133 r"""Returns the number of different vehicle classes in the model.""" 6134 return _pywrapcp.RoutingModel_GetVehicleClassesCount(self)
Returns the number of different vehicle classes in the model.
6136 def GetSameVehicleIndicesOfIndex(self, node): 6137 r"""Returns variable indices of nodes constrained to be on the same route.""" 6138 return _pywrapcp.RoutingModel_GetSameVehicleIndicesOfIndex(self, node)
Returns variable indices of nodes constrained to be on the same route.
6143 def GetSameActivityIndicesOfIndex(self, node): 6144 r"""Returns variable indices of nodes constrained to have the same activity.""" 6145 return _pywrapcp.RoutingModel_GetSameActivityIndicesOfIndex(self, node)
Returns variable indices of nodes constrained to have the same activity.
6147 def GetSameActivityGroupOfIndex(self, node): 6148 r"""Returns the same activity group of the node.""" 6149 return _pywrapcp.RoutingModel_GetSameActivityGroupOfIndex(self, node)
Returns the same activity group of the node.
6151 def GetSameActivityGroups(self): 6152 r"""Returns same activity groups of all nodes.""" 6153 return _pywrapcp.RoutingModel_GetSameActivityGroups(self)
Returns same activity groups of all nodes.
6155 def GetSameActivityGroupsCount(self): 6156 r"""Returns the number of same activity groups.""" 6157 return _pywrapcp.RoutingModel_GetSameActivityGroupsCount(self)
Returns the number of same activity groups.
6159 def GetSameActivityIndicesOfGroup(self, group): 6160 r"""Returns variable indices of nodes in the same activity group.""" 6161 return _pywrapcp.RoutingModel_GetSameActivityIndicesOfGroup(self, group)
Returns variable indices of nodes in the same activity group.
6166 def ArcIsMoreConstrainedThanArc(self, _from, to1, to2): 6167 r""" 6168 Returns whether the arc from->to1 is more constrained than from->to2, 6169 taking into account, in order: 6170 - whether the destination node isn't an end node 6171 - whether the destination node is mandatory 6172 - whether the destination node is bound to the same vehicle as the source 6173 - the "primary constrained" dimension (see SetPrimaryConstrainedDimension) 6174 It then breaks ties using, in order: 6175 - the arc cost (taking unperformed penalties into account) 6176 - the size of the vehicle vars of "to1" and "to2" (lowest size wins) 6177 - the value: the lowest value of the indices to1 and to2 wins. 6178 See the .cc for details. 6179 The more constrained arc is typically preferable when building a 6180 first solution. This method is intended to be used as a callback for the 6181 BestValueByComparisonSelector value selector. 6182 Args: 6183 from: the variable index of the source node 6184 to1: the variable index of the first candidate destination node. 6185 to2: the variable index of the second candidate destination node. 6186 """ 6187 return _pywrapcp.RoutingModel_ArcIsMoreConstrainedThanArc(self, _from, to1, to2)
Returns whether the arc from->to1 is more constrained than from->to2, taking into account, in order:
- whether the destination node isn't an end node
- whether the destination node is mandatory
- whether the destination node is bound to the same vehicle as the source
- the "primary constrained" dimension (see SetPrimaryConstrainedDimension) It then breaks ties using, in order:
- the arc cost (taking unperformed penalties into account)
- the size of the vehicle vars of "to1" and "to2" (lowest size wins)
- the value: the lowest value of the indices to1 and to2 wins. See the .cc for details. The more constrained arc is typically preferable when building a first solution. This method is intended to be used as a callback for the BestValueByComparisonSelector value selector.
Arguments:
- from: the variable index of the source node
- to1: the variable index of the first candidate destination node.
- to2: the variable index of the second candidate destination node.
6189 def DebugOutputAssignment(self, solution_assignment, dimension_to_print): 6190 r""" 6191 Print some debugging information about an assignment, including the 6192 feasible intervals of the CumulVar for dimension "dimension_to_print" 6193 at each step of the routes. 6194 If "dimension_to_print" is omitted, all dimensions will be printed. 6195 """ 6196 return _pywrapcp.RoutingModel_DebugOutputAssignment(self, solution_assignment, dimension_to_print)
Print some debugging information about an assignment, including the feasible intervals of the CumulVar for dimension "dimension_to_print" at each step of the routes. If "dimension_to_print" is omitted, all dimensions will be printed.
6198 def CheckIfAssignmentIsFeasible(self, assignment, call_at_solution_monitors): 6199 r""" 6200 Returns a vector cumul_bounds, for which cumul_bounds[i][j] is a pair 6201 containing the minimum and maximum of the CumulVar of the jth node on 6202 route i. 6203 - cumul_bounds[i][j].first is the minimum. 6204 - cumul_bounds[i][j].second is the maximum. 6205 Checks if an assignment is feasible. 6206 """ 6207 return _pywrapcp.RoutingModel_CheckIfAssignmentIsFeasible(self, assignment, call_at_solution_monitors)
Returns a vector cumul_bounds, for which cumul_bounds[i][j] is a pair containing the minimum and maximum of the CumulVar of the jth node on route i.
- cumul_bounds[i][j].first is the minimum.
- cumul_bounds[i][j].second is the maximum. Checks if an assignment is feasible.
6209 def solver(self): 6210 r""" 6211 Returns the underlying constraint solver. Can be used to add extra 6212 constraints and/or modify search algorithms. 6213 """ 6214 return _pywrapcp.RoutingModel_solver(self)
Returns the underlying constraint solver. Can be used to add extra constraints and/or modify search algorithms.
6216 def CheckLimit(self, *args): 6217 r""" 6218 Returns true if the search limit has been crossed with the given time 6219 offset. 6220 """ 6221 return _pywrapcp.RoutingModel_CheckLimit(self, *args)
Returns true if the search limit has been crossed with the given time offset.
6223 def RemainingTime(self): 6224 r"""Returns the time left in the search limit.""" 6225 return _pywrapcp.RoutingModel_RemainingTime(self)
Returns the time left in the search limit.
6227 def UpdateTimeLimit(self, time_limit): 6228 r"""Updates the time limit of the search limit.""" 6229 return _pywrapcp.RoutingModel_UpdateTimeLimit(self, time_limit)
Updates the time limit of the search limit.
6231 def TimeBuffer(self): 6232 r"""Returns the time buffer to safely return a solution.""" 6233 return _pywrapcp.RoutingModel_TimeBuffer(self)
Returns the time buffer to safely return a solution.
6235 def GetMutableCPSatInterrupt(self): 6236 r"""Returns the atomic<bool> to stop the CP-SAT solver.""" 6237 return _pywrapcp.RoutingModel_GetMutableCPSatInterrupt(self)
Returns the atomic
6239 def GetMutableCPInterrupt(self): 6240 r"""Returns the atomic<bool> to stop the CP solver.""" 6241 return _pywrapcp.RoutingModel_GetMutableCPInterrupt(self)
Returns the atomic
6243 def CancelSearch(self): 6244 r"""Cancels the current search.""" 6245 return _pywrapcp.RoutingModel_CancelSearch(self)
Cancels the current search.
6247 def nodes(self): 6248 r""" 6249 Sizes and indices 6250 Returns the number of nodes in the model. 6251 """ 6252 return _pywrapcp.RoutingModel_nodes(self)
Sizes and indices Returns the number of nodes in the model.
6254 def vehicles(self): 6255 r"""Returns the number of vehicle routes in the model.""" 6256 return _pywrapcp.RoutingModel_vehicles(self)
Returns the number of vehicle routes in the model.
6258 def Size(self): 6259 r"""Returns the number of next variables in the model.""" 6260 return _pywrapcp.RoutingModel_Size(self)
Returns the number of next variables in the model.
6262 def GetNumberOfDecisionsInFirstSolution(self, search_parameters): 6263 r""" 6264 Returns statistics on first solution search, number of decisions sent to 6265 filters, number of decisions rejected by filters. 6266 """ 6267 return _pywrapcp.RoutingModel_GetNumberOfDecisionsInFirstSolution(self, search_parameters)
Returns statistics on first solution search, number of decisions sent to filters, number of decisions rejected by filters.
6272 def GetAutomaticFirstSolutionStrategy(self): 6273 r"""Returns the automatic first solution strategy selected.""" 6274 return _pywrapcp.RoutingModel_GetAutomaticFirstSolutionStrategy(self)
Returns the automatic first solution strategy selected.
6276 def IsMatchingModel(self): 6277 r"""Returns true if a vehicle/node matching problem is detected.""" 6278 return _pywrapcp.RoutingModel_IsMatchingModel(self)
Returns true if a vehicle/node matching problem is detected.
6280 def AreRoutesInterdependent(self, parameters): 6281 r""" 6282 Returns true if routes are interdependent. This means that any 6283 modification to a route might impact another. 6284 """ 6285 return _pywrapcp.RoutingModel_AreRoutesInterdependent(self, parameters)
Returns true if routes are interdependent. This means that any modification to a route might impact another.
6287 def MakeGuidedSlackFinalizer(self, dimension, initializer): 6288 r""" 6289 The next few members are in the public section only for testing purposes. 6290 6291 MakeGuidedSlackFinalizer creates a DecisionBuilder for the slacks of a 6292 dimension using a callback to choose which values to start with. 6293 The finalizer works only when all next variables in the model have 6294 been fixed. It has the following two characteristics: 6295 1. It follows the routes defined by the nexts variables when choosing a 6296 variable to make a decision on. 6297 2. When it comes to choose a value for the slack of node i, the decision 6298 builder first calls the callback with argument i, and supposingly the 6299 returned value is x it creates decisions slack[i] = x, slack[i] = x + 6300 1, slack[i] = x - 1, slack[i] = x + 2, etc. 6301 """ 6302 return _pywrapcp.RoutingModel_MakeGuidedSlackFinalizer(self, dimension, initializer)
The next few members are in the public section only for testing purposes.
MakeGuidedSlackFinalizer creates a DecisionBuilder for the slacks of a dimension using a callback to choose which values to start with. The finalizer works only when all next variables in the model have been fixed. It has the following two characteristics:
- It follows the routes defined by the nexts variables when choosing a variable to make a decision on.
- When it comes to choose a value for the slack of node i, the decision builder first calls the callback with argument i, and supposingly the returned value is x it creates decisions slack[i] = x, slack[i] = x + 1, slack[i] = x - 1, slack[i] = x + 2, etc.
6304 def MakeSelfDependentDimensionFinalizer(self, dimension): 6305 r""" 6306 MakeSelfDependentDimensionFinalizer is a finalizer for the slacks of a 6307 self-dependent dimension. It makes an extensive use of the caches of the 6308 state dependent transits. 6309 In detail, MakeSelfDependentDimensionFinalizer returns a composition of a 6310 local search decision builder with a greedy descent operator for the cumul 6311 of the start of each route and a guided slack finalizer. Provided there 6312 are no time windows and the maximum slacks are large enough, once the 6313 cumul of the start of route is fixed, the guided finalizer can find 6314 optimal values of the slacks for the rest of the route in time 6315 proportional to the length of the route. Therefore the composed finalizer 6316 generally works in time O(log(t)*n*m), where t is the latest possible 6317 departute time, n is the number of nodes in the network and m is the 6318 number of vehicles. 6319 """ 6320 return _pywrapcp.RoutingModel_MakeSelfDependentDimensionFinalizer(self, dimension)
MakeSelfDependentDimensionFinalizer is a finalizer for the slacks of a self-dependent dimension. It makes an extensive use of the caches of the state dependent transits. In detail, MakeSelfDependentDimensionFinalizer returns a composition of a local search decision builder with a greedy descent operator for the cumul of the start of each route and a guided slack finalizer. Provided there are no time windows and the maximum slacks are large enough, once the cumul of the start of route is fixed, the guided finalizer can find optimal values of the slacks for the rest of the route in time proportional to the length of the route. Therefore the composed finalizer generally works in time O(log(t)nm), where t is the latest possible departute time, n is the number of nodes in the network and m is the number of vehicles.
6325 def GetVehiclesOfSameClass(self, start_end_index): 6326 r""" 6327 Returns indices of the vehicles which are in the same vehicle class as the 6328 vehicle starting or ending at start_end_index. 6329 """ 6330 return _pywrapcp.RoutingModel_GetVehiclesOfSameClass(self, start_end_index)
Returns indices of the vehicles which are in the same vehicle class as the vehicle starting or ending at start_end_index.
6332 def GetSameVehicleClassArcs(self, from_index, to_index): 6333 r""" 6334 Returns all arcs which are equivalent to the {from_index, to_index} arc 6335 wrt vehicle classes. Arcs will be returned only if from_index is the 6336 start of a vehicle or if to_index is the end of a vehicle. The returned 6337 arcs will then be starting or ending at start or end nodes of vehicles in 6338 the same vehicle class. The input arc is included in the returned vector. 6339 """ 6340 return _pywrapcp.RoutingModel_GetSameVehicleClassArcs(self, from_index, to_index)
Returns all arcs which are equivalent to the {from_index, to_index} arc wrt vehicle classes. Arcs will be returned only if from_index is the start of a vehicle or if to_index is the end of a vehicle. The returned arcs will then be starting or ending at start or end nodes of vehicles in the same vehicle class. The input arc is included in the returned vector.
6349class RoutingModelVisitor(BaseObject): 6350 r"""Routing model visitor.""" 6351 6352 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6353 __repr__ = _swig_repr 6354 6355 def __init__(self): 6356 _pywrapcp.RoutingModelVisitor_swiginit(self, _pywrapcp.new_RoutingModelVisitor()) 6357 __swig_destroy__ = _pywrapcp.delete_RoutingModelVisitor
Routing model visitor.
6352 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Inherited Members
6365class TypeRegulationsChecker(object): 6366 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6367 6368 def __init__(self, *args, **kwargs): 6369 raise AttributeError("No constructor defined - class is abstract") 6370 __repr__ = _swig_repr 6371 __swig_destroy__ = _pywrapcp.delete_TypeRegulationsChecker 6372 6373 def CheckVehicle(self, vehicle, next_accessor): 6374 return _pywrapcp.TypeRegulationsChecker_CheckVehicle(self, vehicle, next_accessor)
6366 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
6378class TypeIncompatibilityChecker(TypeRegulationsChecker): 6379 r"""Checker for type incompatibilities.""" 6380 6381 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6382 __repr__ = _swig_repr 6383 6384 def __init__(self, model, check_hard_incompatibilities): 6385 _pywrapcp.TypeIncompatibilityChecker_swiginit(self, _pywrapcp.new_TypeIncompatibilityChecker(model, check_hard_incompatibilities)) 6386 __swig_destroy__ = _pywrapcp.delete_TypeIncompatibilityChecker
Checker for type incompatibilities.
6381 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Inherited Members
6390class TypeRequirementChecker(TypeRegulationsChecker): 6391 r"""Checker for type requirements.""" 6392 6393 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6394 __repr__ = _swig_repr 6395 6396 def __init__(self, model): 6397 _pywrapcp.TypeRequirementChecker_swiginit(self, _pywrapcp.new_TypeRequirementChecker(model)) 6398 __swig_destroy__ = _pywrapcp.delete_TypeRequirementChecker
Checker for type requirements.
6393 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
Inherited Members
6402class TypeRegulationsConstraint(Constraint): 6403 r""" 6404 The following constraint ensures that incompatibilities and requirements 6405 between types are respected. 6406 6407 It verifies both "hard" and "temporal" incompatibilities. 6408 Two nodes with hard incompatible types cannot be served by the same vehicle 6409 at all, while with a temporal incompatibility they can't be on the same 6410 route at the same time. 6411 The VisitTypePolicy of a node determines how visiting it impacts the type 6412 count on the route. 6413 6414 For example, for 6415 - three temporally incompatible types T1 T2 and T3 6416 - 2 pairs of nodes a1/r1 and a2/r2 of type T1 and T2 respectively, with 6417 - a1 and a2 of VisitTypePolicy TYPE_ADDED_TO_VEHICLE 6418 - r1 and r2 of policy ADDED_TYPE_REMOVED_FROM_VEHICLE 6419 - 3 nodes A, UV and AR of type T3, respectively with type policies 6420 TYPE_ADDED_TO_VEHICLE, TYPE_ON_VEHICLE_UP_TO_VISIT and 6421 TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED 6422 the configurations 6423 UV --> a1 --> r1 --> a2 --> r2, a1 --> r1 --> a2 --> r2 --> A and 6424 a1 --> r1 --> AR --> a2 --> r2 are acceptable, whereas the configurations 6425 a1 --> a2 --> r1 --> ..., or A --> a1 --> r1 --> ..., or 6426 a1 --> r1 --> UV --> ... are not feasible. 6427 6428 It also verifies same-vehicle and temporal type requirements. 6429 A node of type T_d with a same-vehicle requirement for type T_r needs to be 6430 served by the same vehicle as a node of type T_r. 6431 Temporal requirements, on the other hand, can take effect either when the 6432 dependent type is being added to the route or when it's removed from it, 6433 which is determined by the dependent node's VisitTypePolicy. 6434 In the above example: 6435 - If T3 is required on the same vehicle as T1, A, AR or UV must be on the 6436 same vehicle as a1. 6437 - If T2 is required when adding T1, a2 must be visited *before* a1, and if 6438 r2 is also visited on the route, it must be *after* a1, i.e. T2 must be on 6439 the vehicle when a1 is visited: 6440 ... --> a2 --> ... --> a1 --> ... --> r2 --> ... 6441 - If T3 is required when removing T1, T3 needs to be on the vehicle when 6442 r1 is visited: 6443 ... --> A --> ... --> r1 --> ... OR ... --> r1 --> ... --> UV --> ... 6444 """ 6445 6446 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6447 __repr__ = _swig_repr 6448 6449 def __init__(self, model): 6450 _pywrapcp.TypeRegulationsConstraint_swiginit(self, _pywrapcp.new_TypeRegulationsConstraint(model)) 6451 6452 def Post(self): 6453 return _pywrapcp.TypeRegulationsConstraint_Post(self) 6454 6455 def InitialPropagateWrapper(self): 6456 return _pywrapcp.TypeRegulationsConstraint_InitialPropagateWrapper(self) 6457 __swig_destroy__ = _pywrapcp.delete_TypeRegulationsConstraint
The following constraint ensures that incompatibilities and requirements between types are respected.
It verifies both "hard" and "temporal" incompatibilities. Two nodes with hard incompatible types cannot be served by the same vehicle at all, while with a temporal incompatibility they can't be on the same route at the same time. The VisitTypePolicy of a node determines how visiting it impacts the type count on the route.
For example, for
- three temporally incompatible types T1 T2 and T3
- 2 pairs of nodes a1/r1 and a2/r2 of type T1 and T2 respectively, with
- a1 and a2 of VisitTypePolicy TYPE_ADDED_TO_VEHICLE
- r1 and r2 of policy ADDED_TYPE_REMOVED_FROM_VEHICLE
- 3 nodes A, UV and AR of type T3, respectively with type policies TYPE_ADDED_TO_VEHICLE, TYPE_ON_VEHICLE_UP_TO_VISIT and TYPE_SIMULTANEOUSLY_ADDED_AND_REMOVED the configurations UV --> a1 --> r1 --> a2 --> r2, a1 --> r1 --> a2 --> r2 --> A and a1 --> r1 --> AR --> a2 --> r2 are acceptable, whereas the configurations a1 --> a2 --> r1 --> ..., or A --> a1 --> r1 --> ..., or a1 --> r1 --> UV --> ... are not feasible.
It also verifies same-vehicle and temporal type requirements. A node of type T_d with a same-vehicle requirement for type T_r needs to be served by the same vehicle as a node of type T_r. Temporal requirements, on the other hand, can take effect either when the dependent type is being added to the route or when it's removed from it, which is determined by the dependent node's VisitTypePolicy. In the above example:
- If T3 is required on the same vehicle as T1, A, AR or UV must be on the same vehicle as a1.
- If T2 is required when adding T1, a2 must be visited before a1, and if r2 is also visited on the route, it must be after a1, i.e. T2 must be on the vehicle when a1 is visited: ... --> a2 --> ... --> a1 --> ... --> r2 --> ...
- If T3 is required when removing T1, T3 needs to be on the vehicle when r1 is visited: ... --> A --> ... --> r1 --> ... OR ... --> r1 --> ... --> UV --> ...
6446 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
This method is called when the constraint is processed by the solver. Its main usage is to attach demons to variables.
6455 def InitialPropagateWrapper(self): 6456 return _pywrapcp.TypeRegulationsConstraint_InitialPropagateWrapper(self)
This method performs the initial propagation of the constraint. It is called just after the post.
Inherited Members
6461class BoundCost(object): 6462 r""" 6463 A structure meant to store soft bounds and associated violation constants. 6464 It is 'Simple' because it has one BoundCost per element, 6465 in contrast to 'Multiple'. Design notes: 6466 - it is meant to store model information to be shared through pointers, 6467 so it disallows copy and assign to avoid accidental duplication. 6468 - it keeps soft bounds as an array of structs to help cache, 6469 because code that uses such bounds typically use both bound and cost. 6470 - soft bounds are named pairs, prevents some mistakes. 6471 - using operator[] to access elements is not interesting, 6472 because the structure will be accessed through pointers, moreover having 6473 to type bound_cost reminds the user of the order if they do a copy 6474 assignment of the element. 6475 """ 6476 6477 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6478 __repr__ = _swig_repr 6479 bound = property(_pywrapcp.BoundCost_bound_get, _pywrapcp.BoundCost_bound_set) 6480 cost = property(_pywrapcp.BoundCost_cost_get, _pywrapcp.BoundCost_cost_set) 6481 6482 def __init__(self, *args): 6483 _pywrapcp.BoundCost_swiginit(self, _pywrapcp.new_BoundCost(*args)) 6484 __swig_destroy__ = _pywrapcp.delete_BoundCost
A structure meant to store soft bounds and associated violation constants. It is 'Simple' because it has one BoundCost per element, in contrast to 'Multiple'. Design notes:
- it is meant to store model information to be shared through pointers, so it disallows copy and assign to avoid accidental duplication.
- it keeps soft bounds as an array of structs to help cache, because code that uses such bounds typically use both bound and cost.
- soft bounds are named pairs, prevents some mistakes.
- using operator[] to access elements is not interesting, because the structure will be accessed through pointers, moreover having to type bound_cost reminds the user of the order if they do a copy assignment of the element.
6477 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
6488class SimpleBoundCosts(object): 6489 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6490 __repr__ = _swig_repr 6491 6492 def __init__(self, num_bounds, default_bound_cost): 6493 _pywrapcp.SimpleBoundCosts_swiginit(self, _pywrapcp.new_SimpleBoundCosts(num_bounds, default_bound_cost)) 6494 6495 def bound_cost(self, element): 6496 return _pywrapcp.SimpleBoundCosts_bound_cost(self, element) 6497 6498 def size(self): 6499 return _pywrapcp.SimpleBoundCosts_size(self) 6500 __swig_destroy__ = _pywrapcp.delete_SimpleBoundCosts
6489 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
6504class RoutingDimension(object): 6505 r""" 6506 Dimensions represent quantities accumulated at nodes along the routes. They 6507 represent quantities such as weights or volumes carried along the route, or 6508 distance or times. 6509 6510 Quantities at a node are represented by "cumul" variables and the increase 6511 or decrease of quantities between nodes are represented by "transit" 6512 variables. These variables are linked as follows: 6513 6514 if j == next(i), 6515 cumuls(j) = cumuls(i) + transits(i) + slacks(i) + 6516 state_dependent_transits(i) 6517 6518 where slack is a positive slack variable (can represent waiting times for 6519 a time dimension), and state_dependent_transits is a non-purely functional 6520 version of transits_. Favour transits over state_dependent_transits when 6521 possible, because purely functional callbacks allow more optimisations and 6522 make the model faster and easier to solve. 6523 for a given vehicle, it is passed as an external vector, it would be better 6524 to have this information here. 6525 """ 6526 6527 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") 6528 6529 def __init__(self, *args, **kwargs): 6530 raise AttributeError("No constructor defined") 6531 __repr__ = _swig_repr 6532 __swig_destroy__ = _pywrapcp.delete_RoutingDimension 6533 6534 def model(self): 6535 r"""Returns the model on which the dimension was created.""" 6536 return _pywrapcp.RoutingDimension_model(self) 6537 6538 def GetTransitValue(self, from_index, to_index, vehicle): 6539 r""" 6540 Returns the transition value for a given pair of nodes (as var index); 6541 this value is the one taken by the corresponding transit variable when 6542 the 'next' variable for 'from_index' is bound to 'to_index'. 6543 """ 6544 return _pywrapcp.RoutingDimension_GetTransitValue(self, from_index, to_index, vehicle) 6545 6546 def GetTransitValueFromClass(self, from_index, to_index, vehicle_class): 6547 r""" 6548 Same as above but taking a vehicle class of the dimension instead of a 6549 vehicle (the class of a vehicle can be obtained with vehicle_to_class()). 6550 """ 6551 return _pywrapcp.RoutingDimension_GetTransitValueFromClass(self, from_index, to_index, vehicle_class) 6552 6553 def CumulVar(self, index): 6554 r""" 6555 Get the cumul, transit and slack variables for the given node (given as 6556 int64_t var index). 6557 """ 6558 return _pywrapcp.RoutingDimension_CumulVar(self, index) 6559 6560 def TransitVar(self, index): 6561 return _pywrapcp.RoutingDimension_TransitVar(self, index) 6562 6563 def FixedTransitVar(self, index): 6564 return _pywrapcp.RoutingDimension_FixedTransitVar(self, index) 6565 6566 def SlackVar(self, index): 6567 return _pywrapcp.RoutingDimension_SlackVar(self, index) 6568 6569 def SetCumulVarRange(self, index, min, max): 6570 r""" 6571 Some functions to allow users to use the interface without knowing about 6572 the underlying CP model. 6573 Restricts the range of the cumul variable associated to index. 6574 """ 6575 return _pywrapcp.RoutingDimension_SetCumulVarRange(self, index, min, max) 6576 6577 def GetCumulVarMin(self, index): 6578 r"""Gets the current minimum of the cumul variable associated to index.""" 6579 return _pywrapcp.RoutingDimension_GetCumulVarMin(self, index) 6580 6581 def GetCumulVarMax(self, index): 6582 r"""Gets the current maximum of the cumul variable associated to index.""" 6583 return _pywrapcp.RoutingDimension_GetCumulVarMax(self, index) 6584 6585 def SetSpanUpperBoundForVehicle(self, upper_bound, vehicle): 6586 r""" 6587 Sets an upper bound on the dimension span on a given vehicle. This is the 6588 preferred way to limit the "length" of the route of a vehicle according to 6589 a dimension. 6590 """ 6591 return _pywrapcp.RoutingDimension_SetSpanUpperBoundForVehicle(self, upper_bound, vehicle) 6592 6593 def SetSpanCostCoefficientForVehicle(self, coefficient, vehicle): 6594 r""" 6595 Sets a cost proportional to the dimension span on a given vehicle, 6596 or on all vehicles at once. "coefficient" must be nonnegative. 6597 This is handy to model costs proportional to idle time when the dimension 6598 represents time. 6599 The cost for a vehicle is 6600 span_cost = coefficient * (dimension end value - dimension start value). 6601 """ 6602 return _pywrapcp.RoutingDimension_SetSpanCostCoefficientForVehicle(self, coefficient, vehicle) 6603 6604 def SetSpanCostCoefficientForAllVehicles(self, coefficient): 6605 return _pywrapcp.RoutingDimension_SetSpanCostCoefficientForAllVehicles(self, coefficient) 6606 6607 def SetSlackCostCoefficientForVehicle(self, coefficient, vehicle): 6608 r""" 6609 Sets a cost proportional to the dimension total slack on a given vehicle, 6610 or on all vehicles at once. "coefficient" must be nonnegative. 6611 This is handy to model costs only proportional to idle time when the 6612 dimension represents time. 6613 The cost for a vehicle is 6614 slack_cost = coefficient * 6615 (dimension end value - dimension start value - total_transit). 6616 """ 6617 return _pywrapcp.RoutingDimension_SetSlackCostCoefficientForVehicle(self, coefficient, vehicle) 6618 6619 def SetSlackCostCoefficientForAllVehicles(self, coefficient): 6620 return _pywrapcp.RoutingDimension_SetSlackCostCoefficientForAllVehicles(self, coefficient) 6621 6622 def SetGlobalSpanCostCoefficient(self, coefficient): 6623 r""" 6624 Sets a cost proportional to the *global* dimension span, that is the 6625 difference between the largest value of route end cumul variables and 6626 the smallest value of route start cumul variables. 6627 In other words: 6628 global_span_cost = 6629 coefficient * (Max(dimension end value) - Min(dimension start value)). 6630 """ 6631 return _pywrapcp.RoutingDimension_SetGlobalSpanCostCoefficient(self, coefficient) 6632 6633 def SetCumulVarSoftUpperBound(self, index, upper_bound, coefficient): 6634 r""" 6635 Sets a soft upper bound to the cumul variable of a given variable index. 6636 If the value of the cumul variable is greater than the bound, a cost 6637 proportional to the difference between this value and the bound is added 6638 to the cost function of the model: 6639 cumulVar <= upper_bound -> cost = 0 6640 cumulVar > upper_bound -> cost = coefficient * (cumulVar - upper_bound) 6641 This is also handy to model tardiness costs when the dimension represents 6642 time. 6643 """ 6644 return _pywrapcp.RoutingDimension_SetCumulVarSoftUpperBound(self, index, upper_bound, coefficient) 6645 6646 def HasCumulVarSoftUpperBound(self, index): 6647 r""" 6648 Returns true if a soft upper bound has been set for a given variable 6649 index. 6650 """ 6651 return _pywrapcp.RoutingDimension_HasCumulVarSoftUpperBound(self, index) 6652 6653 def GetCumulVarSoftUpperBound(self, index): 6654 r""" 6655 Returns the soft upper bound of a cumul variable for a given variable 6656 index. The "hard" upper bound of the variable is returned if no soft upper 6657 bound has been set. 6658 """ 6659 return _pywrapcp.RoutingDimension_GetCumulVarSoftUpperBound(self, index) 6660 6661 def GetCumulVarSoftUpperBoundCoefficient(self, index): 6662 r""" 6663 Returns the cost coefficient of the soft upper bound of a cumul variable 6664 for a given variable index. If no soft upper bound has been set, 0 is 6665 returned. 6666 """ 6667 return _pywrapcp.RoutingDimension_GetCumulVarSoftUpperBoundCoefficient(self, index) 6668 6669 def SetCumulVarSoftLowerBound(self, index, lower_bound, coefficient): 6670 r""" 6671 Sets a soft lower bound to the cumul variable of a given variable index. 6672 If the value of the cumul variable is less than the bound, a cost 6673 proportional to the difference between this value and the bound is added 6674 to the cost function of the model: 6675 cumulVar > lower_bound -> cost = 0 6676 cumulVar <= lower_bound -> cost = coefficient * (lower_bound - 6677 cumulVar). 6678 This is also handy to model earliness costs when the dimension represents 6679 time. 6680 """ 6681 return _pywrapcp.RoutingDimension_SetCumulVarSoftLowerBound(self, index, lower_bound, coefficient) 6682 6683 def HasCumulVarSoftLowerBound(self, index): 6684 r""" 6685 Returns true if a soft lower bound has been set for a given variable 6686 index. 6687 """ 6688 return _pywrapcp.RoutingDimension_HasCumulVarSoftLowerBound(self, index) 6689 6690 def GetCumulVarSoftLowerBound(self, index): 6691 r""" 6692 Returns the soft lower bound of a cumul variable for a given variable 6693 index. The "hard" lower bound of the variable is returned if no soft lower 6694 bound has been set. 6695 """ 6696 return _pywrapcp.RoutingDimension_GetCumulVarSoftLowerBound(self, index) 6697 6698 def GetCumulVarSoftLowerBoundCoefficient(self, index): 6699 r""" 6700 Returns the cost coefficient of the soft lower bound of a cumul variable 6701 for a given variable index. If no soft lower bound has been set, 0 is 6702 returned. 6703 """ 6704 return _pywrapcp.RoutingDimension_GetCumulVarSoftLowerBoundCoefficient(self, index) 6705 6706 def SetBreakIntervalsOfVehicle(self, breaks, vehicle, node_visit_transits): 6707 r""" 6708 Sets the breaks for a given vehicle. Breaks are represented by 6709 IntervalVars. They may interrupt transits between nodes and increase 6710 the value of corresponding slack variables. 6711 A break may take place before the start of a vehicle, after the end of 6712 a vehicle, or during a travel i -> j. 6713 6714 In that case, the interval [break.Start(), break.End()) must be a subset 6715 of [CumulVar(i) + pre_travel(i, j), CumulVar(j) - post_travel(i, j)). In 6716 other words, a break may not overlap any node n's visit, given by 6717 [CumulVar(n) - post_travel(_, n), CumulVar(n) + pre_travel(n, _)). 6718 This formula considers post_travel(_, start) and pre_travel(end, _) to be 6719 0; pre_travel will never be called on any (_, start) and post_travel will 6720 never we called on any (end, _). If pre_travel_evaluator or 6721 post_travel_evaluator is -1, it will be taken as a function that always 6722 returns 0. 6723 Deprecated, sets pre_travel(i, j) = node_visit_transit[i]. 6724 """ 6725 return _pywrapcp.RoutingDimension_SetBreakIntervalsOfVehicle(self, breaks, vehicle, node_visit_transits) 6726 6727 def SetBreakDistanceDurationOfVehicle(self, distance, duration, vehicle): 6728 r""" 6729 With breaks supposed to be consecutive, this forces the distance between 6730 breaks of size at least minimum_break_duration to be at most distance. 6731 This supposes that the time until route start and after route end are 6732 infinite breaks. 6733 """ 6734 return _pywrapcp.RoutingDimension_SetBreakDistanceDurationOfVehicle(self, distance, duration, vehicle) 6735 6736 def InitializeBreaks(self): 6737 r""" 6738 Sets up vehicle_break_intervals_, vehicle_break_distance_duration_, 6739 pre_travel_evaluators and post_travel_evaluators. 6740 """ 6741 return _pywrapcp.RoutingDimension_InitializeBreaks(self) 6742 6743 def HasBreakConstraints(self): 6744 r"""Returns true if any break interval or break distance was defined.""" 6745 return _pywrapcp.RoutingDimension_HasBreakConstraints(self) 6746 6747 def GetPreTravelEvaluatorOfVehicle(self, vehicle): 6748 return _pywrapcp.RoutingDimension_GetPreTravelEvaluatorOfVehicle(self, vehicle) 6749 6750 def GetPostTravelEvaluatorOfVehicle(self, vehicle): 6751 return _pywrapcp.RoutingDimension_GetPostTravelEvaluatorOfVehicle(self, vehicle) 6752 6753 def base_dimension(self): 6754 r"""Returns the parent in the dependency tree if any or nullptr otherwise.""" 6755 return _pywrapcp.RoutingDimension_base_dimension(self) 6756 6757 def ShortestTransitionSlack(self, node): 6758 r""" 6759 It makes sense to use the function only for self-dependent dimension. 6760 For such dimensions the value of the slack of a node determines the 6761 transition cost of the next transit. Provided that 6762 1. cumul[node] is fixed, 6763 2. next[node] and next[next[node]] (if exists) are fixed, 6764 the value of slack[node] for which cumul[next[node]] + transit[next[node]] 6765 is minimized can be found in O(1) using this function. 6766 """ 6767 return _pywrapcp.RoutingDimension_ShortestTransitionSlack(self, node) 6768 6769 def index(self): 6770 r"""Returns the index of the dimension in the model.""" 6771 return _pywrapcp.RoutingDimension_index(self) 6772 6773 def name(self): 6774 r"""Returns the name of the dimension.""" 6775 return _pywrapcp.RoutingDimension_name(self) 6776 6777 def SetPickupToDeliveryLimitFunctionForPair(self, limit_function, pair_index): 6778 return _pywrapcp.RoutingDimension_SetPickupToDeliveryLimitFunctionForPair(self, limit_function, pair_index) 6779 6780 def HasPickupToDeliveryLimits(self): 6781 return _pywrapcp.RoutingDimension_HasPickupToDeliveryLimits(self) 6782 6783 def AddNodePrecedence(self, first_node, second_node, offset): 6784 return _pywrapcp.RoutingDimension_AddNodePrecedence(self, first_node, second_node, offset) 6785 6786 def GetSpanUpperBoundForVehicle(self, vehicle): 6787 return _pywrapcp.RoutingDimension_GetSpanUpperBoundForVehicle(self, vehicle) 6788 6789 def GetSpanCostCoefficientForVehicle(self, vehicle): 6790 return _pywrapcp.RoutingDimension_GetSpanCostCoefficientForVehicle(self, vehicle) 6791 6792 def GetSlackCostCoefficientForVehicle(self, vehicle): 6793 return _pywrapcp.RoutingDimension_GetSlackCostCoefficientForVehicle(self, vehicle) 6794 6795 def global_span_cost_coefficient(self): 6796 return _pywrapcp.RoutingDimension_global_span_cost_coefficient(self) 6797 6798 def GetGlobalOptimizerOffset(self): 6799 return _pywrapcp.RoutingDimension_GetGlobalOptimizerOffset(self) 6800 6801 def GetLocalOptimizerOffsetForVehicle(self, vehicle): 6802 return _pywrapcp.RoutingDimension_GetLocalOptimizerOffsetForVehicle(self, vehicle) 6803 6804 def SetSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle): 6805 r""" 6806 If the span of vehicle on this dimension is larger than bound, 6807 the cost will be increased by cost * (span - bound). 6808 """ 6809 return _pywrapcp.RoutingDimension_SetSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle) 6810 6811 def HasSoftSpanUpperBounds(self): 6812 return _pywrapcp.RoutingDimension_HasSoftSpanUpperBounds(self) 6813 6814 def GetSoftSpanUpperBoundForVehicle(self, vehicle): 6815 return _pywrapcp.RoutingDimension_GetSoftSpanUpperBoundForVehicle(self, vehicle) 6816 6817 def SetQuadraticCostSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle): 6818 r""" 6819 If the span of vehicle on this dimension is larger than bound, 6820 the cost will be increased by cost * (span - bound)^2. 6821 """ 6822 return _pywrapcp.RoutingDimension_SetQuadraticCostSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle) 6823 6824 def HasQuadraticCostSoftSpanUpperBounds(self): 6825 return _pywrapcp.RoutingDimension_HasQuadraticCostSoftSpanUpperBounds(self) 6826 6827 def GetQuadraticCostSoftSpanUpperBoundForVehicle(self, vehicle): 6828 return _pywrapcp.RoutingDimension_GetQuadraticCostSoftSpanUpperBoundForVehicle(self, vehicle)
Dimensions represent quantities accumulated at nodes along the routes. They represent quantities such as weights or volumes carried along the route, or distance or times.
Quantities at a node are represented by "cumul" variables and the increase or decrease of quantities between nodes are represented by "transit" variables. These variables are linked as follows:
if j == next(i), cumuls(j) = cumuls(i) + transits(i) + slacks(i) + state_dependent_transits(i)
where slack is a positive slack variable (can represent waiting times for a time dimension), and state_dependent_transits is a non-purely functional version of transits_. Favour transits over state_dependent_transits when possible, because purely functional callbacks allow more optimisations and make the model faster and easier to solve. for a given vehicle, it is passed as an external vector, it would be better to have this information here.
6527 thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
The membership flag
6534 def model(self): 6535 r"""Returns the model on which the dimension was created.""" 6536 return _pywrapcp.RoutingDimension_model(self)
Returns the model on which the dimension was created.
6538 def GetTransitValue(self, from_index, to_index, vehicle): 6539 r""" 6540 Returns the transition value for a given pair of nodes (as var index); 6541 this value is the one taken by the corresponding transit variable when 6542 the 'next' variable for 'from_index' is bound to 'to_index'. 6543 """ 6544 return _pywrapcp.RoutingDimension_GetTransitValue(self, from_index, to_index, vehicle)
Returns the transition value for a given pair of nodes (as var index); this value is the one taken by the corresponding transit variable when the 'next' variable for 'from_index' is bound to 'to_index'.
6546 def GetTransitValueFromClass(self, from_index, to_index, vehicle_class): 6547 r""" 6548 Same as above but taking a vehicle class of the dimension instead of a 6549 vehicle (the class of a vehicle can be obtained with vehicle_to_class()). 6550 """ 6551 return _pywrapcp.RoutingDimension_GetTransitValueFromClass(self, from_index, to_index, vehicle_class)
Same as above but taking a vehicle class of the dimension instead of a vehicle (the class of a vehicle can be obtained with vehicle_to_class()).
6553 def CumulVar(self, index): 6554 r""" 6555 Get the cumul, transit and slack variables for the given node (given as 6556 int64_t var index). 6557 """ 6558 return _pywrapcp.RoutingDimension_CumulVar(self, index)
Get the cumul, transit and slack variables for the given node (given as int64_t var index).
6569 def SetCumulVarRange(self, index, min, max): 6570 r""" 6571 Some functions to allow users to use the interface without knowing about 6572 the underlying CP model. 6573 Restricts the range of the cumul variable associated to index. 6574 """ 6575 return _pywrapcp.RoutingDimension_SetCumulVarRange(self, index, min, max)
Some functions to allow users to use the interface without knowing about the underlying CP model. Restricts the range of the cumul variable associated to index.
6577 def GetCumulVarMin(self, index): 6578 r"""Gets the current minimum of the cumul variable associated to index.""" 6579 return _pywrapcp.RoutingDimension_GetCumulVarMin(self, index)
Gets the current minimum of the cumul variable associated to index.
6581 def GetCumulVarMax(self, index): 6582 r"""Gets the current maximum of the cumul variable associated to index.""" 6583 return _pywrapcp.RoutingDimension_GetCumulVarMax(self, index)
Gets the current maximum of the cumul variable associated to index.
6585 def SetSpanUpperBoundForVehicle(self, upper_bound, vehicle): 6586 r""" 6587 Sets an upper bound on the dimension span on a given vehicle. This is the 6588 preferred way to limit the "length" of the route of a vehicle according to 6589 a dimension. 6590 """ 6591 return _pywrapcp.RoutingDimension_SetSpanUpperBoundForVehicle(self, upper_bound, vehicle)
Sets an upper bound on the dimension span on a given vehicle. This is the preferred way to limit the "length" of the route of a vehicle according to a dimension.
6593 def SetSpanCostCoefficientForVehicle(self, coefficient, vehicle): 6594 r""" 6595 Sets a cost proportional to the dimension span on a given vehicle, 6596 or on all vehicles at once. "coefficient" must be nonnegative. 6597 This is handy to model costs proportional to idle time when the dimension 6598 represents time. 6599 The cost for a vehicle is 6600 span_cost = coefficient * (dimension end value - dimension start value). 6601 """ 6602 return _pywrapcp.RoutingDimension_SetSpanCostCoefficientForVehicle(self, coefficient, vehicle)
Sets a cost proportional to the dimension span on a given vehicle, or on all vehicles at once. "coefficient" must be nonnegative. This is handy to model costs proportional to idle time when the dimension represents time. The cost for a vehicle is span_cost = coefficient * (dimension end value - dimension start value).
6607 def SetSlackCostCoefficientForVehicle(self, coefficient, vehicle): 6608 r""" 6609 Sets a cost proportional to the dimension total slack on a given vehicle, 6610 or on all vehicles at once. "coefficient" must be nonnegative. 6611 This is handy to model costs only proportional to idle time when the 6612 dimension represents time. 6613 The cost for a vehicle is 6614 slack_cost = coefficient * 6615 (dimension end value - dimension start value - total_transit). 6616 """ 6617 return _pywrapcp.RoutingDimension_SetSlackCostCoefficientForVehicle(self, coefficient, vehicle)
Sets a cost proportional to the dimension total slack on a given vehicle, or on all vehicles at once. "coefficient" must be nonnegative. This is handy to model costs only proportional to idle time when the dimension represents time. The cost for a vehicle is slack_cost = coefficient * (dimension end value - dimension start value - total_transit).
6622 def SetGlobalSpanCostCoefficient(self, coefficient): 6623 r""" 6624 Sets a cost proportional to the *global* dimension span, that is the 6625 difference between the largest value of route end cumul variables and 6626 the smallest value of route start cumul variables. 6627 In other words: 6628 global_span_cost = 6629 coefficient * (Max(dimension end value) - Min(dimension start value)). 6630 """ 6631 return _pywrapcp.RoutingDimension_SetGlobalSpanCostCoefficient(self, coefficient)
Sets a cost proportional to the global dimension span, that is the difference between the largest value of route end cumul variables and the smallest value of route start cumul variables. In other words: global_span_cost = coefficient * (Max(dimension end value) - Min(dimension start value)).
6633 def SetCumulVarSoftUpperBound(self, index, upper_bound, coefficient): 6634 r""" 6635 Sets a soft upper bound to the cumul variable of a given variable index. 6636 If the value of the cumul variable is greater than the bound, a cost 6637 proportional to the difference between this value and the bound is added 6638 to the cost function of the model: 6639 cumulVar <= upper_bound -> cost = 0 6640 cumulVar > upper_bound -> cost = coefficient * (cumulVar - upper_bound) 6641 This is also handy to model tardiness costs when the dimension represents 6642 time. 6643 """ 6644 return _pywrapcp.RoutingDimension_SetCumulVarSoftUpperBound(self, index, upper_bound, coefficient)
Sets a soft upper bound to the cumul variable of a given variable index. If the value of the cumul variable is greater than the bound, a cost proportional to the difference between this value and the bound is added to the cost function of the model: cumulVar <= upper_bound -> cost = 0 cumulVar > upper_bound -> cost = coefficient * (cumulVar - upper_bound) This is also handy to model tardiness costs when the dimension represents time.
6646 def HasCumulVarSoftUpperBound(self, index): 6647 r""" 6648 Returns true if a soft upper bound has been set for a given variable 6649 index. 6650 """ 6651 return _pywrapcp.RoutingDimension_HasCumulVarSoftUpperBound(self, index)
Returns true if a soft upper bound has been set for a given variable index.
6653 def GetCumulVarSoftUpperBound(self, index): 6654 r""" 6655 Returns the soft upper bound of a cumul variable for a given variable 6656 index. The "hard" upper bound of the variable is returned if no soft upper 6657 bound has been set. 6658 """ 6659 return _pywrapcp.RoutingDimension_GetCumulVarSoftUpperBound(self, index)
Returns the soft upper bound of a cumul variable for a given variable index. The "hard" upper bound of the variable is returned if no soft upper bound has been set.
6661 def GetCumulVarSoftUpperBoundCoefficient(self, index): 6662 r""" 6663 Returns the cost coefficient of the soft upper bound of a cumul variable 6664 for a given variable index. If no soft upper bound has been set, 0 is 6665 returned. 6666 """ 6667 return _pywrapcp.RoutingDimension_GetCumulVarSoftUpperBoundCoefficient(self, index)
Returns the cost coefficient of the soft upper bound of a cumul variable for a given variable index. If no soft upper bound has been set, 0 is returned.
6669 def SetCumulVarSoftLowerBound(self, index, lower_bound, coefficient): 6670 r""" 6671 Sets a soft lower bound to the cumul variable of a given variable index. 6672 If the value of the cumul variable is less than the bound, a cost 6673 proportional to the difference between this value and the bound is added 6674 to the cost function of the model: 6675 cumulVar > lower_bound -> cost = 0 6676 cumulVar <= lower_bound -> cost = coefficient * (lower_bound - 6677 cumulVar). 6678 This is also handy to model earliness costs when the dimension represents 6679 time. 6680 """ 6681 return _pywrapcp.RoutingDimension_SetCumulVarSoftLowerBound(self, index, lower_bound, coefficient)
Sets a soft lower bound to the cumul variable of a given variable index. If the value of the cumul variable is less than the bound, a cost proportional to the difference between this value and the bound is added to the cost function of the model: cumulVar > lower_bound -> cost = 0 cumulVar <= lower_bound -> cost = coefficient * (lower_bound - cumulVar). This is also handy to model earliness costs when the dimension represents time.
6683 def HasCumulVarSoftLowerBound(self, index): 6684 r""" 6685 Returns true if a soft lower bound has been set for a given variable 6686 index. 6687 """ 6688 return _pywrapcp.RoutingDimension_HasCumulVarSoftLowerBound(self, index)
Returns true if a soft lower bound has been set for a given variable index.
6690 def GetCumulVarSoftLowerBound(self, index): 6691 r""" 6692 Returns the soft lower bound of a cumul variable for a given variable 6693 index. The "hard" lower bound of the variable is returned if no soft lower 6694 bound has been set. 6695 """ 6696 return _pywrapcp.RoutingDimension_GetCumulVarSoftLowerBound(self, index)
Returns the soft lower bound of a cumul variable for a given variable index. The "hard" lower bound of the variable is returned if no soft lower bound has been set.
6698 def GetCumulVarSoftLowerBoundCoefficient(self, index): 6699 r""" 6700 Returns the cost coefficient of the soft lower bound of a cumul variable 6701 for a given variable index. If no soft lower bound has been set, 0 is 6702 returned. 6703 """ 6704 return _pywrapcp.RoutingDimension_GetCumulVarSoftLowerBoundCoefficient(self, index)
Returns the cost coefficient of the soft lower bound of a cumul variable for a given variable index. If no soft lower bound has been set, 0 is returned.
6706 def SetBreakIntervalsOfVehicle(self, breaks, vehicle, node_visit_transits): 6707 r""" 6708 Sets the breaks for a given vehicle. Breaks are represented by 6709 IntervalVars. They may interrupt transits between nodes and increase 6710 the value of corresponding slack variables. 6711 A break may take place before the start of a vehicle, after the end of 6712 a vehicle, or during a travel i -> j. 6713 6714 In that case, the interval [break.Start(), break.End()) must be a subset 6715 of [CumulVar(i) + pre_travel(i, j), CumulVar(j) - post_travel(i, j)). In 6716 other words, a break may not overlap any node n's visit, given by 6717 [CumulVar(n) - post_travel(_, n), CumulVar(n) + pre_travel(n, _)). 6718 This formula considers post_travel(_, start) and pre_travel(end, _) to be 6719 0; pre_travel will never be called on any (_, start) and post_travel will 6720 never we called on any (end, _). If pre_travel_evaluator or 6721 post_travel_evaluator is -1, it will be taken as a function that always 6722 returns 0. 6723 Deprecated, sets pre_travel(i, j) = node_visit_transit[i]. 6724 """ 6725 return _pywrapcp.RoutingDimension_SetBreakIntervalsOfVehicle(self, breaks, vehicle, node_visit_transits)
Sets the breaks for a given vehicle. Breaks are represented by IntervalVars. They may interrupt transits between nodes and increase the value of corresponding slack variables. A break may take place before the start of a vehicle, after the end of a vehicle, or during a travel i -> j.
In that case, the interval [break.Start(), break.End()) must be a subset of [CumulVar(i) + pre_travel(i, j), CumulVar(j) - post_travel(i, j)). In other words, a break may not overlap any node n's visit, given by [CumulVar(n) - post_travel(_, n), CumulVar(n) + pre_travel(n, _)). This formula considers post_travel(_, start) and pre_travel(end, _) to be 0; pre_travel will never be called on any (_, start) and post_travel will never we called on any (end, _). If pre_travel_evaluator or post_travel_evaluator is -1, it will be taken as a function that always returns 0. Deprecated, sets pre_travel(i, j) = node_visit_transit[i].
6727 def SetBreakDistanceDurationOfVehicle(self, distance, duration, vehicle): 6728 r""" 6729 With breaks supposed to be consecutive, this forces the distance between 6730 breaks of size at least minimum_break_duration to be at most distance. 6731 This supposes that the time until route start and after route end are 6732 infinite breaks. 6733 """ 6734 return _pywrapcp.RoutingDimension_SetBreakDistanceDurationOfVehicle(self, distance, duration, vehicle)
With breaks supposed to be consecutive, this forces the distance between breaks of size at least minimum_break_duration to be at most distance. This supposes that the time until route start and after route end are infinite breaks.
6736 def InitializeBreaks(self): 6737 r""" 6738 Sets up vehicle_break_intervals_, vehicle_break_distance_duration_, 6739 pre_travel_evaluators and post_travel_evaluators. 6740 """ 6741 return _pywrapcp.RoutingDimension_InitializeBreaks(self)
Sets up vehicle_break_intervals_, vehicle_break_distance_duration_, pre_travel_evaluators and post_travel_evaluators.
6743 def HasBreakConstraints(self): 6744 r"""Returns true if any break interval or break distance was defined.""" 6745 return _pywrapcp.RoutingDimension_HasBreakConstraints(self)
Returns true if any break interval or break distance was defined.
6753 def base_dimension(self): 6754 r"""Returns the parent in the dependency tree if any or nullptr otherwise.""" 6755 return _pywrapcp.RoutingDimension_base_dimension(self)
Returns the parent in the dependency tree if any or nullptr otherwise.
6757 def ShortestTransitionSlack(self, node): 6758 r""" 6759 It makes sense to use the function only for self-dependent dimension. 6760 For such dimensions the value of the slack of a node determines the 6761 transition cost of the next transit. Provided that 6762 1. cumul[node] is fixed, 6763 2. next[node] and next[next[node]] (if exists) are fixed, 6764 the value of slack[node] for which cumul[next[node]] + transit[next[node]] 6765 is minimized can be found in O(1) using this function. 6766 """ 6767 return _pywrapcp.RoutingDimension_ShortestTransitionSlack(self, node)
It makes sense to use the function only for self-dependent dimension. For such dimensions the value of the slack of a node determines the transition cost of the next transit. Provided that
- cumul[node] is fixed,
- next[node] and next[next[node]] (if exists) are fixed, the value of slack[node] for which cumul[next[node]] + transit[next[node]] is minimized can be found in O(1) using this function.
6769 def index(self): 6770 r"""Returns the index of the dimension in the model.""" 6771 return _pywrapcp.RoutingDimension_index(self)
Returns the index of the dimension in the model.
6773 def name(self): 6774 r"""Returns the name of the dimension.""" 6775 return _pywrapcp.RoutingDimension_name(self)
Returns the name of the dimension.
6804 def SetSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle): 6805 r""" 6806 If the span of vehicle on this dimension is larger than bound, 6807 the cost will be increased by cost * (span - bound). 6808 """ 6809 return _pywrapcp.RoutingDimension_SetSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle)
If the span of vehicle on this dimension is larger than bound, the cost will be increased by cost * (span - bound).
6817 def SetQuadraticCostSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle): 6818 r""" 6819 If the span of vehicle on this dimension is larger than bound, 6820 the cost will be increased by cost * (span - bound)^2. 6821 """ 6822 return _pywrapcp.RoutingDimension_SetQuadraticCostSoftSpanUpperBoundForVehicle(self, bound_cost, vehicle)
If the span of vehicle on this dimension is larger than bound, the cost will be increased by cost * (span - bound)^2.
6833def SolveModelWithSat(model, search_stats, search_parameters, initial_solution, solution): 6834 r""" 6835 Attempts to solve the model using the cp-sat solver. As of 5/2019, will 6836 solve the TSP corresponding to the model if it has a single vehicle. 6837 Therefore the resulting solution might not actually be feasible. Will return 6838 false if a solution could not be found. 6839 """ 6840 return _pywrapcp.SolveModelWithSat(model, search_stats, search_parameters, initial_solution, solution)
Attempts to solve the model using the cp-sat solver. As of 5/2019, will solve the TSP corresponding to the model if it has a single vehicle. Therefore the resulting solution might not actually be feasible. Will return false if a solution could not be found.