C++ Reference

C++ Reference: CP-SAT

cp_model.h
Go to the documentation of this file.
1 // Copyright 2010-2022 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
38 #ifndef OR_TOOLS_SAT_CP_MODEL_H_
39 #define OR_TOOLS_SAT_CP_MODEL_H_
40 
41 #include <cstdint>
42 #include <initializer_list>
43 #include <iosfwd>
44 #include <limits>
45 #include <ostream>
46 #include <string>
47 #include <utility>
48 #include <vector>
49 
50 #include "absl/container/flat_hash_map.h"
51 #include "absl/types/span.h"
52 #include "ortools/sat/cp_model.pb.h"
54 #include "ortools/sat/cp_model_utils.h"
55 #include "ortools/sat/model.h"
56 #include "ortools/sat/sat_parameters.pb.h"
58 
60 namespace sat {
61 
62 class CpModelBuilder;
63 class IntVar;
64 class LinearExpr;
65 
74 class BoolVar {
75  public:
80  BoolVar() = default;
81 
84  BoolVar WithName(const std::string& name);
85 
87  std::string Name() const;
88 
90  BoolVar Not() const { return BoolVar(NegatedRef(index_), builder_); }
91 
92  bool operator==(const BoolVar& other) const {
93  return other.builder_ == builder_ && other.index_ == index_;
94  }
95 
96  bool operator!=(const BoolVar& other) const {
97  return other.builder_ != builder_ || other.index_ != index_;
98  }
99 
100  std::string DebugString() const;
101 
108  int index() const { return index_; }
109 
110  private:
111  friend class CircuitConstraint;
112  friend class Constraint;
113  friend class CpModelBuilder;
114  friend class DoubleLinearExpr;
115  friend class IntVar;
116  friend class IntervalVar;
118  friend class LinearExpr;
119  friend class ReservoirConstraint;
120  friend bool SolutionBooleanValue(const CpSolverResponse& r, BoolVar x);
121 
122  BoolVar(int index, CpModelBuilder* builder);
123 
124  CpModelBuilder* builder_ = nullptr;
125  int index_ = std::numeric_limits<int32_t>::min();
126 };
127 
128 std::ostream& operator<<(std::ostream& os, const BoolVar& var);
129 
135 
142 class IntVar {
143  public:
148  IntVar() = default;
149 
156  explicit IntVar(const BoolVar& var);
157 
164 
166  IntVar WithName(const std::string& name);
167 
169  std::string Name() const;
170 
171  bool operator==(const IntVar& other) const {
172  return other.builder_ == builder_ && other.index_ == index_;
173  }
174 
175  bool operator!=(const IntVar& other) const {
176  return other.builder_ != builder_ || other.index_ != index_;
177  }
178 
179  // Returns the domain of the variable.
180  // Note that we keep the fully qualified return type as compilation fails with
181  // gcc otherwise.
183 
184  std::string DebugString() const;
185 
187  int index() const { return index_; }
188 
189  private:
190  friend class BoolVar;
191  friend class CpModelBuilder;
192  friend class CumulativeConstraint;
193  friend class DoubleLinearExpr;
194  friend class LinearExpr;
195  friend class IntervalVar;
196  friend class ReservoirConstraint;
197  friend int64_t SolutionIntegerValue(const CpSolverResponse& r,
198  const LinearExpr& expr);
199 
200  IntVar(int index, CpModelBuilder* builder);
201 
202  CpModelBuilder* builder_ = nullptr;
203  int index_ = std::numeric_limits<int32_t>::min();
204 };
205 
206 std::ostream& operator<<(std::ostream& os, const IntVar& var);
207 
241 class LinearExpr {
242  public:
244  LinearExpr() = default;
245 
246  // NOLINTBEGIN(google-explicit-constructor)
247 
251 
254 
257 
258  // NOLINTEND(google-explicit-constructor)
259 
261  static LinearExpr Sum(absl::Span<const IntVar> vars);
262 
264  static LinearExpr Sum(absl::Span<const BoolVar> vars);
265 
267  static LinearExpr WeightedSum(absl::Span<const IntVar> vars,
268  absl::Span<const int64_t> coeffs);
269 
271  static LinearExpr WeightedSum(absl::Span<const BoolVar> vars,
272  absl::Span<const int64_t> coeffs);
273 
275  static LinearExpr Term(IntVar var, int64_t coefficient);
276 
278  static LinearExpr Term(BoolVar var, int64_t coefficient);
279 
281  static LinearExpr FromProto(const LinearExpressionProto& proto);
282 
283  // Operators.
286  LinearExpr& operator*=(int64_t factor);
287 
289  const std::vector<int>& variables() const { return variables_; }
290 
292  const std::vector<int64_t>& coefficients() const { return coefficients_; }
293 
295  const bool IsConstant() const { return variables_.empty(); }
296 
298  int64_t constant() const { return constant_; }
299 
305  std::string DebugString(const CpModelProto* proto = nullptr) const;
306 
307  private:
308  std::vector<int> variables_;
309  std::vector<int64_t> coefficients_;
310  int64_t constant_ = 0;
311 };
312 
313 std::ostream& operator<<(std::ostream& os, const LinearExpr& e);
314 
346  public:
348 
351  explicit DoubleLinearExpr(BoolVar var);
352 
354  explicit DoubleLinearExpr(IntVar var);
355 
357  explicit DoubleLinearExpr(double constant);
358 
360  DoubleLinearExpr& operator+=(double value);
361 
365 
368 
370  DoubleLinearExpr& AddTerm(IntVar var, double coeff);
371  DoubleLinearExpr& AddTerm(BoolVar var, double coeff);
372 
374  DoubleLinearExpr& AddExpression(const LinearExpr& exprs, double coeff = 1.0);
375 
377  DoubleLinearExpr& operator-=(double value);
378 
381 
384 
386  DoubleLinearExpr& operator*=(double coeff);
387 
389  static DoubleLinearExpr Sum(absl::Span<const IntVar> vars);
390 
392  static DoubleLinearExpr Sum(absl::Span<const BoolVar> vars);
393 
395  static DoubleLinearExpr WeightedSum(absl::Span<const IntVar> vars,
396  absl::Span<const double> coeffs);
397 
399  static DoubleLinearExpr WeightedSum(absl::Span<const BoolVar> vars,
400  absl::Span<const double> coeffs);
401 
403  const std::vector<int>& variables() const { return variables_; }
404 
406  const std::vector<double>& coefficients() const { return coefficients_; }
407 
408  // Returns true if the expression has no variable.
409  const bool IsConstant() const { return variables_.empty(); }
410 
412  double constant() const { return constant_; }
413 
415  std::string DebugString(const CpModelProto* proto = nullptr) const;
416 
417  private:
418  std::vector<int> variables_;
419  std::vector<double> coefficients_;
420  double constant_ = 0;
421 };
422 
423 std::ostream& operator<<(std::ostream& os, const DoubleLinearExpr& e);
424 
445 class IntervalVar {
446  public:
452 
454  IntervalVar WithName(const std::string& name);
455 
457  std::string Name() const;
458 
462 
466 
470 
477 
479  bool operator==(const IntervalVar& other) const {
480  return other.builder_ == builder_ && other.index_ == index_;
481  }
482 
484  bool operator!=(const IntervalVar& other) const {
485  return other.builder_ != builder_ || other.index_ != index_;
486  }
487 
489  std::string DebugString() const;
490 
492  int index() const { return index_; }
493 
494  private:
495  friend class CpModelBuilder;
496  friend class CumulativeConstraint;
497  friend class NoOverlap2DConstraint;
498  friend std::ostream& operator<<(std::ostream& os, const IntervalVar& var);
499 
500  IntervalVar(int index, CpModelBuilder* builder);
501 
502  CpModelBuilder* builder_ = nullptr;
503  int index_ = std::numeric_limits<int32_t>::min();
504 };
505 
506 std::ostream& operator<<(std::ostream& os, const IntervalVar& var);
507 
508 // -- ABSL HASHING SUPPORT -----------------------------------------------------
509 template <typename H>
510 H AbslHashValue(H h, const IntVar& i) {
511  return H::combine(std::move(h), i.index());
512 }
513 
514 template <typename H>
515 H AbslHashValue(H h, const IntervalVar& i) {
516  return H::combine(std::move(h), i.index());
517 }
518 
528 class Constraint {
529  public:
547  Constraint OnlyEnforceIf(absl::Span<const BoolVar> literals);
548 
551 
553  Constraint WithName(const std::string& name);
554 
556  const std::string& Name() const;
557 
559  const ConstraintProto& Proto() const { return *proto_; }
560 
562  ConstraintProto* MutableProto() const { return proto_; }
563 
564  protected:
565  friend class CpModelBuilder;
566 
567  explicit Constraint(ConstraintProto* proto);
568 
569  ConstraintProto* proto_ = nullptr;
570 };
571 
578  public:
586  void AddArc(int tail, int head, BoolVar literal);
587 
588  private:
589  friend class CpModelBuilder;
590 
592 };
593 
601  public:
609  void AddArc(int tail, int head, BoolVar literal);
610 
611  private:
612  friend class CpModelBuilder;
613 
615 };
616 
623 class TableConstraint : public Constraint {
624  public:
626  void AddTuple(absl::Span<const int64_t> tuple);
627 
628  private:
629  friend class CpModelBuilder;
630 
632 };
633 
641  public:
648  void AddEvent(LinearExpr time, int64_t level_change);
649 
656  void AddOptionalEvent(LinearExpr time, int64_t level_change,
657  BoolVar is_active);
658 
659  private:
660  friend class CpModelBuilder;
661 
662  ReservoirConstraint(ConstraintProto* proto, CpModelBuilder* builder);
663 
664  CpModelBuilder* builder_;
665 };
666 
674  public:
676  void AddTransition(int tail, int head, int64_t transition_label);
677 
678  private:
679  friend class CpModelBuilder;
680 
682 };
683 
691  public:
693  void AddRectangle(IntervalVar x_coordinate, IntervalVar y_coordinate);
694 
695  private:
696  friend class CpModelBuilder;
697 
699 };
700 
711  public:
713  void AddDemand(IntervalVar interval, LinearExpr demand);
714 
715  private:
716  friend class CpModelBuilder;
717 
718  CumulativeConstraint(ConstraintProto* proto, CpModelBuilder* builder);
719 
720  CpModelBuilder* builder_;
721 };
722 
731  public:
733  void SetName(const std::string& name);
734 
736  IntVar NewIntVar(const Domain& domain);
737 
740 
744  IntVar NewConstant(int64_t value);
745 
750 
755 
757  IntervalVar NewIntervalVar(const LinearExpr& start, const LinearExpr& size,
758  const LinearExpr& end);
759 
761  IntervalVar NewFixedSizeIntervalVar(const LinearExpr& start, int64_t size);
762 
766  const LinearExpr& size,
767  const LinearExpr& end, BoolVar presence);
768 
771  int64_t size, BoolVar presence);
772 
782  void FixVariable(IntVar var, int64_t value);
783  void FixVariable(BoolVar var, bool value);
784 
786  Constraint AddBoolOr(absl::Span<const BoolVar> literals);
787 
789  Constraint AddAtLeastOne(absl::Span<const BoolVar> literals);
790 
792  Constraint AddAtMostOne(absl::Span<const BoolVar> literals);
793 
795  Constraint AddExactlyOne(absl::Span<const BoolVar> literals);
796 
798  Constraint AddBoolAnd(absl::Span<const BoolVar> literals);
799 
801  Constraint AddBoolXor(absl::Span<const BoolVar> literals);
802 
805  return AddBoolOr({a.Not(), b});
806  }
807 
809  Constraint AddImplication(absl::Span<const BoolVar> lhs,
810  absl::Span<const BoolVar> rhs) {
811  return AddBoolAnd(rhs).OnlyEnforceIf(lhs);
812  }
813 
815  Constraint AddEquality(const LinearExpr& left, const LinearExpr& right);
816 
818  Constraint AddGreaterOrEqual(const LinearExpr& left, const LinearExpr& right);
819 
821  Constraint AddGreaterThan(const LinearExpr& left, const LinearExpr& right);
822 
824  Constraint AddLessOrEqual(const LinearExpr& left, const LinearExpr& right);
825 
827  Constraint AddLessThan(const LinearExpr& left, const LinearExpr& right);
828 
830  Constraint AddLinearConstraint(const LinearExpr& expr, const Domain& domain);
831 
833  Constraint AddNotEqual(const LinearExpr& left, const LinearExpr& right);
834 
836  Constraint AddAllDifferent(absl::Span<const IntVar> vars);
837 
839  Constraint AddAllDifferent(absl::Span<const LinearExpr> exprs);
840 
842  Constraint AddAllDifferent(std::initializer_list<LinearExpr> exprs);
843 
846  absl::Span<const IntVar> variables,
847  IntVar target);
848 
850  Constraint AddElement(IntVar index, absl::Span<const int64_t> values,
851  IntVar target);
852 
870 
885 
897  TableConstraint AddAllowedAssignments(absl::Span<const IntVar> vars);
898 
909  TableConstraint AddForbiddenAssignments(absl::Span<const IntVar> vars);
910 
916  Constraint AddInverseConstraint(absl::Span<const IntVar> variables,
917  absl::Span<const IntVar> inverse_variables);
918 
939  int64_t max_level);
940 
968  absl::Span<const IntVar> transition_variables, int starting_state,
969  absl::Span<const int> final_states);
970 
973  absl::Span<const IntVar> vars);
974 
977  absl::Span<const LinearExpr> exprs);
978 
981  std::initializer_list<LinearExpr> exprs);
982 
985  absl::Span<const IntVar> vars);
986 
989  absl::Span<const LinearExpr> exprs);
990 
993  std::initializer_list<LinearExpr> exprs);
994 
997  const LinearExpr& numerator,
998  const LinearExpr& denominator);
999 
1001  Constraint AddAbsEquality(const LinearExpr& target, const LinearExpr& expr);
1002 
1005  const LinearExpr& mod);
1006 
1009  absl::Span<const LinearExpr> exprs);
1010 
1013  absl::Span<const IntVar> vars);
1014 
1017  std::initializer_list<LinearExpr> exprs);
1018 
1021  const LinearExpr& left,
1022  const LinearExpr& right);
1023 
1028  Constraint AddNoOverlap(absl::Span<const IntervalVar> vars);
1029 
1034 
1042 
1044  void Minimize(const LinearExpr& expr);
1045 
1048  void Minimize(const DoubleLinearExpr& expr);
1049 
1051  void Maximize(const LinearExpr& expr);
1052 
1055  void Maximize(const DoubleLinearExpr& expr);
1056 
1059 
1061  bool HasObjective() const;
1062 
1065  absl::Span<const IntVar> variables,
1066  DecisionStrategyProto::VariableSelectionStrategy var_strategy,
1067  DecisionStrategyProto::DomainReductionStrategy domain_strategy);
1068 
1071  absl::Span<const BoolVar> variables,
1072  DecisionStrategyProto::VariableSelectionStrategy var_strategy,
1073  DecisionStrategyProto::DomainReductionStrategy domain_strategy);
1074 
1076  void AddHint(IntVar var, int64_t value);
1077 
1079  void AddHint(BoolVar var, bool value);
1080 
1082  void ClearHints();
1083 
1086 
1088  void AddAssumptions(absl::Span<const BoolVar> literals);
1089 
1092 
1093  const CpModelProto& Build() const { return cp_model_; }
1094  const CpModelProto& Proto() const { return cp_model_; }
1095  CpModelProto* MutableProto() { return &cp_model_; }
1096 
1098  bool ExportToFile(const std::string& filename) const;
1099 
1101  void CopyFrom(const CpModelProto& model_proto);
1102 
1105 
1108 
1111 
1112  private:
1113  friend class CumulativeConstraint;
1114  friend class ReservoirConstraint;
1115  friend class IntervalVar;
1116  friend class IntVar;
1117 
1118  // Fills the 'expr_proto' with the linear expression represented by 'expr'.
1119  LinearExpressionProto LinearExprToProto(const LinearExpr& expr,
1120  bool negate = false);
1121 
1122  // Returns a (cached) integer variable index with a constant value.
1123  int IndexFromConstant(int64_t value);
1124 
1125  // Returns a valid integer index from a BoolVar index.
1126  // If the input index is a positive, it returns this index.
1127  // If the input index is negative, it creates a cached IntVar equal to
1128  // 1 - BoolVar(PositiveRef(index)), and returns the index of this new
1129  // variable.
1130  int GetOrCreateIntegerIndex(int index);
1131 
1132  void FillLinearTerms(const LinearExpr& left, const LinearExpr& right,
1133  LinearConstraintProto* proto);
1134 
1135  CpModelProto cp_model_;
1136  absl::flat_hash_map<int64_t, int> constant_to_index_map_;
1137  absl::flat_hash_map<int, int> bool_to_integer_index_map_;
1138 };
1139 
1141 int64_t SolutionIntegerValue(const CpSolverResponse& r, const LinearExpr& expr);
1142 
1144 bool SolutionBooleanValue(const CpSolverResponse& r, BoolVar x);
1145 
1146 // Returns a more readable and compact DebugString() than
1147 // proto.variables(index).DebugString(). This is used by IntVar::DebugString()
1148 // but also allow to get the same string from a const proto.
1149 std::string VarDebugString(const CpModelProto& proto, int index);
1150 
1151 // ============================================================================
1152 // Minimal support for "natural" API to create LinearExpr.
1153 //
1154 // Note(user): This might be optimized further by optimizing LinearExpr for
1155 // holding one term, or introducing an LinearTerm class, but these should mainly
1156 // be used to construct small expressions. Revisit if we run into performance
1157 // issues. Note that if perf become a bottleneck for a client, then probably
1158 // directly writing the proto will be even faster.
1159 // ============================================================================
1160 
1161 inline LinearExpr operator-(LinearExpr expr) { return expr *= -1; }
1162 
1163 inline LinearExpr operator+(const LinearExpr& lhs, const LinearExpr& rhs) {
1164  LinearExpr temp(lhs);
1165  temp += rhs;
1166  return temp;
1167 }
1168 inline LinearExpr operator+(LinearExpr&& lhs, const LinearExpr& rhs) {
1169  lhs += rhs;
1170  return std::move(lhs);
1171 }
1172 inline LinearExpr operator+(const LinearExpr& lhs, LinearExpr&& rhs) {
1173  rhs += lhs;
1174  return std::move(rhs);
1175 }
1177  if (lhs.variables().size() < rhs.variables().size()) {
1178  rhs += std::move(lhs);
1179  return std::move(rhs);
1180  } else {
1181  lhs += std::move(rhs);
1182  return std::move(lhs);
1183  }
1184 }
1185 
1186 inline LinearExpr operator-(const LinearExpr& lhs, const LinearExpr& rhs) {
1187  LinearExpr temp(lhs);
1188  temp -= rhs;
1189  return temp;
1190 }
1191 inline LinearExpr operator-(LinearExpr&& lhs, const LinearExpr& rhs) {
1192  lhs -= rhs;
1193  return std::move(lhs);
1194 }
1195 inline LinearExpr operator-(const LinearExpr& lhs, LinearExpr&& rhs) {
1196  rhs *= -1;
1197  rhs += lhs;
1198  return std::move(rhs);
1199 }
1201  lhs -= std::move(rhs);
1202  return std::move(lhs);
1203 }
1204 
1205 inline LinearExpr operator*(LinearExpr expr, int64_t factor) {
1206  expr *= factor;
1207  return expr;
1208 }
1209 inline LinearExpr operator*(int64_t factor, LinearExpr expr) {
1210  expr *= factor;
1211  return expr;
1212 }
1213 
1214 // For DoubleLinearExpr.
1215 
1217  expr *= -1;
1218  return expr;
1219 }
1220 
1222  const DoubleLinearExpr& rhs) {
1223  DoubleLinearExpr temp(lhs);
1224  temp += rhs;
1225  return temp;
1226 }
1228  const DoubleLinearExpr& rhs) {
1229  lhs += rhs;
1230  return std::move(lhs);
1231 }
1233  DoubleLinearExpr&& rhs) {
1234  rhs += lhs;
1235  return std::move(rhs);
1236 }
1238  DoubleLinearExpr&& rhs) {
1239  if (lhs.variables().size() < rhs.variables().size()) {
1240  rhs += std::move(lhs);
1241  return std::move(rhs);
1242  } else {
1243  lhs += std::move(rhs);
1244  return std::move(lhs);
1245  }
1246 }
1247 
1248 inline DoubleLinearExpr operator+(DoubleLinearExpr expr, double rhs) {
1249  expr += rhs;
1250  return expr;
1251 }
1252 inline DoubleLinearExpr operator+(double lhs, DoubleLinearExpr expr) {
1253  expr += lhs;
1254  return expr;
1255 }
1256 
1258  const DoubleLinearExpr& rhs) {
1259  DoubleLinearExpr temp(lhs);
1260  temp -= rhs;
1261  return temp;
1262 }
1264  const DoubleLinearExpr& rhs) {
1265  lhs -= rhs;
1266  return std::move(lhs);
1267 }
1269  DoubleLinearExpr&& rhs) {
1270  rhs *= -1;
1271  rhs += lhs;
1272  return std::move(rhs);
1273 }
1275  DoubleLinearExpr&& rhs) {
1276  lhs -= std::move(rhs);
1277  return std::move(lhs);
1278 }
1279 
1280 inline DoubleLinearExpr operator-(DoubleLinearExpr epxr, double rhs) {
1281  epxr -= rhs;
1282  return epxr;
1283 }
1284 inline DoubleLinearExpr operator-(double lhs, DoubleLinearExpr expr) {
1285  expr *= -1;
1286  expr += lhs;
1287  return expr;
1288 }
1289 
1290 inline DoubleLinearExpr operator*(DoubleLinearExpr expr, double factor) {
1291  expr *= factor;
1292  return expr;
1293 }
1294 
1295 inline DoubleLinearExpr operator*(double factor, DoubleLinearExpr expr) {
1296  expr *= factor;
1297  return expr;
1298 }
1299 
1300 } // namespace sat
1301 } // namespace operations_research
1302 
1303 #endif // OR_TOOLS_SAT_CP_MODEL_H_
We call domain any subset of Int64 = [kint64min, kint64max].
Specialized automaton constraint.
Definition: cp_model.h:673
void AddTransition(int tail, int head, int64_t transition_label)
Adds a transitions to the automaton.
A Boolean variable.
Definition: cp_model.h:74
BoolVar()=default
A default constructed BoolVar can be used to mean not defined yet.
std::string Name() const
Returns the name of the variable.
BoolVar WithName(const std::string &name)
Sets the name of the variable.
std::string DebugString() const
friend bool SolutionBooleanValue(const CpSolverResponse &r, BoolVar x)
Evaluates the value of a Boolean literal in a solver response.
bool operator!=(const BoolVar &other) const
Definition: cp_model.h:96
bool operator==(const BoolVar &other) const
Definition: cp_model.h:92
int index() const
Returns the index of the variable in the model.
Definition: cp_model.h:108
BoolVar Not() const
Returns the logical negation of the current Boolean variable.
Definition: cp_model.h:90
Specialized circuit constraint.
Definition: cp_model.h:577
void AddArc(int tail, int head, BoolVar literal)
Add an arc to the circuit.
Constraint OnlyEnforceIf(absl::Span< const BoolVar > literals)
The constraint will be enforced iff all literals listed here are true.
Constraint WithName(const std::string &name)
Sets the name of the constraint.
const std::string & Name() const
Returns the name of the constraint (or the empty string if not set).
const ConstraintProto & Proto() const
Returns the underlying protobuf object (useful for testing).
Definition: cp_model.h:559
ConstraintProto * MutableProto() const
Returns the mutable underlying protobuf object (useful for model edition).
Definition: cp_model.h:562
Constraint(ConstraintProto *proto)
Constraint OnlyEnforceIf(BoolVar literal)
See OnlyEnforceIf(absl::Span<const BoolVar> literals).
Wrapper class around the cp_model proto.
Definition: cp_model.h:730
Constraint AddAtMostOne(absl::Span< const BoolVar > literals)
At most one literal is true. Sum literals <= 1.
void AddHint(IntVar var, int64_t value)
Adds hinting to a variable.
TableConstraint AddForbiddenAssignments(absl::Span< const IntVar > vars)
Adds an forbidden assignments constraint.
Constraint AddMultiplicationEquality(const LinearExpr &target, absl::Span< const IntVar > vars)
Adds target == prod(vars).
Constraint AddMaxEquality(const LinearExpr &target, absl::Span< const LinearExpr > exprs)
Adds target == max(exprs).
Constraint AddMinEquality(const LinearExpr &target, absl::Span< const IntVar > vars)
Adds target == min(vars).
Constraint AddLinearConstraint(const LinearExpr &expr, const Domain &domain)
Adds expr in domain.
void ClearAssumptions()
Remove all assumptions from the model.
Constraint AddAbsEquality(const LinearExpr &target, const LinearExpr &expr)
Adds target == abs(expr).
void AddAssumptions(absl::Span< const BoolVar > literals)
Adds multiple literals to the model as assumptions.
IntervalVar NewFixedSizeIntervalVar(const LinearExpr &start, int64_t size)
Creates an interval variable with a fixed size.
void Minimize(const DoubleLinearExpr &expr)
Adds a linear floating point minimization objective.
MultipleCircuitConstraint AddMultipleCircuitConstraint()
Adds a multiple circuit constraint, aka the "VRP" (Vehicle Routing Problem) constraint.
BoolVar TrueVar()
Creates an always true Boolean variable.
IntVar NewIntVar(const Domain &domain)
Creates an integer variable with the given domain.
void ClearObjective()
Removes the objective from the model.
Constraint AddImplication(absl::Span< const BoolVar > lhs, absl::Span< const BoolVar > rhs)
Adds implication: if all lhs vars are true then all rhs vars must be true.
Definition: cp_model.h:809
void AddDecisionStrategy(absl::Span< const BoolVar > variables, DecisionStrategyProto::VariableSelectionStrategy var_strategy, DecisionStrategyProto::DomainReductionStrategy domain_strategy)
Adds a decision strategy on a list of boolean variables.
void ClearHints()
Removes all hints.
Constraint AddMultiplicationEquality(const LinearExpr &target, std::initializer_list< LinearExpr > exprs)
Adds target == prod(vars).
void Maximize(const LinearExpr &expr)
Adds a linear maximization objective.
void FixVariable(BoolVar var, bool value)
Constraint AddMinEquality(const LinearExpr &target, absl::Span< const LinearExpr > exprs)
Adds target == min(exprs).
BoolVar NewBoolVar()
Creates a Boolean variable.
void AddHint(BoolVar var, bool value)
Adds hinting to a Boolean variable.
void Maximize(const DoubleLinearExpr &expr)
Adds a linear floating point maximization objective.
Constraint AddAtLeastOne(absl::Span< const BoolVar > literals)
Same as AddBoolOr(). Sum literals >= 1.
Constraint AddMaxEquality(const LinearExpr &target, absl::Span< const IntVar > vars)
Adds target == max(vars).
Constraint AddMultiplicationEquality(const LinearExpr &target, absl::Span< const LinearExpr > exprs)
Adds target == prod(exprs).
void AddDecisionStrategy(absl::Span< const IntVar > variables, DecisionStrategyProto::VariableSelectionStrategy var_strategy, DecisionStrategyProto::DomainReductionStrategy domain_strategy)
Adds a decision strategy on a list of integer variables.
IntervalVar NewOptionalIntervalVar(const LinearExpr &start, const LinearExpr &size, const LinearExpr &end, BoolVar presence)
Creates an optional interval variable from 3 affine expressions and a Boolean variable.
CircuitConstraint AddCircuitConstraint()
Adds a circuit constraint.
Constraint AddVariableElement(IntVar index, absl::Span< const IntVar > variables, IntVar target)
Adds the element constraint: variables[index] == target.
const CpModelProto & Proto() const
Definition: cp_model.h:1094
const CpModelProto & Build() const
Definition: cp_model.h:1093
Constraint AddMaxEquality(const LinearExpr &target, std::initializer_list< LinearExpr > exprs)
Adds target == max(exprs).
Constraint AddGreaterThan(const LinearExpr &left, const LinearExpr &right)
Adds left > right.
bool HasObjective() const
Checks whether the model contains an objective.
void CopyFrom(const CpModelProto &model_proto)
Replaces the current model with the one from the given proto.
Constraint AddLessThan(const LinearExpr &left, const LinearExpr &right)
Adds left < right.
Constraint AddBoolXor(absl::Span< const BoolVar > literals)
Adds the constraint that an odd number of literals is true.
void SetName(const std::string &name)
Sets the name of the model.
Constraint AddElement(IntVar index, absl::Span< const int64_t > values, IntVar target)
Adds the element constraint: values[index] == target.
void AddAssumption(BoolVar lit)
Adds a literal to the model as assumptions.
void Minimize(const LinearExpr &expr)
Adds a linear minimization objective.
BoolVar FalseVar()
Creates an always false Boolean variable.
Constraint AddImplication(BoolVar a, BoolVar b)
Adds a => b.
Definition: cp_model.h:804
Constraint AddBoolAnd(absl::Span< const BoolVar > literals)
Adds the constraint that all literals must be true.
IntervalVar GetIntervalVarFromProtoIndex(int index)
Returns the interval variable from its index in the proto.
CumulativeConstraint AddCumulative(LinearExpr capacity)
The cumulative constraint.
void FixVariable(IntVar var, int64_t value)
It is sometime convenient when building a model to create a bunch of variables that will later be fix...
Constraint AddLessOrEqual(const LinearExpr &left, const LinearExpr &right)
Adds left <= right.
ReservoirConstraint AddReservoirConstraint(int64_t min_level, int64_t max_level)
Adds a reservoir constraint with optional refill/emptying events.
Constraint AddEquality(const LinearExpr &left, const LinearExpr &right)
Adds left == right.
NoOverlap2DConstraint AddNoOverlap2D()
The no_overlap_2d constraint prevents a set of boxes from overlapping.
Constraint AddGreaterOrEqual(const LinearExpr &left, const LinearExpr &right)
Adds left >= right.
Constraint AddBoolOr(absl::Span< const BoolVar > literals)
Adds the constraint that at least one of the literals must be true.
IntVar GetIntVarFromProtoIndex(int index)
Returns the integer variable from its index in the proto.
Constraint AddMultiplicationEquality(const LinearExpr &target, const LinearExpr &left, const LinearExpr &right)
Adds target == left * right.
AutomatonConstraint AddAutomaton(absl::Span< const IntVar > transition_variables, int starting_state, absl::Span< const int > final_states)
An automaton constraint.
bool ExportToFile(const std::string &filename) const
Export the model to file.
IntervalVar NewOptionalFixedSizeIntervalVar(const LinearExpr &start, int64_t size, BoolVar presence)
Creates an optional interval variable with a fixed size.
Constraint AddAllDifferent(absl::Span< const LinearExpr > exprs)
This constraint forces all expressions to have different values.
Constraint AddDivisionEquality(const LinearExpr &target, const LinearExpr &numerator, const LinearExpr &denominator)
Adds target = num / denom (integer division rounded towards 0).
BoolVar GetBoolVarFromProtoIndex(int index)
Returns the Boolean variable from its index in the proto.
Constraint AddNotEqual(const LinearExpr &left, const LinearExpr &right)
Adds left != right.
Constraint AddModuloEquality(const LinearExpr &target, const LinearExpr &var, const LinearExpr &mod)
Adds target = var % mod.
Constraint AddAllDifferent(absl::Span< const IntVar > vars)
This constraint forces all variables to have different values.
TableConstraint AddAllowedAssignments(absl::Span< const IntVar > vars)
Adds an allowed assignments constraint.
IntVar NewConstant(int64_t value)
Creates a constant variable.
Constraint AddAllDifferent(std::initializer_list< LinearExpr > exprs)
This constraint forces all expressions to have different values.
IntervalVar NewIntervalVar(const LinearExpr &start, const LinearExpr &size, const LinearExpr &end)
Creates an interval variable from 3 affine expressions.
Constraint AddInverseConstraint(absl::Span< const IntVar > variables, absl::Span< const IntVar > inverse_variables)
An inverse constraint.
Constraint AddExactlyOne(absl::Span< const BoolVar > literals)
Exactly one literal is true. Sum literals == 1.
Constraint AddNoOverlap(absl::Span< const IntervalVar > vars)
Adds a no-overlap constraint that ensures that all present intervals do not overlap in time.
Constraint AddMinEquality(const LinearExpr &target, std::initializer_list< LinearExpr > exprs)
Adds target == min(exprs).
Specialized cumulative constraint.
Definition: cp_model.h:710
void AddDemand(IntervalVar interval, LinearExpr demand)
Adds a pair (interval, demand) to the constraint.
A dedicated container for linear expressions with double coefficients.
Definition: cp_model.h:345
DoubleLinearExpr & operator-=(double value)
Adds a constant value to the linear expression.
static DoubleLinearExpr WeightedSum(absl::Span< const IntVar > vars, absl::Span< const double > coeffs)
Constructs the scalar product of variables and coefficients.
DoubleLinearExpr & operator+=(BoolVar var)
static DoubleLinearExpr Sum(absl::Span< const IntVar > vars)
Constructs the sum of a list of variables.
double constant() const
Returns the constant term.
Definition: cp_model.h:412
std::string DebugString(const CpModelProto *proto=nullptr) const
Debug string. See the documentation for LinearExpr::DebugString().
DoubleLinearExpr & operator*=(double coeff)
Multiply the linear expression by a constant.
DoubleLinearExpr & operator+=(IntVar var)
Adds a single integer variable to the linear expression.
static DoubleLinearExpr Sum(absl::Span< const BoolVar > vars)
Constructs the sum of a list of Boolean variables.
DoubleLinearExpr & operator+=(const DoubleLinearExpr &expr)
Adds another linear expression to the linear expression.
DoubleLinearExpr & AddTerm(IntVar var, double coeff)
Adds a term (var * coeff) to the linear expression.
DoubleLinearExpr & AddTerm(BoolVar var, double coeff)
DoubleLinearExpr(IntVar var)
Constructs a linear expression from an integer variable.
static DoubleLinearExpr WeightedSum(absl::Span< const BoolVar > vars, absl::Span< const double > coeffs)
Constructs the scalar product of Boolean variables and coefficients.
DoubleLinearExpr & operator+=(double value)
Adds a constant value to the linear expression.
DoubleLinearExpr & operator-=(const DoubleLinearExpr &expr)
Adds another linear expression to the linear expression.
DoubleLinearExpr(BoolVar var)
Constructs a linear expression from a Boolean variable.
DoubleLinearExpr & AddExpression(const LinearExpr &exprs, double coeff=1.0)
Adds a linear expression to the double linear expression.
const std::vector< double > & coefficients() const
Returns the vector of coefficients.
Definition: cp_model.h:406
DoubleLinearExpr(double constant)
Constructs a constant linear expression.
const std::vector< int > & variables() const
Returns the vector of variable indices.
Definition: cp_model.h:403
DoubleLinearExpr & operator-=(IntVar var)
Adds a single integer variable to the linear expression.
An integer variable.
Definition: cp_model.h:142
BoolVar ToBoolVar() const
Cast IntVar -> BoolVar.
std::string Name() const
Returns the name of the variable (or the empty string if not set).
::operations_research::Domain Domain() const
bool operator==(const IntVar &other) const
Definition: cp_model.h:171
std::string DebugString() const
bool operator!=(const IntVar &other) const
Definition: cp_model.h:175
IntVar WithName(const std::string &name)
Sets the name of the variable.
friend int64_t SolutionIntegerValue(const CpSolverResponse &r, const LinearExpr &expr)
Evaluates the value of an linear expression in a solver response.
int index() const
Returns the index of the variable in the model. This will be non-negative.
Definition: cp_model.h:187
IntVar(const BoolVar &var)
Cast BoolVar -> IntVar.
IntVar()=default
A default constructed IntVar can be used to mean not defined yet.
Represents a Interval variable.
Definition: cp_model.h:445
LinearExpr SizeExpr() const
Returns the size linear expression.
LinearExpr StartExpr() const
Returns the start linear expression.
BoolVar PresenceBoolVar() const
Returns a BoolVar indicating the presence of this interval.
std::string Name() const
Returns the name of the interval (or the empty string if not set).
std::string DebugString() const
Returns a debug string.
bool operator!=(const IntervalVar &other) const
Difference test with another interval variable.
Definition: cp_model.h:484
bool operator==(const IntervalVar &other) const
Equality test with another interval variable.
Definition: cp_model.h:479
IntervalVar WithName(const std::string &name)
Sets the name of the variable.
LinearExpr EndExpr() const
Returns the end linear expression.
IntervalVar()
A default constructed IntervalVar can be used to mean not defined yet.
int index() const
Returns the index of the interval constraint in the model.
Definition: cp_model.h:492
friend std::ostream & operator<<(std::ostream &os, const IntervalVar &var)
A dedicated container for linear expressions.
Definition: cp_model.h:241
LinearExpr & operator+=(const LinearExpr &other)
const bool IsConstant() const
Returns true if the expression has no variables.
Definition: cp_model.h:295
static LinearExpr WeightedSum(absl::Span< const BoolVar > vars, absl::Span< const int64_t > coeffs)
Constructs the scalar product of Boolean variables and coefficients.
static LinearExpr Term(IntVar var, int64_t coefficient)
Constructs var * coefficient.
std::string DebugString(const CpModelProto *proto=nullptr) const
Debug string.
static LinearExpr WeightedSum(absl::Span< const IntVar > vars, absl::Span< const int64_t > coeffs)
Constructs the scalar product of variables and coefficients.
LinearExpr(IntVar var)
Constructs a linear expression from an integer variable.
static LinearExpr FromProto(const LinearExpressionProto &proto)
Constructs a linear expr from its proto representation.
static LinearExpr Sum(absl::Span< const IntVar > vars)
Constructs the sum of a list of variables.
LinearExpr(BoolVar var)
Constructs a linear expression from a Boolean variable.
static LinearExpr Term(BoolVar var, int64_t coefficient)
Constructs bool * coefficient.
int64_t constant() const
Returns the constant term.
Definition: cp_model.h:298
LinearExpr()=default
Creates an empty linear expression with value zero.
static LinearExpr Sum(absl::Span< const BoolVar > vars)
Constructs the sum of a list of Boolean variables.
LinearExpr & operator*=(int64_t factor)
LinearExpr & operator-=(const LinearExpr &other)
const std::vector< int64_t > & coefficients() const
Returns the vector of coefficients.
Definition: cp_model.h:292
const std::vector< int > & variables() const
Returns the vector of variable indices.
Definition: cp_model.h:289
LinearExpr(int64_t constant)
Constructs a constant linear expression.
void AddArc(int tail, int head, BoolVar literal)
Add an arc to the circuit.
Specialized no_overlap2D constraint.
Definition: cp_model.h:690
void AddRectangle(IntervalVar x_coordinate, IntervalVar y_coordinate)
Adds a rectangle (parallel to the axis) to the constraint.
Specialized reservoir constraint.
Definition: cp_model.h:640
void AddOptionalEvent(LinearExpr time, int64_t level_change, BoolVar is_active)
Adds an optional event.
void AddEvent(LinearExpr time, int64_t level_change)
Adds a mandatory event.
Specialized assignment constraint.
Definition: cp_model.h:623
void AddTuple(absl::Span< const int64_t > tuple)
Adds a tuple of possible values to the constraint.
std::string VarDebugString(const CpModelProto &proto, int index)
LinearExpr operator+(const LinearExpr &lhs, const LinearExpr &rhs)
Definition: cp_model.h:1163
LinearExpr operator-(LinearExpr expr)
Definition: cp_model.h:1161
BoolVar Not(BoolVar x)
A convenient wrapper so we can write Not(x) instead of x.Not() which is sometimes clearer.
std::ostream & operator<<(std::ostream &os, const BoolVar &var)
H AbslHashValue(H h, const IntVar &i)
Definition: cp_model.h:510
int64_t SolutionIntegerValue(const CpSolverResponse &r, const LinearExpr &expr)
Evaluates the value of an linear expression in a solver response.
LinearExpr operator*(LinearExpr expr, int64_t factor)
Definition: cp_model.h:1205
bool SolutionBooleanValue(const CpSolverResponse &r, BoolVar x)
Evaluates the value of a Boolean literal in a solver response.