OR-Tools  9.6
cp_model_mapping.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 
14 #ifndef OR_TOOLS_SAT_CP_MODEL_MAPPING_H_
15 #define OR_TOOLS_SAT_CP_MODEL_MAPPING_H_
16 
17 #include <cstdint>
18 #include <functional>
19 #include <vector>
20 
21 #include "absl/container/flat_hash_map.h"
22 #include "absl/container/flat_hash_set.h"
23 #include "absl/meta/type_traits.h"
25 #include "ortools/base/logging.h"
27 #include "ortools/sat/cp_model.pb.h"
29 #include "ortools/sat/integer.h"
30 #include "ortools/sat/intervals.h"
32 #include "ortools/sat/model.h"
33 #include "ortools/sat/sat_base.h"
35 
36 namespace operations_research {
37 namespace sat {
38 
39 // For an optimization problem, this contains the internal integer objective
40 // to minimize and information on how to display it correctly in the logs.
42  double scaling_factor = 1.0;
43  double offset = 0.0;
44  IntegerVariable objective_var = kNoIntegerVariable;
45 
46  // The objective linear expression that should be equal to objective_var.
47  // If not all proto variable have an IntegerVariable view, then some vars
48  // will be set to kNoIntegerVariable. In practice, when this is used, we make
49  // sure there is a view though.
50  std::vector<IntegerVariable> vars;
51  std::vector<IntegerValue> coeffs;
52 
53  // List of variable that when set to their lower bound should help getting a
54  // better objective. This is used by some search heuristic to preferably
55  // assign any of the variable here to their lower bound first.
56  absl::flat_hash_set<IntegerVariable> objective_impacting_variables;
57 
58  double ScaleIntegerObjective(IntegerValue value) const {
59  return (ToDouble(value) + offset) * scaling_factor;
60  }
61 };
62 
63 // Holds the mapping between CpModel proto indices and the sat::model ones.
64 //
65 // This also holds some information used when loading a CpModel proto.
67  public:
68  // Returns true if the given CpModelProto variable reference refers to a
69  // Boolean variable. Such variable will always have an associated Literal(),
70  // but not always an associated Integer().
71  bool IsBoolean(int ref) const {
72  DCHECK_LT(PositiveRef(ref), booleans_.size());
73  return booleans_[PositiveRef(ref)] != kNoBooleanVariable;
74  }
75 
76  bool IsInteger(int ref) const {
77  DCHECK_LT(PositiveRef(ref), integers_.size());
78  return integers_[PositiveRef(ref)] != kNoIntegerVariable;
79  }
80 
81  sat::Literal Literal(int ref) const {
82  DCHECK(IsBoolean(ref));
83  return sat::Literal(booleans_[PositiveRef(ref)], RefIsPositive(ref));
84  }
85 
86  IntegerVariable Integer(int ref) const {
87  DCHECK(IsInteger(ref));
88  const IntegerVariable var = integers_[PositiveRef(ref)];
89  return RefIsPositive(ref) ? var : NegationOf(var);
90  }
91 
92  // TODO(user): We could "easily" create an intermediate variable for more
93  // complex linear expression. We could also identify duplicate expressions to
94  // not create two identical integer variable.
95  AffineExpression Affine(const LinearExpressionProto& exp) const {
96  CHECK_LE(exp.vars().size(), 1);
97  if (exp.vars().empty()) {
98  return AffineExpression(IntegerValue(exp.offset()));
99  }
100  return AffineExpression(Integer(exp.vars(0)), IntegerValue(exp.coeffs(0)),
101  IntegerValue(exp.offset()));
102  }
103 
104  IntervalVariable Interval(int i) const {
105  CHECK_GE(i, 0);
106  CHECK_LT(i, intervals_.size());
107  CHECK_NE(intervals_[i], kNoIntervalVariable);
108  return intervals_[i];
109  }
110 
111  template <typename List>
112  std::vector<IntegerVariable> Integers(const List& list) const {
113  std::vector<IntegerVariable> result;
114  for (const auto i : list) result.push_back(Integer(i));
115  return result;
116  }
117 
118  template <typename ProtoIndices>
119  std::vector<sat::Literal> Literals(const ProtoIndices& indices) const {
120  std::vector<sat::Literal> result;
121  for (const int i : indices) result.push_back(CpModelMapping::Literal(i));
122  return result;
123  }
124 
125  template <typename List>
126  std::vector<AffineExpression> Affines(const List& list) const {
127  std::vector<AffineExpression> result;
128  for (const auto& i : list) result.push_back(Affine(i));
129  return result;
130  }
131 
132  template <typename ProtoIndices>
133  std::vector<IntervalVariable> Intervals(const ProtoIndices& indices) const {
134  std::vector<IntervalVariable> result;
135  for (const int i : indices) result.push_back(Interval(i));
136  return result;
137  }
138 
139  // Depending on the option, we will load constraints in stages. This is used
140  // to detect constraints that are already loaded. For instance the interval
141  // constraints and the linear constraint of size 1 (encodings) are usually
142  // loaded first.
143  bool ConstraintIsAlreadyLoaded(const ConstraintProto* ct) const {
144  return already_loaded_ct_.contains(ct);
145  }
146 
147  // Returns true if the given constraint is a "half-encoding" constraint. That
148  // is, if it is of the form (b => size 1 linear) but there is no (<=) side in
149  // the model. Such constraint are detected while we extract integer encoding
150  // and are cached here so that we can deal properly with them during the
151  // linear relaxation.
152  bool IsHalfEncodingConstraint(const ConstraintProto* ct) const {
153  return is_half_encoding_ct_.contains(ct);
154  }
155 
156  // Note that both these functions returns positive reference or -1.
157  int GetProtoVariableFromBooleanVariable(BooleanVariable var) const {
158  if (var.value() >= reverse_boolean_map_.size()) return -1;
159  return reverse_boolean_map_[var];
160  }
161  int GetProtoVariableFromIntegerVariable(IntegerVariable var) const {
162  if (var.value() >= reverse_integer_map_.size()) return -1;
163  return reverse_integer_map_[var];
164  }
165 
166  const std::vector<IntegerVariable>& GetVariableMapping() const {
167  return integers_;
168  }
169 
171  const LinearExpressionProto& expr_proto) const {
172  LinearExpression expr;
173  expr.vars = Integers(expr_proto.vars());
174  for (int j = 0; j < expr_proto.coeffs_size(); ++j) {
175  expr.coeffs.push_back(IntegerValue(expr_proto.coeffs(j)));
176  }
177  expr.offset = IntegerValue(expr_proto.offset());
178  return CanonicalizeExpr(expr);
179  }
180 
181  // For logging only, these are not super efficient.
182  int NumIntegerVariables() const {
183  int result = 0;
184  for (const IntegerVariable var : integers_) {
185  if (var != kNoIntegerVariable) result++;
186  }
187  return result;
188  }
189  int NumBooleanVariables() const {
190  int result = 0;
191  for (const BooleanVariable var : booleans_) {
192  if (var != kNoBooleanVariable) result++;
193  }
194  return result;
195  }
196 
197  // Returns the number of variables in the loaded proto.
198  int NumProtoVariables() const { return integers_.size(); }
199 
200  private:
201  friend void LoadVariables(const CpModelProto& model_proto,
202  bool view_all_booleans_as_integers, Model* m);
203  friend void ExtractEncoding(const CpModelProto& model_proto, Model* m);
204 
205  // Note that only the variables used by at least one constraint will be
206  // created, the other will have a kNo[Integer,Interval,Boolean]VariableValue.
207  std::vector<IntegerVariable> integers_;
208  std::vector<IntervalVariable> intervals_;
209  std::vector<BooleanVariable> booleans_;
210 
211  // Recover from a IntervalVariable/BooleanVariable its associated CpModelProto
212  // index. The value of -1 is used to indicate that there is no correspondence
213  // (i.e. this variable is only used internally).
214  absl::StrongVector<BooleanVariable, int> reverse_boolean_map_;
215  absl::StrongVector<IntegerVariable, int> reverse_integer_map_;
216 
217  // Set of constraints to ignore because they were already dealt with by
218  // ExtractEncoding().
219  absl::flat_hash_set<const ConstraintProto*> already_loaded_ct_;
220  absl::flat_hash_set<const ConstraintProto*> is_half_encoding_ct_;
221 };
222 
223 } // namespace sat
224 } // namespace operations_research
225 
226 #endif // OR_TOOLS_SAT_CP_MODEL_MAPPING_H_
size_type size() const
IntervalVariable Interval(int i) const
std::vector< sat::Literal > Literals(const ProtoIndices &indices) const
int GetProtoVariableFromIntegerVariable(IntegerVariable var) const
friend void LoadVariables(const CpModelProto &model_proto, bool view_all_booleans_as_integers, Model *m)
std::vector< IntegerVariable > Integers(const List &list) const
std::vector< AffineExpression > Affines(const List &list) const
const std::vector< IntegerVariable > & GetVariableMapping() const
std::vector< IntervalVariable > Intervals(const ProtoIndices &indices) const
bool ConstraintIsAlreadyLoaded(const ConstraintProto *ct) const
AffineExpression Affine(const LinearExpressionProto &exp) const
bool IsHalfEncodingConstraint(const ConstraintProto *ct) const
int GetProtoVariableFromBooleanVariable(BooleanVariable var) const
IntegerVariable Integer(int ref) const
sat::Literal Literal(int ref) const
LinearExpression GetExprFromProto(const LinearExpressionProto &expr_proto) const
friend void ExtractEncoding(const CpModelProto &model_proto, Model *m)
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:42
CpModelProto const * model_proto
const Constraint * ct
int64_t value
IntVar * var
Definition: expr_array.cc:1874
bool RefIsPositive(int ref)
const IntegerVariable kNoIntegerVariable(-1)
const IntervalVariable kNoIntervalVariable(-1)
LinearExpression CanonicalizeExpr(const LinearExpression &expr)
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
Definition: integer.cc:46
const BooleanVariable kNoBooleanVariable(-1)
double ToDouble(IntegerValue value)
Definition: integer.h:77
Collection of objects used to extend the Constraint Solver library.
double ScaleIntegerObjective(IntegerValue value) const
absl::flat_hash_set< IntegerVariable > objective_impacting_variables