cp_model.h
Go to the documentation of this file.
1 // Copyright 2010-2018 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 
14 // This file implements a wrapper around the CP-SAT model proto.
15 //
16 // Here is a minimal example that shows how to create a model, solve it, and
17 // print out the solution.
18 //
19 // CpModelBuilder cp_model;
20 // Domain all_animals(0, 20);
21 // IntVar rabbits = cp_model.NewIntVar(all_animals).WithName("rabbits");
22 // IntVar pheasants = cp_model.NewIntVar(all_animals).WithName("pheasants");
23 //
24 // cp_model.AddEquality(LinearExpr::Sum({rabbits, pheasants}), 20);
25 // cp_model.AddEquality(LinearExpr::ScalProd({rabbits, pheasants}, {4, 2}), 56);
26 //
27 // const CpSolverResponse response = Solve(cp_model);
28 // if (response.status() == CpSolverStatus::FEASIBLE) {
29 // LOG(INFO) << SolutionIntegerValue(response, rabbits)
30 // << " rabbits, and " << SolutionIntegerValue(response, pheasants)
31 // << " pheasants.";
32 // }
33 
34 #ifndef OR_TOOLS_SAT_CP_MODEL_H_
35 #define OR_TOOLS_SAT_CP_MODEL_H_
36 
37 #include <string>
38 
39 #include "absl/container/flat_hash_map.h"
40 #include "absl/types/span.h"
43 #include "ortools/sat/cp_model_utils.h"
44 #include "ortools/sat/model.h"
47 
49 namespace sat {
50 
51 class CpModelBuilder;
52 class LinearExpr;
53 
54 // A Boolean variable.
55 // This class wraps an IntegerVariableProto with domain [0, 1].
56 // It supports logical negation (Not).
57 //
58 // This can only be constructed via CpModelBuilder.NewBoolVar().
59 class BoolVar {
60  public:
61  BoolVar();
62 
63  // Sets the name of the variable.
64  BoolVar WithName(const std::string& name);
65 
66  const std::string& Name() const { return Proto().name(); }
67 
68  // Returns the logical negation of the current Boolean variable.
69  BoolVar Not() const { return BoolVar(NegatedRef(index_), cp_model_); }
70 
71  bool operator==(const BoolVar& other) const {
72  return other.cp_model_ == cp_model_ && other.index_ == index_;
73  }
74 
75  bool operator!=(const BoolVar& other) const {
76  return other.cp_model_ != cp_model_ || other.index_ != index_;
77  }
78 
79  std::string DebugString() const;
80 
81  // Useful for testing.
82  const IntegerVariableProto& Proto() const {
83  return cp_model_->variables(index_);
84  }
85 
86  // Useful for model edition.
88  return cp_model_->mutable_variables(index_);
89  }
90 
91  // Returns the index of the variable in the model. If the variable is the
92  // negation of another variable v, its index is -v.index() - 1.
93  int index() const { return index_; }
94 
95  private:
96  friend class CircuitConstraint;
97  friend class Constraint;
98  friend class CpModelBuilder;
99  friend class IntVar;
100  friend class IntervalVar;
101  friend class LinearExpr;
102  friend class ReservoirConstraint;
103  friend bool SolutionBooleanValue(const CpSolverResponse& r, BoolVar x);
104 
105  BoolVar(int index, CpModelProto* cp_model);
106 
107  CpModelProto* cp_model_ = nullptr;
108  int index_ = kint32min;
109 };
110 
111 std::ostream& operator<<(std::ostream& os, const BoolVar& var);
112 
113 // A convenient wrapper so we can write Not(x) instead of x.Not() which is
114 // sometimes clearer.
115 BoolVar Not(BoolVar x);
116 
117 // An integer variable.
118 // This class wraps an IntegerVariableProto.
119 // This can only be constructed via CpModelBuilder.NewIntVar().
120 //
121 // Note that a BoolVar can be used in any place that accept an
122 // IntVar via an implicit cast. It will simply take the value
123 // 0 (when false) or 1 (when true).
124 class IntVar {
125  public:
126  IntVar();
127 
128  // Implicit cast BoolVar -> IntVar.
129  IntVar(const BoolVar& var); // NOLINT(runtime/explicit)
130 
131  // Sets the name of the variable.
132  IntVar WithName(const std::string& name);
133 
134  const std::string& Name() const { return Proto().name(); }
135 
136  bool operator==(const IntVar& other) const {
137  return other.cp_model_ == cp_model_ && other.index_ == index_;
138  }
139 
140  bool operator!=(const IntVar& other) const {
141  return other.cp_model_ != cp_model_ || other.index_ != index_;
142  }
143 
144  std::string DebugString() const;
145 
146  // Useful for testing.
147  const IntegerVariableProto& Proto() const {
148  return cp_model_->variables(index_);
149  }
150 
151  // Useful for model edition.
153  return cp_model_->mutable_variables(index_);
154  }
155 
156  // Returns the index of the variable in the model.
157  int index() const { return index_; }
158 
159  private:
160  friend class CpModelBuilder;
161  friend class CumulativeConstraint;
162  friend class LinearExpr;
163  friend class IntervalVar;
164  friend class ReservoirConstraint;
165  friend int64 SolutionIntegerValue(const CpSolverResponse& r,
166  const LinearExpr& expr);
167  friend int64 SolutionIntegerMin(const CpSolverResponse& r, IntVar x);
168  friend int64 SolutionIntegerMax(const CpSolverResponse& r, IntVar x);
169 
170  IntVar(int index, CpModelProto* cp_model);
171 
172  CpModelProto* cp_model_ = nullptr;
173  int index_ = kint32min;
174 };
175 
176 std::ostream& operator<<(std::ostream& os, const IntVar& var);
177 
178 // A dedicated container for linear expressions.
179 //
180 // This class helps building and manipulating linear expressions.
181 // With the use of implicit constructors, it can accept integer values, Boolean
182 // and Integer variables. Note that Not(x) will be silently transformed into
183 // 1 - x when added to the linear expression.
184 //
185 // Furthermore, static methods allows sums and scalar products, with or without
186 // an additional constant.
187 //
188 // Usage:
189 // CpModelBuilder cp_model;
190 // IntVar x = model.NewIntVar(0, 10, "x");
191 // IntVar y = model.NewIntVar(0, 10, "y");
192 // BoolVar b = model.NewBoolVar().WithName("b");
193 // BoolVar c = model.NewBoolVar().WithName("c");
194 // LinearExpr e1(x); // e1 = x.
195 // LinearExpr e2 = LinearExpr::Sum({x, y}).AddConstant(5); // e2 = x + y + 5;
196 // LinearExpr e3 = LinearExpr::ScalProd({x, y}, {2, -1}); // e3 = 2 * x - y.
197 // LinearExpr e4(b); // e4 = b.
198 // LinearExpr e5(b.Not()); // e5 = 1 - b.
199 // // If passing a std::vector<BoolVar>, a specialized method must be called.
200 // std::vector<BoolVar> bools = {b, Not(c)};
201 // LinearExpr e6 = LinearExpr::BooleanSum(bools); // e6 = b + 1 - c;
202 // // e7 = -3 * b + 1 - c;
203 // LinearExpr e7 = LinearExpr::BooleanScalProd(bools, {-3, 1});
204 //
205 // This can be used implicitly in some of the CpModelBuilder methods.
206 // cp_model.AddGreaterThan(x, 5); // x > 5
207 // cp_model.AddEquality(x, LinearExpr(y).AddConstant(5)); // x == y + 5
208 class LinearExpr {
209  public:
210  LinearExpr();
211 
212  // Constructs a linear expression from a Boolean variable.
213  // It deals with logical negation correctly.
214  LinearExpr(BoolVar var); // NOLINT(runtime/explicit)
215 
216  // Constructs a linear expression from an integer variable.
217  LinearExpr(IntVar var); // NOLINT(runtime/explicit)
218 
219  // Constructs a constant linear expression.
220  LinearExpr(int64 constant); // NOLINT(runtime/explicit)
221 
222  // Adds a constant value to the linear expression.
223  LinearExpr& AddConstant(int64 value);
224 
225  // Adds a single integer variable to the linear expression.
226  void AddVar(IntVar var);
227 
228  // Adds a term (var * coeff) to the linear expression.
229  void AddTerm(IntVar var, int64 coeff);
230 
231  // Constructs the sum of a list of variables.
232  static LinearExpr Sum(absl::Span<const IntVar> vars);
233 
234  // Constructs the scalar product of variables and coefficients.
235  static LinearExpr ScalProd(absl::Span<const IntVar> vars,
236  absl::Span<const int64> coeffs);
237 
238  // Constructs the sum of a list of Booleans.
239  static LinearExpr BooleanSum(absl::Span<const BoolVar> vars);
240 
241  // Constructs the scalar product of Booleans and coefficients.
242  static LinearExpr BooleanScalProd(absl::Span<const BoolVar> vars,
243  absl::Span<const int64> coeffs);
244 
245  // Useful for testing.
246  const std::vector<IntVar>& variables() const { return variables_; }
247  const std::vector<int64>& coefficients() const { return coefficients_; }
248  int64 constant() const { return constant_; }
249 
250  // TODO(user): LinearExpr.DebugString() and operator<<.
251 
252  private:
253  std::vector<IntVar> variables_;
254  std::vector<int64> coefficients_;
255  int64 constant_ = 0;
256 };
257 
258 // Represents a Interval variable.
259 //
260 // An interval variable is both a constraint and a variable. It is defined by
261 // three integer variables: start, size, and end.
262 //
263 // It is a constraint because, internally, it enforces that start + size == end.
264 //
265 // It is also a variable as it can appear in specific scheduling constraints:
266 // NoOverlap, NoOverlap2D, Cumulative.
267 //
268 // Optionally, a presence literal can be added to this constraint. This presence
269 // literal is understood by the same constraints. These constraints ignore
270 // interval variables with precence literals assigned to false. Conversely,
271 // these constraints will also set these presence literals to false if they
272 // cannot fit these intervals into the schedule.
273 //
274 // It can only be constructed via CpModelBuilder.NewIntervalVar().
275 class IntervalVar {
276  public:
277  // Default ctor.
278  IntervalVar();
279 
280  // Sets the name of the variable.
281  IntervalVar WithName(const std::string& name);
282 
283  std::string Name() const;
284 
285  // Returns the start variable.
286  IntVar StartVar() const;
287 
288  // Returns the size variable.
289  IntVar SizeVar() const;
290 
291  // Returns the end variable.
292  IntVar EndVar() const;
293 
294  // Returns a BoolVar indicating the presence of this interval.
295  // It returns CpModelBuilder.TrueVar() if the interval is not optional.
296  BoolVar PresenceBoolVar() const;
297 
298  bool operator==(const IntervalVar& other) const {
299  return other.cp_model_ == cp_model_ && other.index_ == index_;
300  }
301 
302  bool operator!=(const IntervalVar& other) const {
303  return other.cp_model_ != cp_model_ || other.index_ != index_;
304  }
305 
306  std::string DebugString() const;
307 
308  // Useful for testing.
310  return cp_model_->constraints(index_).interval();
311  }
312 
313  // Useful for model edition.
315  return cp_model_->mutable_constraints(index_)->mutable_interval();
316  }
317 
318  // Returns the index of the interval constraint in the model.
319  int index() const { return index_; }
320 
321  private:
322  friend class CpModelBuilder;
323  friend class CumulativeConstraint;
324  friend class NoOverlap2DConstraint;
325  friend std::ostream& operator<<(std::ostream& os, const IntervalVar& var);
326 
327  IntervalVar(int index, CpModelProto* cp_model);
328 
329  CpModelProto* cp_model_ = nullptr;
330  int index_ = kint32min;
331 };
332 
333 std::ostream& operator<<(std::ostream& os, const IntervalVar& var);
334 
335 // A constraint.
336 //
337 // This class enable modifying the constraint that was added to the model.
338 //
339 // It can anly be built by the different CpModelBuilder::AddXXX methods.
340 class Constraint {
341  public:
342  // The constraint will be enforced iff all literals listed here are true. If
343  // this is empty, then the constraint will always be enforced. An enforced
344  // constraint must be satisfied, and an un-enforced one will simply be
345  // ignored.
346  //
347  // This is also called half-reification. To have an equivalence between a
348  // literal and a constraint (full reification), one must add both a constraint
349  // (controlled by a literal l) and its negation (controlled by the negation of
350  // l).
351  //
352  // Important: as of September 2018, only a few constraint support enforcement:
353  // - bool_or, bool_and, linear: fully supported.
354  // - interval: only support a single enforcement literal.
355  // - other: no support (but can be added on a per-demand basis).
356  Constraint OnlyEnforceIf(absl::Span<const BoolVar> literals);
357 
358  // See OnlyEnforceIf(absl::Span<const BoolVar> literals).
360 
361  // Sets the name of the constraint.
362  Constraint WithName(const std::string& name);
363 
364  const std::string& Name() const;
365 
366  // Useful for testing.
367  const ConstraintProto& Proto() const { return *proto_; }
368 
369  // Useful for model edition.
370  ConstraintProto* MutableProto() const { return proto_; }
371 
372  protected:
373  friend class CpModelBuilder;
374 
375  explicit Constraint(ConstraintProto* proto);
376 
378 };
379 
380 // Specialized circuit constraint.
381 //
382 // This constraint allows adding arcs to the circuit constraint incrementally.
384  public:
385  void AddArc(int tail, int head, BoolVar literal);
386 
387  private:
388  friend class CpModelBuilder;
389 
391 };
392 
393 // Specialized assignment constraint.
394 //
395 // This constraint allows adding tuples to the allowed/forbidden assignment
396 // constraint incrementally.
397 class TableConstraint : public Constraint {
398  public:
399  void AddTuple(absl::Span<const int64> tuple);
400 
401  private:
402  friend class CpModelBuilder;
403 
405 };
406 
407 // Specialized reservoir constraint.
408 //
409 // This constraint allows adding emptying/refilling events to the reservoir
410 // constraint incrementally.
412  public:
413  void AddEvent(IntVar time, int64 demand);
414  void AddOptionalEvent(IntVar time, int64 demand, BoolVar is_active);
415 
416  private:
417  friend class CpModelBuilder;
418 
420 
421  CpModelBuilder* builder_;
422 };
423 
424 // Specialized automaton constraint.
425 //
426 // This constraint allows adding transitions to the automaton constraint
427 // incrementally.
429  public:
430  void AddTransition(int tail, int head, int64 transition_label);
431 
432  private:
433  friend class CpModelBuilder;
434 
436 };
437 
438 // Specialized no_overlap2D constraint.
439 //
440 // This constraint allows adding rectangles to the no_overlap2D
441 // constraint incrementally.
443  public:
444  void AddRectangle(IntervalVar x_coordinate, IntervalVar y_coordinate);
445 
446  private:
447  friend class CpModelBuilder;
448 
450 };
451 
452 // Specialized cumulative constraint.
453 //
454 // This constraint allows adding fixed or variables demands to the cumulative
455 // constraint incrementally.
457  public:
458  void AddDemand(IntervalVar interval, IntVar demand);
459 
460  private:
461  friend class CpModelBuilder;
462 
464 
465  CpModelBuilder* builder_;
466 };
467 
468 // Wrapper class around the cp_model proto.
469 //
470 // This class provides two types of methods:
471 // - NewXXX to create integer, boolean, or interval variables.
472 // - AddXXX to create new constraints and add them to the model.
474  public:
475  // Creates an integer variable with the given domain.
476  IntVar NewIntVar(const Domain& domain);
477 
478  // Creates a Boolean variable.
480 
481  // Creates a constant variable.
482  IntVar NewConstant(int64 value);
483 
484  // Creates an always true Boolean variable.
485  BoolVar TrueVar();
486 
487  // Creates an always false Boolean variable.
488  BoolVar FalseVar();
489 
490  // Creates an interval variable.
491  IntervalVar NewIntervalVar(IntVar start, IntVar size, IntVar end);
492 
493  // Creates an optional interval variable.
495  BoolVar presence);
496 
497  // Adds the constraint that at least one of the literals must be true.
498  Constraint AddBoolOr(absl::Span<const BoolVar> literals);
499 
500  // Adds the constraint that all literals must be true.
501  Constraint AddBoolAnd(absl::Span<const BoolVar> literals);
502 
504  Constraint AddBoolXor(absl::Span<const BoolVar> literals);
505 
506  // Adds a => b.
508  return AddBoolOr({a.Not(), b});
509  }
510 
511  // Adds left == right.
512  Constraint AddEquality(const LinearExpr& left, const LinearExpr& right);
513 
514  // Adds left >= right.
515  Constraint AddGreaterOrEqual(const LinearExpr& left, const LinearExpr& right);
516 
517  // Adds left > right.
518  Constraint AddGreaterThan(const LinearExpr& left, const LinearExpr& right);
519 
520  // Adds left <= right.
521  Constraint AddLessOrEqual(const LinearExpr& left, const LinearExpr& right);
522 
523  // Adds left < right.
524  Constraint AddLessThan(const LinearExpr& left, const LinearExpr& right);
525 
526  // Adds expr in domain.
527  Constraint AddLinearConstraint(const LinearExpr& expr, const Domain& domain);
528 
529  // Adds left != right.
530  Constraint AddNotEqual(const LinearExpr& left, const LinearExpr& right);
531 
532  // this constraint forces all variables to have different values.
533  Constraint AddAllDifferent(absl::Span<const IntVar> vars);
534 
535  // Adds the element constraint: variables[index] == target
537  absl::Span<const IntVar> variables,
538  IntVar target);
539 
540  // Adds the element constraint: values[index] == target
541  Constraint AddElement(IntVar index, absl::Span<const int64> values,
542  IntVar target);
543 
544  // Adds a circuit constraint.
545  //
546  // The circuit constraint is defined on a graph where the arc presence are
547  // controlled by literals. That is the arc is part of the circuit of its
548  // corresponding literal is assigned to true.
549  //
550  // For now, we ignore node indices with no incident arc. All the other nodes
551  // must have exactly one incoming and one outgoing selected arc (i.e. literal
552  // at true). All the selected arcs that are not self-loops must form a single
553  // circuit.
554  //
555  // It returns a circuit constraint that allows adding arcs incrementally after
556  // construction.
558 
559  // Adds an allowed assignments constraint.
560  //
561  // An AllowedAssignments constraint is a constraint on an array of variables
562  // that forces, when all variables are fixed to a single value, that the
563  // corresponding list of values is equal to one of the tuple added to the
564  // constraint.
565  //
566  // It returns a table constraint that allows adding tuples incrementally after
567  // construction,
568  TableConstraint AddAllowedAssignments(absl::Span<const IntVar> vars);
569 
570  // Adds an forbidden assignments constraint.
571  //
572  // A ForbiddenAssignments constraint is a constraint on an array of variables
573  // where the list of impossible combinations is provided in the tuples added
574  // to the constraint.
575  //
576  // It returns a table constraint that allows adding tuples incrementally after
577  // construction,
578  TableConstraint AddForbiddenAssignments(absl::Span<const IntVar> vars);
579 
580  // An inverse constraint enforces that if 'variables[i]' is assigned a value
581  // 'j', then inverse_variables[j] is assigned a value 'i'. And vice versa.
582  Constraint AddInverseConstraint(absl::Span<const IntVar> variables,
583  absl::Span<const IntVar> inverse_variables);
584 
585  // Adds a reservoir constraint with optional refill/emptying events.
586  //
587  // Maintain a reservoir level within bounds. The water level starts at 0, and
588  // at any time >= 0, it must be within min_level, and max_level. Furthermore,
589  // this constraints expect all times variables to be >= 0. Given an event
590  // (time, demand, active), if active is true, and if time is assigned a value
591  // t, then the level of the reservoir changes by demand (which is constant) at
592  // time t.
593  //
594  // Note that level_min can be > 0, or level_max can be < 0. It just forces
595  // some demands to be executed at time 0 to make sure that we are within those
596  // bounds with the executed demands. Therefore, at any time t >= 0:
597  // sum(demands[i] * actives[i] if times[i] <= t) in [min_level, max_level]
598  //
599  // It returns a ReservoirConstraint that allows adding optional and non
600  // optional events incrementally after construction.
601  ReservoirConstraint AddReservoirConstraint(int64 min_level, int64 max_level);
602 
603  // An automaton constraint takes a list of variables (of size n), an initial
604  // state, a set of final states, and a set of transitions. A transition is a
605  // triplet ('tail', 'head', 'label'), where 'tail' and 'head' are states,
606  // and 'label' is the label of an arc from 'head' to 'tail',
607  // corresponding to the value of one variable in the list of variables.
608  //
609  // This automaton will be unrolled into a flow with n + 1 phases. Each phase
610  // contains the possible states of the automaton. The first state contains the
611  // initial state. The last phase contains the final states.
612  //
613  // Between two consecutive phases i and i + 1, the automaton creates a set of
614  // arcs. For each transition (tail, head, label), it will add an arc from
615  // the state 'tail' of phase i and the state 'head' of phase i + 1. This arc
616  // labeled by the value 'label' of the variables 'variables[i]'. That is,
617  // this arc can only be selected if 'variables[i]' is assigned the value
618  // 'label'. A feasible solution of this constraint is an assignment of
619  // variables such that, starting from the initial state in phase 0, there is a
620  // path labeled by the values of the variables that ends in one of the final
621  // states in the final phase.
622  //
623  // It returns an AutomatonConstraint that allows adding transition
624  // incrementally after construction.
626  absl::Span<const IntVar> transition_variables, int starting_state,
627  absl::Span<const int> final_states);
628 
629  // Adds target == min(vars).
630  Constraint AddMinEquality(IntVar target, absl::Span<const IntVar> vars);
631 
632  // Adds target == max(vars).
633  Constraint AddMaxEquality(IntVar target, absl::Span<const IntVar> vars);
634 
635  // Adds target = num / denom (integer division rounded towards 0).
636  Constraint AddDivisionEquality(IntVar target, IntVar numerator,
637  IntVar denominator);
638 
639  // Adds target == abs(var).
640  Constraint AddAbsEquality(IntVar target, IntVar var);
641 
642  // Adds target = var % mod.
643  Constraint AddModuloEquality(IntVar target, IntVar var, IntVar mod);
644 
645  // Adds target == prod(vars).
646  Constraint AddProductEquality(IntVar target, absl::Span<const IntVar> vars);
647 
648  // Adds a constraint than ensures that all present intervals do not overlap
649  // in time.
650  Constraint AddNoOverlap(absl::Span<const IntervalVar> vars);
651 
652  // The no_overlap_2d constraint prevents a set of boxes from overlapping.
654 
655  // The cumulative constraint ensures that for any integer point, the sum of
656  // the demands of the intervals containing that point does not exceed the
657  // capacity.
659 
660  // Adds a linear minimization objective.
661  void Minimize(const LinearExpr& expr);
662 
663  // Adds a linear maximization objective.
664  void Maximize(const LinearExpr& expr);
665 
666  // Sets scaling of the objective. (must be called after Minimize() of
667  // Maximize()). 'scaling' must be > 0.0.
668  void ScaleObjectiveBy(double scaling);
669 
670  // Adds a decision strategy on a list of integer variables.
671  void AddDecisionStrategy(
672  absl::Span<const IntVar> variables,
675 
676  // Adds a decision strategy on a list of boolean variables.
677  void AddDecisionStrategy(
678  absl::Span<const BoolVar> variables,
681 
682  // TODO(user) : add MapDomain?
683 
684  const CpModelProto& Build() const { return Proto(); }
685 
686  const CpModelProto& Proto() const { return cp_model_; }
687  CpModelProto* MutableProto() { return &cp_model_; }
688 
689  private:
690  friend class CumulativeConstraint;
691  friend class ReservoirConstraint;
692 
693  // Returns a (cached) integer variable index with a constant value.
694  int IndexFromConstant(int64 value);
695 
696  // Returns a valid integer index from a BoolVar index.
697  // If the input index is a positive, it returns this index.
698  // If the input index is negative, it creates a cached IntVar equal to
699  // 1 - BoolVar(PositiveRef(index)), and returns the index of this new
700  // variable.
701  int GetOrCreateIntegerIndex(int index);
702 
703  void FillLinearTerms(const LinearExpr& left, const LinearExpr& right,
704  LinearConstraintProto* proto);
705 
706  CpModelProto cp_model_;
707  absl::flat_hash_map<int64, int> constant_to_index_map_;
708  absl::flat_hash_map<int, int> bool_to_integer_index_map_;
709 };
710 
711 // Evaluates the value of an linear expression in a solver response.
712 int64 SolutionIntegerValue(const CpSolverResponse& r, const LinearExpr& expr);
713 
714 // Returns the min of an integer variable in a solution.
715 int64 SolutionIntegerMin(const CpSolverResponse& r, IntVar x);
716 
717 // Returns the max of an integer variable in a solution.
718 int64 SolutionIntegerMax(const CpSolverResponse& r, IntVar x);
719 
720 // Returns the value of a Boolean literal (a Boolean variable or its negation)
721 // in a solver response.
723 
724 } // namespace sat
725 } // namespace operations_research
726 
727 #endif // OR_TOOLS_SAT_CP_MODEL_H_
ReservoirConstraint AddReservoirConstraint(int64 min_level, int64 max_level)
Adds a reservoir constraint with optional refill/emptying events.
Constraint AddGreaterThan(const LinearExpr &left, const LinearExpr &right)
Adds left > right.
IntVar NewIntVar(const Domain &domain)
Creates an integer variable with the given domain.
Constraint AddBoolOr(absl::Span< const BoolVar > literals)
Adds the constraint that at least one of the literals must be true.
void Maximize(const LinearExpr &expr)
Adds a linear maximization objective.
void AddTransition(int tail, int head, int64 transition_label)
bool operator==(const BoolVar &other) const
Definition: cp_model.h:71
std::ostream & operator<<(std::ostream &os, const BoolVar &var)
Constraint WithName(const std::string &name)
Sets the name of the constraint.
const std::vector< IntVar > & variables() const
Useful for testing.
Definition: cp_model.h:246
const ConstraintProto & Proto() const
Useful for testing.
Definition: cp_model.h:367
void AddDemand(IntervalVar interval, IntVar demand)
void AddOptionalEvent(IntVar time, int64 demand, BoolVar is_active)
Constraint AddImplication(BoolVar a, BoolVar b)
Adds a => b.
Definition: cp_model.h:507
ConstraintProto * MutableProto() const
Useful for model edition.
Definition: cp_model.h:370
void AddRectangle(IntervalVar x_coordinate, IntervalVar y_coordinate)
Constraint AddLinearConstraint(const LinearExpr &expr, const Domain &domain)
Adds expr in domain.
Constraint(ConstraintProto *proto)
Constraint AddMinEquality(IntVar target, absl::Span< const IntVar > vars)
Adds target == min(vars).
IntVar StartVar() const
Returns the start variable.
int64 SolutionIntegerMin(const CpSolverResponse &r, IntVar x)
Returns the min of an integer variable in a solution.
Constraint AddModuloEquality(IntVar target, IntVar var, IntVar mod)
Adds target = var % mod.
Wrapper class around the cp_model proto.
Definition: cp_model.h:473
IntVar EndVar() const
Returns the end variable.
IntervalConstraintProto * MutableProto() const
Useful for model edition.
Definition: cp_model.h:314
Constraint AddInverseConstraint(absl::Span< const IntVar > variables, absl::Span< const IntVar > inverse_variables)
An inverse constraint enforces that if 'variables[i]' is assigned a value 'j', then inverse_variables...
Specialized reservoir constraint.
Definition: cp_model.h:411
const CpModelProto & Proto() const
Definition: cp_model.h:686
A dedicated container for linear expressions.
Definition: cp_model.h:208
int64 SolutionIntegerMax(const CpSolverResponse &r, IntVar x)
Returns the max of an integer variable in a solution.
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.
static LinearExpr Sum(absl::Span< const IntVar > vars)
Constructs the sum of a list of variables.
CircuitConstraint AddCircuitConstraint()
Adds a circuit constraint.
Constraint AddBoolAnd(absl::Span< const BoolVar > literals)
Adds the constraint that all literals must be true.
BoolVar NewBoolVar()
Creates a Boolean variable.
BoolVar FalseVar()
Creates an always false Boolean variable.
friend bool SolutionBooleanValue(const CpSolverResponse &r, BoolVar x)
Returns the value of a Boolean literal (a Boolean variable or its negation) in a solver response.
Constraint AddMaxEquality(IntVar target, absl::Span< const IntVar > vars)
Adds target == max(vars).
CumulativeConstraint AddCumulative(IntVar capacity)
The cumulative constraint ensures that for any integer point, the sum of the demands of the intervals...
Constraint AddDivisionEquality(IntVar target, IntVar numerator, IntVar denominator)
Adds target = num / denom (integer division rounded towards 0).
Represents a Interval variable.
Definition: cp_model.h:275
const IntervalConstraintProto & Proto() const
Useful for testing.
Definition: cp_model.h:309
IntVar WithName(const std::string &name)
Sets the name of the variable.
BoolVar WithName(const std::string &name)
Sets the name of the variable.
void AddEvent(IntVar time, int64 demand)
Constraint AddGreaterOrEqual(const LinearExpr &left, const LinearExpr &right)
Adds left >= right.
BoolVar PresenceBoolVar() const
Returns a BoolVar indicating the presence of this interval.
IntervalVar NewIntervalVar(IntVar start, IntVar size, IntVar end)
Creates an interval variable.
IntervalVar NewOptionalIntervalVar(IntVar start, IntVar size, IntVar end, BoolVar presence)
Creates an optional interval variable.
int index() const
Returns the index of the interval constraint in the model.
Definition: cp_model.h:319
Specialized cumulative constraint.
Definition: cp_model.h:456
static LinearExpr BooleanScalProd(absl::Span< const BoolVar > vars, absl::Span< const int64 > coeffs)
Constructs the scalar product of Booleans and coefficients.
Constraint AddElement(IntVar index, absl::Span< const int64 > values, IntVar target)
Adds the element constraint: values[index] == target.
const ::operations_research::sat::ConstraintProto & constraints(int index) const
Definition: cp_model.pb.h:7258
Constraint AddAbsEquality(IntVar target, IntVar var)
Adds target == abs(var).
Constraint AddAllDifferent(absl::Span< const IntVar > vars)
this constraint forces all variables to have different values.
A Boolean variable.
Definition: cp_model.h:59
TableConstraint AddForbiddenAssignments(absl::Span< const IntVar > vars)
Adds an forbidden assignments constraint.
Specialized assignment constraint.
Definition: cp_model.h:397
BoolVar Not(BoolVar x)
A convenient wrapper so we can write Not(x) instead of x.Not() which is sometimes clearer.
bool operator!=(const BoolVar &other) const
Definition: cp_model.h:75
bool operator!=(const IntervalVar &other) const
Definition: cp_model.h:302
void ScaleObjectiveBy(double scaling)
Sets scaling of the objective.
const CpModelProto & Build() const
Definition: cp_model.h:684
friend int64 SolutionIntegerMax(const CpSolverResponse &r, IntVar x)
Returns the max of an integer variable in a solution.
Constraint AddLessThan(const LinearExpr &left, const LinearExpr &right)
Adds left < right.
const std::string & Name() const
::operations_research::sat::IntegerVariableProto * mutable_variables(int index)
Definition: cp_model.pb.h:7219
bool operator!=(const IntVar &other) const
Definition: cp_model.h:140
Specialized no_overlap2D constraint.
Definition: cp_model.h:442
bool operator==(const IntervalVar &other) const
Definition: cp_model.h:298
const std::string & Name() const
Definition: cp_model.h:134
IntVar NewConstant(int64 value)
Creates a constant variable.
friend int64 SolutionIntegerMin(const CpSolverResponse &r, IntVar x)
Returns the min of an integer variable in a solution.
bool SolutionBooleanValue(const CpSolverResponse &r, BoolVar x)
Returns the value of a Boolean literal (a Boolean variable or its negation) in a solver response.
Constraint AddBoolXor(absl::Span< const BoolVar > literals)
Adds the constraint that a odd number of literal is true.
friend int64 SolutionIntegerValue(const CpSolverResponse &r, const LinearExpr &expr)
Evaluates the value of an linear expression in a solver response.
const std::string & Name() const
Definition: cp_model.h:66
std::string DebugString() const
Constraint AddProductEquality(IntVar target, absl::Span< const IntVar > vars)
Adds target == prod(vars).
TableConstraint AddAllowedAssignments(absl::Span< const IntVar > vars)
Adds an allowed assignments constraint.
static LinearExpr ScalProd(absl::Span< const IntVar > vars, absl::Span< const int64 > coeffs)
Constructs the scalar product of variables and coefficients.
int64 SolutionIntegerValue(const CpSolverResponse &r, const LinearExpr &expr)
Evaluates the value of an linear expression in a solver response.
const IntegerVariableProto & Proto() const
Useful for testing.
Definition: cp_model.h:82
void Minimize(const LinearExpr &expr)
Adds a linear minimization objective.
void AddTerm(IntVar var, int64 coeff)
Adds a term (var * coeff) to the linear expression.
We call "domain" any subset of Int64 = [kint64min, kint64max].
friend std::ostream & operator<<(std::ostream &os, const IntervalVar &var)
::operations_research::sat::ConstraintProto * mutable_constraints(int index)
Definition: cp_model.pb.h:7249
IntVar SizeVar() const
Returns the size variable.
LinearExpr & AddConstant(int64 value)
Adds a constant value to the linear expression.
void AddTuple(absl::Span< const int64 > tuple)
IntegerVariableProto * MutableProto() const
Useful for model edition.
Definition: cp_model.h:87
AutomatonConstraint AddAutomaton(absl::Span< const IntVar > transition_variables, int starting_state, absl::Span< const int > final_states)
An automaton constraint takes a list of variables (of size n), an initial state, a set of final state...
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in c...
Definition: cp_model.h:48
NoOverlap2DConstraint AddNoOverlap2D()
The no_overlap_2d constraint prevents a set of boxes from overlapping.
Specialized circuit constraint.
Definition: cp_model.h:383
An integer variable.
Definition: cp_model.h:124
IntervalVar WithName(const std::string &name)
Sets the name of the variable.
::operations_research::sat::IntervalConstraintProto * mutable_interval()
Definition: cp_model.pb.h:6685
int index() const
Returns the index of the variable in the model.
Definition: cp_model.h:93
std::string DebugString() const
const IntegerVariableProto & Proto() const
Useful for testing.
Definition: cp_model.h:147
const ::operations_research::sat::IntegerVariableProto & variables(int index) const
Definition: cp_model.pb.h:7228
Constraint AddNoOverlap(absl::Span< const IntervalVar > vars)
Adds a constraint than ensures that all present intervals do not overlap in time.
IntegerVariableProto * MutableProto() const
Useful for model edition.
Definition: cp_model.h:152
Constraint AddVariableElement(IntVar index, absl::Span< const IntVar > variables, IntVar target)
Adds the element constraint: variables[index] == target.
Constraint AddEquality(const LinearExpr &left, const LinearExpr &right)
Adds left == right.
Constraint AddLessOrEqual(const LinearExpr &left, const LinearExpr &right)
Adds left <= right.
bool operator==(const IntVar &other) const
Definition: cp_model.h:136
static LinearExpr BooleanSum(absl::Span< const BoolVar > vars)
Constructs the sum of a list of Booleans.
void AddArc(int tail, int head, BoolVar literal)
Specialized automaton constraint.
Definition: cp_model.h:428
Constraint AddNotEqual(const LinearExpr &left, const LinearExpr &right)
Adds left != right.
void AddVar(IntVar var)
Adds a single integer variable to the linear expression.
const std::vector< int64 > & coefficients() const
Definition: cp_model.h:247
const ::operations_research::sat::IntervalConstraintProto & interval() const
Definition: cp_model.pb.h:6679
BoolVar TrueVar()
Creates an always true Boolean variable.
Constraint OnlyEnforceIf(absl::Span< const BoolVar > literals)
The constraint will be enforced iff all literals listed here are true.
int index() const
Returns the index of the variable in the model.
Definition: cp_model.h:157
BoolVar Not() const
Returns the logical negation of the current Boolean variable.
Definition: cp_model.h:69