forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model.h
1301 lines (1075 loc) · 43.5 KB
/
cp_model.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-2021 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.
/**
* \file
* This file implements a wrapper around the CP-SAT model proto.
*
* Here is a minimal example that shows how to create a model, solve it, and
* print out the solution.
* \code
CpModelBuilder cp_model;
Domain all_animals(0, 20);
IntVar rabbits = cp_model.NewIntVar(all_animals).WithName("rabbits");
IntVar pheasants = cp_model.NewIntVar(all_animals).WithName("pheasants");
cp_model.AddEquality(LinearExpr::Sum({rabbits, pheasants}), 20);
cp_model.AddEquality(LinearExpr::ScalProd({rabbits, pheasants}, {4, 2}), 56);
const CpSolverResponse response = Solve(cp_model.Build());
if (response.status() == CpSolverStatus::FEASIBLE) {
LOG(INFO) << SolutionIntegerValue(response, rabbits)
<< " rabbits, and " << SolutionIntegerValue(response, pheasants)
<< " pheasants.";
}
\endcode
*/
#ifndef OR_TOOLS_SAT_CP_MODEL_H_
#define OR_TOOLS_SAT_CP_MODEL_H_
#include <cstdint>
#include <initializer_list>
#include <limits>
#include <string>
#include "absl/container/flat_hash_map.h"
#include "absl/types/span.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_solver.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/sat/model.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/util/sorted_interval_list.h"
namespace operations_research {
namespace sat {
class CpModelBuilder;
class LinearExpr;
class IntVar;
/**
* A Boolean variable.
*
* This class refer to an IntegerVariableProto with domain [0, 1] or to its
* logical negation (Not). This is called a Boolean Literal in other context.
*
* This can only be constructed via \c CpModelBuilder.NewBoolVar().
*/
class BoolVar {
public:
/// A default constructed BoolVar can be used to mean not defined yet.
/// However, it shouldn't be passed to any of the functions in this file.
/// Doing so will crash in debug mode and will result in an invalid model in
/// opt mode.
BoolVar();
/// Sets the name of the variable.
/// Note that this will always set the "positive" version of this Boolean.
BoolVar WithName(const std::string& name);
/// Returns the name of the variable.
std::string Name() const;
/// Returns the logical negation of the current Boolean variable.
BoolVar Not() const { return BoolVar(NegatedRef(index_), builder_); }
bool operator==(const BoolVar& other) const {
return other.builder_ == builder_ && other.index_ == index_;
}
bool operator!=(const BoolVar& other) const {
return other.builder_ != builder_ || other.index_ != index_;
}
std::string DebugString() const;
/**
* Returns the index of the variable in the model.
*
* Warning: If the variable is the negation of another variable v, its index
* is -v.index() - 1. So this can be negative.
*/
int index() const { return index_; }
private:
friend class CircuitConstraint;
friend class Constraint;
friend class CpModelBuilder;
friend class DoubleLinearExpr;
friend class IntVar;
friend class IntervalVar;
friend class MultipleCircuitConstraint;
friend class LinearExpr;
friend class ReservoirConstraint;
friend bool SolutionBooleanValue(const CpSolverResponse& r, BoolVar x);
BoolVar(int index, CpModelBuilder* builder);
CpModelBuilder* builder_ = nullptr;
int index_ = std::numeric_limits<int32_t>::min();
};
std::ostream& operator<<(std::ostream& os, const BoolVar& var);
/**
* A convenient wrapper so we can write Not(x) instead of x.Not() which is
* sometimes clearer.
*/
BoolVar Not(BoolVar x);
/**
* An integer variable.
*
* This class wraps an IntegerVariableProto.
* This can only be constructed via \c CpModelBuilder.NewIntVar().
*/
class IntVar {
public:
/// A default constructed IntVar can be used to mean not defined yet.
/// However, it shouldn't be passed to any of the functions in this file.
/// Doing so will crash in debug mode and will result in an invalid model in
/// opt mode.
IntVar();
/// Cast BoolVar -> IntVar.
/// The IntVar will take the value 1 (when the bool is true) and 0 otherwise.
///
/// Warning: If you construct an IntVar from a negated BoolVar, this might
/// create a new variable in the model. Otherwise this just point to the same
/// underlying variable.
IntVar(const BoolVar& var); // NOLINT(runtime/explicit)
/// Cast IntVar -> BoolVar.
///
/// Warning: The domain of the var must be within {0,1}. If not, we crash
/// in debug mode, and in opt mode you will get an invalid model if you use
/// this BoolVar anywhere since it will not have a valid domain.
BoolVar ToBoolVar() const;
/// Sets the name of the variable.
IntVar WithName(const std::string& name);
/// Returns the name of the variable (or the empty string if not set).
std::string Name() const;
bool operator==(const IntVar& other) const {
return other.builder_ == builder_ && other.index_ == index_;
}
bool operator!=(const IntVar& other) const {
return other.builder_ != builder_ || other.index_ != index_;
}
// Returns the domain of the variable.
::operations_research::Domain Domain() const;
std::string DebugString() const;
/// Returns the index of the variable in the model. This will be non-negative.
int index() const { return index_; }
/// Deprecated. Just do var + cte where needed.
LinearExpr AddConstant(int64_t value) const;
private:
friend class BoolVar;
friend class CpModelBuilder;
friend class CumulativeConstraint;
friend class DoubleLinearExpr;
friend class LinearExpr;
friend class IntervalVar;
friend class ReservoirConstraint;
friend int64_t SolutionIntegerValue(const CpSolverResponse& r,
const LinearExpr& expr);
IntVar(int index, CpModelBuilder* builder);
CpModelBuilder* builder_ = nullptr;
int index_ = std::numeric_limits<int32_t>::min();
};
std::ostream& operator<<(std::ostream& os, const IntVar& var);
/**
* A dedicated container for linear expressions.
*
* With the use of implicit constructors, it can accept integer values, Boolean
* and Integer variables. Note that Not(x) will be silently transformed into 1 -
* x when added to the linear expression. It also support operator overloads to
* construct the linear expression naturally.
*
* Furthermore, static methods allow to construct a linear expression from sums
* or scalar products.
*
* Usage:
* \code
CpModelBuilder cp_model;
IntVar x = model.NewIntVar({0, 10}).WithName("x");
IntVar y = model.NewIntVar({0, 10}).WithName("y");
BoolVar b = model.NewBoolVar().WithName("b");
BoolVar c = model.NewBoolVar().WithName("c");
LinearExpr e1(x); // Or e1 = x.
LinearExpr e2 = x + y + 5;
LinearExpr e3 = 2 * x - y;
LinearExpr e4 = b;
LinearExpr e5 = b.Not(); // 1 - b.
std::vector<BoolVar> bools = {b, Not(c)};
LinearExpr e6 = LinearExpr::Sum(bools); // b + 1 - c;
LinearExpr e7 = -3 * b + Not(c); // -3 * b + 1 - c;
\endcode
* This can be used implicitly in some of the CpModelBuilder methods.
* \code
cp_model.AddGreaterThan(x, 5);
cp_model.AddEquality(x, y + 5);
\endcode
*/
class LinearExpr {
public:
/// Creates an empty linear expression with value zero.
LinearExpr() = default;
/// Constructs a linear expression from a Boolean variable.
/// It deals with logical negation correctly.
LinearExpr(BoolVar var); // NOLINT(runtime/explicit)
/// Constructs a linear expression from an integer variable.
LinearExpr(IntVar var); // NOLINT(runtime/explicit)
/// Constructs a constant linear expression.
LinearExpr(int64_t constant); // NOLINT(runtime/explicit)
/// Constructs the sum of a list of variables.
static LinearExpr Sum(absl::Span<const IntVar> vars);
/// Constructs the sum of a list of Boolean variables.
static LinearExpr Sum(absl::Span<const BoolVar> vars);
/// Constructs the sum of a list of variables.
// TODO(user): Remove when the operators + and * are implemented.
static LinearExpr Sum(std::initializer_list<IntVar> vars);
/// Constructs the scalar product of variables and coefficients.
static LinearExpr ScalProd(absl::Span<const IntVar> vars,
absl::Span<const int64_t> coeffs);
/// Constructs the scalar product of Boolean variables and coefficients.
static LinearExpr ScalProd(absl::Span<const BoolVar> vars,
absl::Span<const int64_t> coeffs);
/// Constructs the scalar product of variables and coefficients.
// TODO(user): Remove when the operators + and * are implemented.
static LinearExpr ScalProd(std::initializer_list<IntVar> vars,
absl::Span<const int64_t> coeffs);
/// Constructs var * coefficient.
static LinearExpr Term(IntVar var, int64_t coefficient);
/// Constructs bool * coefficient.
static LinearExpr Term(BoolVar var, int64_t coefficient);
/// Deprecated. Use Sum() instead.
static LinearExpr BooleanSum(absl::Span<const BoolVar> vars);
/// Deprecated. Use ScalProd() instead.
static LinearExpr BooleanScalProd(absl::Span<const BoolVar> vars,
absl::Span<const int64_t> coeffs);
/// Constructs a linear expr from its proto representation.
static LinearExpr FromProto(const LinearExpressionProto& proto);
// Operators.
LinearExpr& operator+=(const LinearExpr& other);
LinearExpr& operator-=(const LinearExpr& other);
LinearExpr& operator*=(int64_t factor);
// Deprecated. Use operators instead.
LinearExpr& AddConstant(int64_t value);
LinearExpr& AddVar(IntVar var);
LinearExpr& AddVar(BoolVar var);
LinearExpr& AddTerm(BoolVar var, int64_t coeff);
LinearExpr& AddTerm(IntVar var, int64_t coeff);
LinearExpr& AddExpression(const LinearExpr& expr) { return *this += expr; }
/// Returns the vector of variable indices.
const std::vector<int>& variables() const { return variables_; }
/// Returns the vector of coefficients.
const std::vector<int64_t>& coefficients() const { return coefficients_; }
/// Returns true if the expression has no variables.
const bool IsConstant() const { return variables_.empty(); }
/// Returns the constant term.
int64_t constant() const { return constant_; }
/**
* Debug string. If the CpModelBuilder is passed, the string will include
* variable names and domains. Otherwise, you will get a shorter string with
* only variable indices.
*/
std::string DebugString(const CpModelProto* proto = nullptr) const;
private:
std::vector<int> variables_;
std::vector<int64_t> coefficients_;
int64_t constant_ = 0;
};
std::ostream& operator<<(std::ostream& os, const LinearExpr& e);
/**
* A dedicated container for linear expressions with double coefficients.
*
* This class helps building and manipulating linear expressions.
* Note that Not(x) will be silently transformed into 1 - x when added to the
* linear expression.
*
* Furthermore, static methods allows sums and scalar products, with or without
* an additional constant.
*
* Usage:
* \code
CpModelBuilder cp_model;
IntVar x = model.NewIntVar({0, 10}).WithName("x");
IntVar y = model.NewIntVar({0, 10}).WithName("y");
BoolVar b = model.NewBoolVar().WithName("b");
BoolVar c = model.NewBoolVar().WithName("c");
DoubleLinearExpr e1(x); // e1 = x.
// e2 = x + y + 5
DoubleLinearExpr e2 = DoubleLinearExpr::Sum({x, y}).AddConstant(5.0);
// e3 = 2 * x - y
DoubleLinearExpr e3 = DoubleLinearExpr::ScalProd({x, y}, {2, -1});
DoubleLinearExpr e4(b); // e4 = b.
DoubleLinearExpr e5(b.Not()); // e5 = 1 - b.
// If passing a std::vector<BoolVar>, a specialized method must be called.
std::vector<BoolVar> bools = {b, Not(c)};
DoubleLinearExpr e6 = DoubleLinearExpr::Sum(bools); // e6 = b + 1 - c;
// e7 = -3.0 * b + 1.5 - 1.5 * c;
DoubleLinearExpr e7 = DoubleLinearExpr::ScalProd(bools, {-3.0, 1.5});
\endcode
* This can be used in the objective definition.
* \code
// Minimize 3.4 * y + 5.2
cp_model.Minimize(DoubleLinearExpr::Term(y, 3.4).AddConstant(5.2));
\endcode
*/
class DoubleLinearExpr {
public:
DoubleLinearExpr();
/// Constructs a linear expression from a Boolean variable.
/// It deals with logical negation correctly.
explicit DoubleLinearExpr(BoolVar var);
/// Constructs a linear expression from an integer variable.
explicit DoubleLinearExpr(IntVar var);
/// Constructs a constant linear expression.
explicit DoubleLinearExpr(double constant);
/// Adds a constant value to the linear expression.
DoubleLinearExpr& operator+=(double value);
/// Adds a single integer variable to the linear expression.
DoubleLinearExpr& operator+=(IntVar var);
DoubleLinearExpr& operator+=(BoolVar var);
/// Adds another linear expression to the linear expression.
DoubleLinearExpr& operator+=(const DoubleLinearExpr& expr);
/// Adds a term (var * coeff) to the linear expression.
DoubleLinearExpr& AddTerm(IntVar var, double coeff);
DoubleLinearExpr& AddTerm(BoolVar var, double coeff);
/// Deprecated. Use +=.
DoubleLinearExpr& AddConstant(double constant);
/// Adds a constant value to the linear expression.
DoubleLinearExpr& operator-=(double value);
/// Adds a single integer variable to the linear expression.
DoubleLinearExpr& operator-=(IntVar var);
/// Adds another linear expression to the linear expression.
DoubleLinearExpr& operator-=(const DoubleLinearExpr& expr);
/// Multiply the linear expression by a constant.
DoubleLinearExpr& operator*=(double coeff);
/// Constructs the sum of a list of variables.
static DoubleLinearExpr Sum(absl::Span<const IntVar> vars);
/// Constructs the sum of a list of Boolean variables.
static DoubleLinearExpr Sum(absl::Span<const BoolVar> vars);
/// Constructs the sum of a list of variables.
static DoubleLinearExpr Sum(std::initializer_list<IntVar> vars);
/// Constructs the scalar product of variables and coefficients.
static DoubleLinearExpr ScalProd(absl::Span<const IntVar> vars,
absl::Span<const double> coeffs);
/// Constructs the scalar product of Boolean variables and coefficients.
static DoubleLinearExpr ScalProd(absl::Span<const BoolVar> vars,
absl::Span<const double> coeffs);
/// Constructs the scalar product of variables and coefficients.
static DoubleLinearExpr ScalProd(std::initializer_list<IntVar> vars,
absl::Span<const double> coeffs);
/// Returns the vector of variable indices.
const std::vector<int>& variables() const { return variables_; }
/// Returns the vector of coefficients.
const std::vector<double>& coefficients() const { return coefficients_; }
// Returns true if the expression has no variable.
const bool IsConstant() const { return variables_.empty(); }
/// Returns the constant term.
double constant() const { return constant_; }
/// Debug string. See the documentation for LinearExpr::DebugString().
std::string DebugString(const CpModelProto* proto = nullptr) const;
private:
std::vector<int> variables_;
std::vector<double> coefficients_;
double constant_ = 0;
};
std::ostream& operator<<(std::ostream& os, const DoubleLinearExpr& e);
/**
* Represents a Interval variable.
*
* An interval variable is both a constraint and a variable. It is defined by
* three objects: start, size, and end. All three can be an integer variable, a
* constant, or an affine expression.
*
* It is a constraint because, internally, it enforces that start + size == end.
*
* It is also a variable as it can appear in specific scheduling constraints:
* NoOverlap, NoOverlap2D, Cumulative.
*
* Optionally, a presence literal can be added to this constraint. This presence
* literal is understood by the same constraints. These constraints ignore
* interval variables with precence literals assigned to false. Conversely,
* these constraints will also set these presence literals to false if they
* cannot fit these intervals into the schedule.
*
* It can only be constructed via \c CpModelBuilder.NewIntervalVar().
*/
class IntervalVar {
public:
/// A default constructed IntervalVar can be used to mean not defined yet.
/// However, it shouldn't be passed to any of the functions in this file.
/// Doing so will crash in debug mode and will result in an invalid model in
/// opt mode.
IntervalVar();
/// Sets the name of the variable.
IntervalVar WithName(const std::string& name);
/// Returns the name of the interval (or the empty string if not set).
std::string Name() const;
/// Returns the start linear expression. Note that this rebuilds the
/// expression each time this method is called.
LinearExpr StartExpr() const;
/// Returns the size linear expression. Note that this rebuilds the
/// expression each time this method is called.
LinearExpr SizeExpr() const;
/// Returns the end linear expression. Note that this rebuilds the
/// expression each time this method is called.
LinearExpr EndExpr() const;
/**
* Returns a BoolVar indicating the presence of this interval.
*
* It returns \c CpModelBuilder.TrueVar() if the interval is not optional.
*/
BoolVar PresenceBoolVar() const;
/// Equality test with another interval variable.
bool operator==(const IntervalVar& other) const {
return other.builder_ == builder_ && other.index_ == index_;
}
/// Difference test with another interval variable.
bool operator!=(const IntervalVar& other) const {
return other.builder_ != builder_ || other.index_ != index_;
}
/// Returns a debug string.
std::string DebugString() const;
/// Returns the index of the interval constraint in the model.
int index() const { return index_; }
private:
friend class CpModelBuilder;
friend class CumulativeConstraint;
friend class NoOverlap2DConstraint;
friend std::ostream& operator<<(std::ostream& os, const IntervalVar& var);
IntervalVar(int index, CpModelBuilder* builder);
CpModelBuilder* builder_ = nullptr;
int index_ = std::numeric_limits<int32_t>::min();
};
std::ostream& operator<<(std::ostream& os, const IntervalVar& var);
/**
* A constraint.
*
* This class enables you to modify the constraint that was previously added to
* the model.
*
* The constraint must be built using the different \c CpModelBuilder::AddXXX
* methods.
*/
class Constraint {
public:
/**
* The constraint will be enforced iff all literals listed here are true.
*
* If this is empty, then the constraint will always be enforced. An enforced
* constraint must be satisfied, and an un-enforced one will simply be
* ignored.
*
* This is also called half-reification. To have an equivalence between a
* literal and a constraint (full reification), one must add both a constraint
* (controlled by a literal l) and its negation (controlled by the negation of
* l).
*
* Important: as of September 2018, only a few constraint support enforcement:
* - bool_or, bool_and, linear: fully supported.
* - interval: only support a single enforcement literal.
* - other: no support (but can be added on a per-demand basis).
*/
Constraint OnlyEnforceIf(absl::Span<const BoolVar> literals);
/// See OnlyEnforceIf(absl::Span<const BoolVar> literals).
Constraint OnlyEnforceIf(BoolVar literal);
/// Sets the name of the constraint.
Constraint WithName(const std::string& name);
/// Returns the name of the constraint (or the empty string if not set).
const std::string& Name() const;
/// Returns the underlying protobuf object (useful for testing).
const ConstraintProto& Proto() const { return *proto_; }
/// Returns the mutable underlying protobuf object (useful for model edition).
ConstraintProto* MutableProto() const { return proto_; }
protected:
friend class CpModelBuilder;
explicit Constraint(ConstraintProto* proto);
ConstraintProto* proto_ = nullptr;
};
/**
* Specialized circuit constraint.
*
* This constraint allows adding arcs to the circuit constraint incrementally.
*/
class CircuitConstraint : public Constraint {
public:
/**
* Add an arc to the circuit.
*
* @param tail the index of the tail node.
* @param head the index of the head node.
* @param literal it will be set to true if the arc is selected.
*/
void AddArc(int tail, int head, BoolVar literal);
private:
friend class CpModelBuilder;
using Constraint::Constraint;
};
/**
* Specialized circuit constraint.
*
* This constraint allows adding arcs to the multiple circuit constraint
* incrementally.
*/
class MultipleCircuitConstraint : public Constraint {
public:
/**
* Add an arc to the circuit.
*
* @param tail the index of the tail node.
* @param head the index of the head node.
* @param literal it will be set to true if the arc is selected.
*/
void AddArc(int tail, int head, BoolVar literal);
private:
friend class CpModelBuilder;
using Constraint::Constraint;
};
/**
* Specialized assignment constraint.
*
* This constraint allows adding tuples to the allowed/forbidden assignment
* constraint incrementally.
*/
class TableConstraint : public Constraint {
public:
/// Adds a tuple of possible values to the constraint.
void AddTuple(absl::Span<const int64_t> tuple);
private:
friend class CpModelBuilder;
using Constraint::Constraint;
};
/**
* Specialized reservoir constraint.
*
* This constraint allows adding emptying/refilling events to the reservoir
* constraint incrementally.
*/
class ReservoirConstraint : public Constraint {
public:
/**
* Adds a mandatory event
*
* It will increase the used capacity by `level_change` at time `time`.
*/
void AddEvent(LinearExpr time, int64_t level_change);
/**
* Adds a optional event
*
* If `c is_active is true, It will increase the used capacity by
* `level_change` at time `c time.
*/
void AddOptionalEvent(LinearExpr time, int64_t level_change,
BoolVar is_active);
private:
friend class CpModelBuilder;
ReservoirConstraint(ConstraintProto* proto, CpModelBuilder* builder);
CpModelBuilder* builder_;
};
/**
* Specialized automaton constraint.
*
* This constraint allows adding transitions to the automaton constraint
* incrementally.
*/
class AutomatonConstraint : public Constraint {
public:
/// Adds a transitions to the automaton.
void AddTransition(int tail, int head, int64_t transition_label);
private:
friend class CpModelBuilder;
using Constraint::Constraint;
};
/**
* Specialized no_overlap2D constraint.
*
* This constraint allows adding rectangles to the no_overlap2D
* constraint incrementally.
*/
class NoOverlap2DConstraint : public Constraint {
public:
/// Adds a rectangle (parallel to the axis) to the constraint.
void AddRectangle(IntervalVar x_coordinate, IntervalVar y_coordinate);
private:
friend class CpModelBuilder;
using Constraint::Constraint;
};
/**
* Specialized cumulative constraint.
*
* This constraint allows adding fixed or variables demands to the cumulative
* constraint incrementally.
*
* One cannot mix the AddDemand() and AddDemandWithEnergy() APIs in the same
* cumulative API. Either always supply energy info, or never.
*/
class CumulativeConstraint : public Constraint {
public:
/// Adds a pair (interval, demand) to the constraint.
void AddDemand(IntervalVar interval, LinearExpr demand);
private:
friend class CpModelBuilder;
CumulativeConstraint(ConstraintProto* proto, CpModelBuilder* builder);
CpModelBuilder* builder_;
};
/**
* Wrapper class around the cp_model proto.
*
* This class provides two types of methods:
* - NewXXX to create integer, boolean, or interval variables.
* - AddXXX to create new constraints and add them to the model.
*/
class CpModelBuilder {
public:
/// Sets the name of the model.
void SetName(const std::string& name);
/// Creates an integer variable with the given domain.
IntVar NewIntVar(const Domain& domain);
/// Creates a Boolean variable.
BoolVar NewBoolVar();
/// Creates a constant variable. This is a shortcut for
/// NewVariable(Domain(value)).but it will return the same variable if used
/// twice with the same constant.
IntVar NewConstant(int64_t value);
/// Creates an always true Boolean variable.
/// If this is called multiple times, the same variable will always be
/// returned.
BoolVar TrueVar();
/// Creates an always false Boolean variable.
/// If this is called multiple times, the same variable will always be
/// returned.
BoolVar FalseVar();
/// Creates an interval variable from 3 affine expressions.
IntervalVar NewIntervalVar(const LinearExpr& start, const LinearExpr& size,
const LinearExpr& end);
/// Creates an interval variable with a fixed size.
IntervalVar NewFixedSizeIntervalVar(const LinearExpr& start, int64_t size);
/// Creates an optional interval variable from 3 affine expressions and a
/// Boolean variable.
IntervalVar NewOptionalIntervalVar(const LinearExpr& start,
const LinearExpr& size,
const LinearExpr& end, BoolVar presence);
/// Creates an optional interval variable with a fixed size.
IntervalVar NewOptionalFixedSizeIntervalVar(const LinearExpr& start,
int64_t size, BoolVar presence);
/// Adds the constraint that at least one of the literals must be true.
Constraint AddBoolOr(absl::Span<const BoolVar> literals);
/// Adds the constraint that all literals must be true.
Constraint AddBoolAnd(absl::Span<const BoolVar> literals);
/// Adds the constraint that an odd number of literals is true.
Constraint AddBoolXor(absl::Span<const BoolVar> literals);
/// Adds a => b.
Constraint AddImplication(BoolVar a, BoolVar b) {
return AddBoolOr({a.Not(), b});
}
/// Adds left == right.
Constraint AddEquality(const LinearExpr& left, const LinearExpr& right);
/// Adds left >= right.
Constraint AddGreaterOrEqual(const LinearExpr& left, const LinearExpr& right);
/// Adds left > right.
Constraint AddGreaterThan(const LinearExpr& left, const LinearExpr& right);
/// Adds left <= right.
Constraint AddLessOrEqual(const LinearExpr& left, const LinearExpr& right);
/// Adds left < right.
Constraint AddLessThan(const LinearExpr& left, const LinearExpr& right);
/// Adds expr in domain.
Constraint AddLinearConstraint(const LinearExpr& expr, const Domain& domain);
/// Adds left != right.
Constraint AddNotEqual(const LinearExpr& left, const LinearExpr& right);
/// This constraint forces all variables to have different values.
Constraint AddAllDifferent(absl::Span<const IntVar> vars);
/// This constraint forces all expressions to have different values.
Constraint AddAllDifferent(absl::Span<const LinearExpr> exprs);
/// This constraint forces all expressions to have different values.
Constraint AddAllDifferent(std::initializer_list<LinearExpr> exprs);
/// Adds the element constraint: variables[index] == target
Constraint AddVariableElement(IntVar index,
absl::Span<const IntVar> variables,
IntVar target);
/// Adds the element constraint: values[index] == target
Constraint AddElement(IntVar index, absl::Span<const int64_t> values,
IntVar target);
/**
* Adds a circuit constraint.
*
* The circuit constraint is defined on a graph where the arc presence is
* controlled by literals. That is the arc is part of the circuit of its
* corresponding literal is assigned to true.
*
* For now, we ignore node indices with no incident arc. All the other nodes
* must have exactly one incoming and one outgoing selected arc (i.e. literal
* at true). All the selected arcs that are not self-loops must form a single
* circuit.
*
* It returns a circuit constraint that allows adding arcs incrementally after
* construction.
*
*/
CircuitConstraint AddCircuitConstraint();
/**
* Adds a multiple circuit constraint, aka the "VRP" (Vehicle Routing Problem)
* constraint.
*
* The direct graph where arc #i (from tails[i] to head[i]) is present iff
* literals[i] is true must satisfy this set of properties:
* - #incoming arcs == 1 except for node 0.
* - #outgoing arcs == 1 except for node 0.
* - for node zero, #incoming arcs == #outgoing arcs.
* - There are no duplicate arcs.
* - Self-arcs are allowed except for node 0.
* - There is no cycle in this graph, except through node 0.
*/
MultipleCircuitConstraint AddMultipleCircuitConstraint();
/**
* Adds an allowed assignments constraint.
*
* An AllowedAssignments constraint is a constraint on an array of variables
* that forces, when all variables are fixed to a single value, that the
* corresponding list of values is equal to one of the tuples added to the
* constraint.
*
* It returns a table constraint that allows adding tuples incrementally after
* construction.
*/
TableConstraint AddAllowedAssignments(absl::Span<const IntVar> vars);
/**
* Adds an forbidden assignments constraint.
*
* A ForbiddenAssignments constraint is a constraint on an array of variables
* where the list of impossible combinations is provided in the tuples added
* to the constraint.
*
* It returns a table constraint that allows adding tuples incrementally after
* construction.
*/
TableConstraint AddForbiddenAssignments(absl::Span<const IntVar> vars);
/** An inverse constraint.
*
* It enforces that if 'variables[i]' is assigned a value
* 'j', then inverse_variables[j] is assigned a value 'i'. And vice versa.
*/
Constraint AddInverseConstraint(absl::Span<const IntVar> variables,
absl::Span<const IntVar> inverse_variables);
/**
* Adds a reservoir constraint with optional refill/emptying events.
*
* Maintain a reservoir level within bounds. The water level starts at 0, and
* at any time >= 0, it must be within min_level, and max_level. Furthermore,
* this constraints expect all times variables to be >= 0. Given an event
* (time, demand, active), if active is true, and if time is assigned a value
* t, then the level of the reservoir changes by demand (which is constant) at
* time t.
*
* Note that level_min can be > 0, or level_max can be < 0. It just forces
* some level_changes to be executed at time 0 to make sure that we are within
* those bounds with the executed level_changes. Therefore, at any time t >=
* 0: sum(level_changes[i] * actives[i] if times[i] <= t) in [min_level,
* max_level]
*
* It returns a ReservoirConstraint that allows adding optional and non
* optional events incrementally after construction.
*/
ReservoirConstraint AddReservoirConstraint(int64_t min_level,
int64_t max_level);
/**
* An automaton constraint.
*
* An automaton constraint takes a list of variables (of size n), an initial
* state, a set of final states, and a set of transitions. A transition is a
* triplet ('tail', 'head', 'label'), where 'tail' and 'head' are states,
* and 'label' is the label of an arc from 'head' to 'tail',
* corresponding to the value of one variable in the list of variables.
*
* This automaton will be unrolled into a flow with n + 1 phases. Each phase
* contains the possible states of the automaton. The first state contains the
* initial state. The last phase contains the final states.
*
* Between two consecutive phases i and i + 1, the automaton creates a set of
* arcs. For each transition (tail, head, label), it will add an arc from
* the state 'tail' of phase i and the state 'head' of phase i + 1. This arc
* labeled by the value 'label' of the variables 'variables[i]'. That is,
* this arc can only be selected if 'variables[i]' is assigned the value
* 'label'. A feasible solution of this constraint is an assignment of
* variables such that, starting from the initial state in phase 0, there is a
* path labeled by the values of the variables that ends in one of the final
* states in the final phase.
*
* It returns an AutomatonConstraint that allows adding transition
* incrementally after construction.
*/
AutomatonConstraint AddAutomaton(
absl::Span<const IntVar> transition_variables, int starting_state,
absl::Span<const int> final_states);
/// Adds target == min(vars).
Constraint AddMinEquality(const LinearExpr& target,
absl::Span<const IntVar> vars);
/// Adds target == min(exprs).
Constraint AddMinEquality(const LinearExpr& target,
absl::Span<const LinearExpr> exprs);
/// Adds target == min(exprs).
Constraint AddMinEquality(const LinearExpr& target,
std::initializer_list<LinearExpr> exprs);
// Deprecated, use AddMinEquality.
Constraint AddLinMinEquality(const LinearExpr& target,
absl::Span<const LinearExpr> exprs) {
return AddMinEquality(target, exprs);
}
/// Adds target == max(vars).
Constraint AddMaxEquality(const LinearExpr& target,
absl::Span<const IntVar> vars);
/// Adds target == max(exprs).
Constraint AddMaxEquality(const LinearExpr& target,
absl::Span<const LinearExpr> exprs);
/// Adds target == max(exprs).
Constraint AddMaxEquality(const LinearExpr& target,
std::initializer_list<LinearExpr> exprs);
// Deprecated, use AddMaxEquality.
Constraint AddLinMaxEquality(const LinearExpr& target,
absl::Span<const LinearExpr> exprs) {
return AddMaxEquality(target, exprs);
}
/// Adds target = num / denom (integer division rounded towards 0).
Constraint AddDivisionEquality(const LinearExpr& target,
const LinearExpr& numerator,