forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
constraint_solver.h
5293 lines (4630 loc) · 217 KB
/
constraint_solver.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Declaration of the core objects for the constraint solver.
///
/// The literature around constraint programming is extremely dense but one
/// can find some basic introductions in the following links:
/// - http://en.wikipedia.org/wiki/Constraint_programming
/// - http://kti.mff.cuni.cz/~bartak/constraints/index.html
///
/// Here is a very simple Constraint Programming problem:
///
/// Knowing that we see 56 legs and 20 heads, how many pheasants and rabbits
/// are we looking at?
///
/// Here is some simple Constraint Programming code to find out:
///
/// void pheasant() {
/// Solver s("pheasant");
/// IntVar* const p = s.MakeIntVar(0, 20, "pheasant"));
/// IntVar* const r = s.MakeIntVar(0, 20, "rabbit"));
/// IntExpr* const legs = s.MakeSum(s.MakeProd(p, 2), s.MakeProd(r, 4));
/// IntExpr* const heads = s.MakeSum(p, r);
/// Constraint* const ct_legs = s.MakeEquality(legs, 56);
/// Constraint* const ct_heads = s.MakeEquality(heads, 20);
/// s.AddConstraint(ct_legs);
/// s.AddConstraint(ct_heads);
/// DecisionBuilder* const db = s.MakePhase(p, r,
/// Solver::CHOOSE_FIRST_UNBOUND,
/// Solver::ASSIGN_MIN_VALUE);
/// s.NewSearch(db);
/// CHECK(s.NextSolution());
/// LOG(INFO) << "rabbits -> " << r->Value() << ", pheasants -> "
/// << p->Value();
/// LOG(INFO) << s.DebugString();
/// s.EndSearch();
/// }
///
/// which outputs:
///
/// rabbits -> 8, pheasants -> 12
/// Solver(name = "pheasant",
/// state = OUTSIDE_SEARCH,
/// branches = 0,
/// fails = 0,
/// decisions = 0
/// propagation loops = 11,
/// demons Run = 25,
/// Run time = 0 ms)
///
///
#ifndef OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
#define OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
#include <functional>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_format.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/hash.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/macros.h"
#include "ortools/base/map_util.h"
#include "ortools/base/random.h"
#include "ortools/base/sysinfo.h"
#include "ortools/base/timer.h"
#include "ortools/constraint_solver/solver_parameters.pb.h"
#include "ortools/util/piecewise_linear_function.h"
#include "ortools/util/sorted_interval_list.h"
#include "ortools/util/tuple_set.h"
class File;
namespace operations_research {
class Assignment;
class AssignmentProto;
class BaseObject;
class CpArgument;
class CpConstraint;
class CpIntegerExpression;
class CpIntervalVariable;
class CpSequenceVariable;
class CastConstraint;
class Constraint;
class Decision;
class DecisionBuilder;
class DecisionVisitor;
class Demon;
class DemonProfiler;
class LocalSearchProfiler;
class Dimension;
class DisjunctiveConstraint;
class ExpressionCache;
class IntExpr;
class IntTupleSet;
class IntVar;
class IntVarAssignment;
class IntVarElement;
class IntervalVar;
class IntervalVarAssignment;
class IntervalVarElement;
class IntVarLocalSearchFilter;
class LocalSearchFilter;
class LocalSearchOperator;
class LocalSearchPhaseParameters;
class ModelCache;
class ModelVisitor;
class OptimizeVar;
class Pack;
class PropagationBaseObject;
class PropagationMonitor;
class LocalSearchMonitor;
class Queue;
class RevBitMatrix;
class RevBitSet;
class RegularLimit;
class RegularLimitParameters;
class Search;
class SearchLimit;
class SearchMonitor;
class SequenceVar;
class SequenceVarAssignment;
class SolutionCollector;
class SolutionPool;
class Solver;
class ConstraintSolverParameters;
class SymmetryBreaker;
struct StateInfo;
struct Trail;
template <class T>
class SimpleRevFIFO;
/// This struct holds all parameters for the default search.
/// DefaultPhaseParameters is only used by Solver::MakeDefaultPhase methods.
/// Note this is for advanced users only.
struct DefaultPhaseParameters {
public:
enum VariableSelection {
CHOOSE_MAX_SUM_IMPACT = 0,
CHOOSE_MAX_AVERAGE_IMPACT = 1,
CHOOSE_MAX_VALUE_IMPACT = 2,
};
enum ValueSelection {
SELECT_MIN_IMPACT = 0,
SELECT_MAX_IMPACT = 1,
};
enum DisplayLevel { NONE = 0, NORMAL = 1, VERBOSE = 2 };
/// This parameter describes how the next variable to instantiate
/// will be chosen.
VariableSelection var_selection_schema;
/// This parameter describes which value to select for a given var.
ValueSelection value_selection_schema;
/// Maximum number of intervals that the initialization of impacts will scan
/// per variable.
int initialization_splits;
/// The default phase will run heuristics periodically. This parameter
/// indicates if we should run all heuristics, or a randomly selected
/// one.
bool run_all_heuristics;
/// 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.
int heuristic_period;
/// The failure limit for each heuristic that we run.
int heuristic_num_failures_limit;
/// Whether to keep the impact from the first search for other searches,
/// or to recompute the impact for each new search.
bool persistent_impact;
/// Seed used to initialize the random part in some heuristics.
int random_seed;
/// This represents the amount of information displayed by the default search.
/// NONE means no display, VERBOSE means extra information.
DisplayLevel display_level;
/// Should we use last conflict method. The default is false.
bool use_last_conflict;
/// When defined, this overrides the default impact based decision builder.
DecisionBuilder* decision_builder;
DefaultPhaseParameters();
};
/// 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.
class Solver {
public:
/// Holds semantic information stating that the 'expression' has been
/// cast into 'variable' using the Var() method, and that
/// 'maintainer' is responsible for maintaining the equality between
/// 'variable' and 'expression'.
struct IntegerCastInfo {
IntegerCastInfo()
: variable(nullptr), expression(nullptr), maintainer(nullptr) {}
IntegerCastInfo(IntVar* const v, IntExpr* const e, Constraint* const c)
: variable(v), expression(e), maintainer(c) {}
IntVar* variable;
IntExpr* expression;
Constraint* maintainer;
};
/// Number of priorities for demons.
static const int kNumPriorities = 3;
/// This enum describes the strategy used to select the next branching
/// variable at each node during the search.
enum IntVarStrategy {
/// The default behavior is CHOOSE_FIRST_UNBOUND.
INT_VAR_DEFAULT,
/// The simple selection is CHOOSE_FIRST_UNBOUND.
INT_VAR_SIMPLE,
/// Select the first unbound variable.
/// Variables are considered in the order of the vector of IntVars used
/// to create the selector.
CHOOSE_FIRST_UNBOUND,
/// Randomly select one of the remaining unbound variables.
CHOOSE_RANDOM,
/// 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.
CHOOSE_MIN_SIZE_LOWEST_MIN,
/// 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.
CHOOSE_MIN_SIZE_HIGHEST_MIN,
/// 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.
CHOOSE_MIN_SIZE_LOWEST_MAX,
/// 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.
CHOOSE_MIN_SIZE_HIGHEST_MAX,
/// 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.
CHOOSE_LOWEST_MIN,
/// 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.
CHOOSE_HIGHEST_MAX,
/// 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.
CHOOSE_MIN_SIZE,
/// 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.
CHOOSE_MAX_SIZE,
/// Among unbound variables, select the variable with the largest
/// gap between the first and the second values of the domain.
CHOOSE_MAX_REGRET_ON_MIN,
/// 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.
CHOOSE_PATH,
};
// TODO(user): add HIGHEST_MIN and LOWEST_MAX.
/// This enum describes the strategy used to select the next variable value to
/// set.
enum IntValueStrategy {
/// The default behavior is ASSIGN_MIN_VALUE.
INT_VALUE_DEFAULT,
/// The simple selection is ASSIGN_MIN_VALUE.
INT_VALUE_SIMPLE,
/// Selects the min value of the selected variable.
ASSIGN_MIN_VALUE,
/// Selects the max value of the selected variable.
ASSIGN_MAX_VALUE,
/// Selects randomly one of the possible values of the selected variable.
ASSIGN_RANDOM_VALUE,
/// 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.
ASSIGN_CENTER_VALUE,
/// Split the domain in two around the center, and choose the lower
/// part first.
SPLIT_LOWER_HALF,
/// Split the domain in two around the center, and choose the lower
/// part first.
SPLIT_UPPER_HALF,
};
/// This enum is used by Solver::MakePhase to specify how to select variables
/// and values during the search.
/// In Solver::MakePhase(const std::vector<IntVar*>&, IntVarStrategy,
/// IntValueStrategy), variables are selected first, and then the associated
/// value.
/// In Solver::MakePhase(const std::vector<IntVar*>& vars, IndexEvaluator2,
/// EvaluatorStrategy), the selection is done scanning every pair
/// <variable, possible value>. The next selected pair is then the best among
/// all possibilities, i.e. the pair with the smallest evaluation.
/// As this is costly, two options are offered: static or dynamic evaluation.
enum EvaluatorStrategy {
/// Pairs are compared at the first call of the selector, and results are
/// cached. Next calls to the selector use the previous computation, and so
/// are not up-to-date, e.g. some <variable, value> pairs may not be
/// possible anymore due to propagation since the first to call.
CHOOSE_STATIC_GLOBAL_BEST,
/// Pairs are compared each time a variable is selected. That way all pairs
/// are relevant and evaluation is accurate.
/// This strategy runs in O(number-of-pairs) at each variable selection,
/// versus O(1) in the static version.
CHOOSE_DYNAMIC_GLOBAL_BEST,
};
/// Used for scheduling. Not yet implemented.
enum SequenceStrategy {
SEQUENCE_DEFAULT,
SEQUENCE_SIMPLE,
CHOOSE_MIN_SLACK_RANK_FORWARD,
CHOOSE_RANDOM_RANK_FORWARD,
};
/// This enum describes the straregy used to select the next interval variable
/// and its value to be fixed.
enum IntervalStrategy {
/// The default is INTERVAL_SET_TIMES_FORWARD.
INTERVAL_DEFAULT,
/// The simple is INTERVAL_SET_TIMES_FORWARD.
INTERVAL_SIMPLE,
/// Selects the variable with the lowest starting time of all variables,
/// and fixes its starting time to this lowest value.
INTERVAL_SET_TIMES_FORWARD,
/// Selects the variable with the highest ending time of all variables,
/// and fixes the ending time to this highest values.
INTERVAL_SET_TIMES_BACKWARD
};
/// This enum is used in Solver::MakeOperator to specify the neighborhood to
/// create.
enum LocalSearchOperators {
/// 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
TWOOPT,
/// 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).
OROPT,
/// Relocate neighborhood with length of 1 (see OROPT comment).
RELOCATE,
/// 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
EXCHANGE,
/// 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
CROSS,
/// 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
MAKEACTIVE,
/// 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
MAKEINACTIVE,
/// 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
MAKECHAININACTIVE,
/// 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
SWAPACTIVE,
/// 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
EXTENDEDSWAPACTIVE,
/// 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.
PATHLNS,
/// Operator which relaxes one entire path and all inactive nodes, thus
/// defining num_paths neighbors.
FULLPATHLNS,
/// 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.
UNACTIVELNS,
/// 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.
INCREMENT,
/// Operator which defines a neighborhood to decrement values.
/// The behavior is the same as INCREMENT, except values are decremented
/// instead of incremented.
DECREMENT,
/// 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.
SIMPLELNS
};
/// This enum is used in Solver::MakeOperator associated with an evaluator
/// to specify the neighborhood to create.
enum EvaluatorLocalSearchOperators {
/// Lin–Kernighan local search.
/// While the accumulated local gain is positive, perform a 2opt or a 3opt
/// move followed by a series of 2opt moves. Return a neighbor for which the
/// global gain is positive.
LK,
/// Sliding TSP operator.
/// Uses an exact dynamic programming algorithm to solve the TSP
/// corresponding to path sub-chains.
/// For a subchain 1 -> 2 -> 3 -> 4 -> 5 -> 6, solves the TSP on
/// nodes A, 2, 3, 4, 5, where A is a merger of nodes 1 and 6 such that
/// cost(A,i) = cost(1,i) and cost(i,A) = cost(i,6).
TSPOPT,
/// TSP-base LNS.
/// Randomly merge consecutive nodes until n "meta"-nodes remain and solve
/// the corresponding TSP.
/// This is an "unlimited" neighborhood which must be stopped by search
/// limits. To force diversification, the operator iteratively forces each
/// node to serve as base of a meta-node.
TSPLNS
};
/// This enum is used in Solver::MakeLocalSearchObjectiveFilter. It specifies
/// the behavior of the objective filter to create. The goal is to define
/// under which condition a move is accepted based on the current objective
/// value.
enum LocalSearchFilterBound {
/// Move is accepted when the current objective value >= objective.Min.
GE,
/// Move is accepted when the current objective value <= objective.Max.
LE,
/// Move is accepted when the current objective value is in the interval
/// objective.Min .. objective.Max.
EQ
};
/// This enum represents the three possible priorities for a demon in the
/// Solver queue.
/// Note: this is for advanced users only.
enum DemonPriority {
/// DELAYED_PRIORITY is the lowest priority: Demons will be processed after
/// VAR_PRIORITY and NORMAL_PRIORITY demons.
DELAYED_PRIORITY = 0,
/// VAR_PRIORITY is between DELAYED_PRIORITY and NORMAL_PRIORITY.
VAR_PRIORITY = 1,
/// NORMAL_PRIORITY is the highest priority: Demons will be processed first.
NORMAL_PRIORITY = 2,
};
/// This enum is used in Solver::MakeIntervalVarRelation to specify the
/// temporal relation between the two intervals t1 and t2.
enum BinaryIntervalRelation {
/// t1 ends after t2 end, i.e. End(t1) >= End(t2) + delay.
ENDS_AFTER_END,
/// t1 ends after t2 start, i.e. End(t1) >= Start(t2) + delay.
ENDS_AFTER_START,
/// t1 ends at t2 end, i.e. End(t1) == End(t2) + delay.
ENDS_AT_END,
/// t1 ends at t2 start, i.e. End(t1) == Start(t2) + delay.
ENDS_AT_START,
/// t1 starts after t2 end, i.e. Start(t1) >= End(t2) + delay.
STARTS_AFTER_END,
/// t1 starts after t2 start, i.e. Start(t1) >= Start(t2) + delay.
STARTS_AFTER_START,
/// t1 starts at t2 end, i.e. Start(t1) == End(t2) + delay.
STARTS_AT_END,
/// t1 starts at t2 start, i.e. Start(t1) == Start(t2) + delay.
STARTS_AT_START,
/// STARTS_AT_START and ENDS_AT_END at the same time.
/// t1 starts at t2 start, i.e. Start(t1) == Start(t2) + delay.
/// t1 ends at t2 end, i.e. End(t1) == End(t2).
STAYS_IN_SYNC
};
/// This enum is used in Solver::MakeIntervalVarRelation to specify the
/// temporal relation between an interval t and an integer d.
enum UnaryIntervalRelation {
/// t ends after d, i.e. End(t) >= d.
ENDS_AFTER,
/// t ends at d, i.e. End(t) == d.
ENDS_AT,
/// t ends before d, i.e. End(t) <= d.
ENDS_BEFORE,
/// t starts after d, i.e. Start(t) >= d.
STARTS_AFTER,
/// t starts at d, i.e. Start(t) == d.
STARTS_AT,
/// t starts before d, i.e. Start(t) <= d.
STARTS_BEFORE,
/// STARTS_BEFORE and ENDS_AFTER at the same time, i.e. d is in t.
/// t starts before d, i.e. Start(t) <= d.
/// t ends after d, i.e. End(t) >= d.
CROSS_DATE,
/// STARTS_AFTER or ENDS_BEFORE, i.e. d is not in t.
/// t starts after d, i.e. Start(t) >= d.
/// t ends before d, i.e. End(t) <= d.
AVOID_DATE
};
/// The Solver is responsible for creating the search tree. Thanks to the
/// DecisionBuilder, it creates a new decision with two branches at each node:
/// left and right.
/// The DecisionModification enum is used to specify how the branch selector
/// should behave.
enum DecisionModification {
/// Keeps the default behavior, i.e. apply left branch first, and then right
/// branch in case of backtracking.
NO_CHANGE,
/// Right branches are ignored. This is used to make the code faster when
/// backtrack makes no sense or is not useful.
/// This is faster as there is no need to create one new node per decision.
KEEP_LEFT,
/// Left branches are ignored. This is used to make the code faster when
/// backtrack makes no sense or is not useful.
/// This is faster as there is no need to create one new node per decision.
KEEP_RIGHT,
/// Backtracks to the previous decisions, i.e. left and right branches are
/// not applied.
KILL_BOTH,
/// Applies right branch first. Left branch will be applied in case of
/// backtracking.
SWITCH_BRANCHES
};
/// This enum is used internally in private methods Solver::PushState and
/// Solver::PopState to tag states in the search tree.
enum MarkerType { SENTINEL, SIMPLE_MARKER, CHOICE_POINT, REVERSIBLE_ACTION };
/// This enum represents the state of the solver w.r.t. the search.
enum SolverState {
/// Before search, after search.
OUTSIDE_SEARCH,
/// Executing the root node.
IN_ROOT_NODE,
/// Executing the search code.
IN_SEARCH,
/// After successful NextSolution and before EndSearch.
AT_SOLUTION,
/// After failed NextSolution and before EndSearch.
NO_MORE_SOLUTIONS,
/// After search, the model is infeasible.
PROBLEM_INFEASIBLE
};
/// Optimization directions.
enum OptimizationDirection { NOT_SET, MAXIMIZATION, MINIMIZATION };
/// Callback typedefs
typedef std::function<int64(int64)> IndexEvaluator1;
typedef std::function<int64(int64, int64)> IndexEvaluator2;
typedef std::function<int64(int64, int64, int64)> IndexEvaluator3;
typedef std::function<bool(int64)> IndexFilter1;
typedef std::function<IntVar*(int64)> Int64ToIntVar;
typedef std::function<int64(Solver* solver, const std::vector<IntVar*>& vars,
int64 first_unbound, int64 last_unbound)>
VariableIndexSelector;
typedef std::function<int64(const IntVar* v, int64 id)> VariableValueSelector;
typedef std::function<bool(int64, int64, int64)> VariableValueComparator;
typedef std::function<DecisionModification()> BranchSelector;
// TODO(user): wrap in swig.
typedef std::function<void(Solver*)> Action;
typedef std::function<void()> Closure;
/// Solver API
explicit Solver(const std::string& name);
Solver(const std::string& name, const ConstraintSolverParameters& parameters);
~Solver();
/// Stored Parameters.
ConstraintSolverParameters parameters() const { return parameters_; }
/// Create a ConstraintSolverParameters proto with all the default values.
// TODO(user): Move to constraint_solver_parameters.h.
static ConstraintSolverParameters DefaultSolverParameters();
/// reversibility
/// SaveValue() saves the value of the corresponding object. It must be
/// called before modifying the object. The value will be restored upon
/// backtrack.
template <class T>
void SaveValue(T* o) {
InternalSaveValue(o);
}
/// Registers the given object as being reversible. By calling this method,
/// the caller gives ownership of the object to the solver, which will
/// delete it when there is a backtrack out of the current state.
///
/// Returns the argument for convenience: this way, the caller may directly
/// invoke a constructor in the argument, without having to store the pointer
/// first.
///
/// This function is only for users that define their own subclasses of
/// BaseObject: for all subclasses predefined in the library, the
/// corresponding factory methods (e.g., MakeIntVar(...),
/// MakeAllDifferent(...) already take care of the registration.
template <typename T>
T* RevAlloc(T* object) {
return reinterpret_cast<T*>(SafeRevAlloc(object));
}
/// Like RevAlloc() above, but for an array of objects: the array
/// must have been allocated with the new[] operator. The entire array
/// will be deleted when backtracking out of the current state.
///
/// This method is valid for arrays of int, int64, uint64, bool,
/// BaseObject*, IntVar*, IntExpr*, and Constraint*.
template <typename T>
T* RevAllocArray(T* object) {
return reinterpret_cast<T*>(SafeRevAllocArray(object));
}
/// 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 <tt>state() ==
/// OUTSIDE_SEARCH</tt>). Most users should only use AddConstraint in this
/// way. In this case, the constraint will belong to the model forever: it
/// cannot not 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(...));
void AddConstraint(Constraint* const c);
/// Adds 'constraint' to the solver and marks it as a cast constraint, that
/// is, a constraint created calling Var() on an expression. This is used
/// internally.
void AddCastConstraint(CastConstraint* const constraint,
IntVar* const target_var, IntExpr* const expr);
/// @{
/// 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().
///
/// @param db The decision builder that will generate the search tree.
/// @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.
bool Solve(DecisionBuilder* const db,
const std::vector<SearchMonitor*>& monitors);
bool Solve(DecisionBuilder* const db);
bool Solve(DecisionBuilder* const db, SearchMonitor* const m1);
bool Solve(DecisionBuilder* const db, SearchMonitor* const m1,
SearchMonitor* const m2);
bool Solve(DecisionBuilder* const db, SearchMonitor* const m1,
SearchMonitor* const m2, SearchMonitor* const m3);
bool Solve(DecisionBuilder* const db, SearchMonitor* const m1,
SearchMonitor* const m2, SearchMonitor* const m3,
SearchMonitor* const m4);
/// @}
/// @{
/// Decomposed search.
/// The code for a top level search should look like
/// solver->NewSearch(db);
/// while (solver->NextSolution()) {
/// //.. use the current solution
/// }
/// solver()->EndSearch();
void NewSearch(DecisionBuilder* const db,
const std::vector<SearchMonitor*>& monitors);
void NewSearch(DecisionBuilder* const db);
void NewSearch(DecisionBuilder* const db, SearchMonitor* const m1);
void NewSearch(DecisionBuilder* const db, SearchMonitor* const m1,
SearchMonitor* const m2);
void NewSearch(DecisionBuilder* const db, SearchMonitor* const m1,
SearchMonitor* const m2, SearchMonitor* const m3);
void NewSearch(DecisionBuilder* const db, SearchMonitor* const m1,
SearchMonitor* const m2, SearchMonitor* const m3,
SearchMonitor* const m4);
bool NextSolution();
void RestartSearch();
void EndSearch();
/// @}
/// 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.
bool SolveAndCommit(DecisionBuilder* const db,
const std::vector<SearchMonitor*>& monitors);
bool SolveAndCommit(DecisionBuilder* const db);
bool SolveAndCommit(DecisionBuilder* const db, SearchMonitor* const m1);
bool SolveAndCommit(DecisionBuilder* const db, SearchMonitor* const m1,
SearchMonitor* const m2);
bool SolveAndCommit(DecisionBuilder* const db, SearchMonitor* const m1,
SearchMonitor* const m2, SearchMonitor* const m3);
/// Checks whether the given assignment satisfies all relevant constraints.
bool CheckAssignment(Assignment* const solution);
/// 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.
bool CheckConstraint(Constraint* const ct);
/// State of the solver.
SolverState state() const { return state_; }
/// Abandon the current branch in the search tree. A backtrack will follow.
void Fail();
#if !defined(SWIG)
/// When SaveValue() is not the best way to go, one can create a reversible
/// action that will be called upon backtrack. The "fast" parameter
/// indicates whether we need restore all values saved through SaveValue()
/// before calling this method.
void AddBacktrackAction(Action a, bool fast);
#endif /// !defined(SWIG)
/// misc debug std::string.
std::string DebugString() const;
/// Current memory usage in bytes
static int64 MemoryUsage();
/// The 'absolute time' as seen by the solver. Unless a user-provided clock
/// was injected via SetClock() (eg. for unit tests), this is a real walltime,
/// shifted so that it was 0 at construction. All so-called "walltime" limits
/// are relative to this time.
absl::Time Now() const;
/// DEPRECATED: Use Now() instead.
/// Time elapsed, in ms since the creation of the solver.
int64 wall_time() const;
/// The number of branches explored since the creation of the solver.
int64 branches() const { return branches_; }
/// The number of solutions found since the start of the search.
int64 solutions() const;
/// The number of unchecked solutions found by local search.
int64 unchecked_solutions() const;
/// The number of demons executed during search for a given priority.
int64 demon_runs(DemonPriority p) const { return demon_runs_[p]; }
/// The number of failures encountered since the creation of the solver.
int64 failures() const { return fails_; }
/// The number of neighbors created.
int64 neighbors() const { return neighbors_; }
/// The number of filtered neighbors (neighbors accepted by filters).
int64 filtered_neighbors() const { return filtered_neighbors_; }
/// The number of accepted neighbors.
int64 accepted_neighbors() const { return accepted_neighbors_; }
/// 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.
uint64 stamp() const;
/// The fail_stamp() is incremented after each backtrack.
uint64 fail_stamp() const;
/// The direction of optimization, getter and setter.
OptimizationDirection optimization_direction() const {
return optimization_direction_;
}
void set_optimization_direction(OptimizationDirection direction) {
optimization_direction_ = direction;