OR-Tools  9.3
cp_model_mapping.h
Go to the documentation of this file.
1// Copyright 2010-2021 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"
27#include "ortools/sat/cp_model.pb.h"
29#include "ortools/sat/integer.h"
32#include "ortools/sat/model.h"
35
36namespace operations_research {
37namespace 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;
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.
183 int result = 0;
184 for (const IntegerVariable var : integers_) {
185 if (var != kNoIntegerVariable) result++;
186 }
187 return result;
188 }
190 int result = 0;
191 for (const BooleanVariable var : booleans_) {
192 if (var != kNoBooleanVariable) result++;
193 }
194 return result;
195 }
196
197 // Returns a heuristic set of values that could be created for the given
198 // variable when the constraints will be loaded.
199 // Note that the pointer is not stable across calls.
200 // It returns nullptr if the set is empty.
201 const absl::flat_hash_set<int64_t>& PotentialEncodedValues(int var) {
202 const auto& it = variables_to_encoded_values_.find(var);
203 if (it != variables_to_encoded_values_.end()) {
204 return it->second;
205 }
206 return empty_set_;
207 }
208
209 // Returns the number of variables in the loaded proto.
210 int NumProtoVariables() const { return integers_.size(); }
211
212 private:
213 friend void LoadVariables(const CpModelProto& model_proto,
214 bool view_all_booleans_as_integers, Model* m);
215 friend void ExtractEncoding(const CpModelProto& model_proto, Model* m);
216
217 // Note that only the variables used by at least one constraint will be
218 // created, the other will have a kNo[Integer,Interval,Boolean]VariableValue.
219 std::vector<IntegerVariable> integers_;
220 std::vector<IntervalVariable> intervals_;
221 std::vector<BooleanVariable> booleans_;
222
223 // Recover from a IntervalVariable/BooleanVariable its associated CpModelProto
224 // index. The value of -1 is used to indicate that there is no correspondence
225 // (i.e. this variable is only used internally).
226 absl::StrongVector<BooleanVariable, int> reverse_boolean_map_;
227 absl::StrongVector<IntegerVariable, int> reverse_integer_map_;
228
229 // Set of constraints to ignore because they were already dealt with by
230 // ExtractEncoding().
231 absl::flat_hash_set<const ConstraintProto*> already_loaded_ct_;
232 absl::flat_hash_set<const ConstraintProto*> is_half_encoding_ct_;
233
234 absl::flat_hash_map<int, absl::flat_hash_set<int64_t>>
235 variables_to_encoded_values_;
236 const absl::flat_hash_set<int64_t> empty_set_;
237};
238
239} // namespace sat
240} // namespace operations_research
241
242#endif // OR_TOOLS_SAT_CP_MODEL_MAPPING_H_
#define CHECK_LT(val1, val2)
Definition: base/logging.h:706
#define CHECK_GE(val1, val2)
Definition: base/logging.h:707
#define CHECK_NE(val1, val2)
Definition: base/logging.h:704
#define DCHECK_LT(val1, val2)
Definition: base/logging.h:894
#define DCHECK(condition)
Definition: base/logging.h:890
#define CHECK_LE(val1, val2)
Definition: base/logging.h:705
size_type size() const
IntervalVariable Interval(int i) const
int GetProtoVariableFromIntegerVariable(IntegerVariable var) const
friend void LoadVariables(const CpModelProto &model_proto, bool view_all_booleans_as_integers, Model *m)
const absl::flat_hash_set< int64_t > & PotentialEncodedValues(int var)
std::vector< IntegerVariable > Integers(const List &list) 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
std::vector< AffineExpression > Affines(const List &list) const
sat::Literal Literal(int ref) const
LinearExpression GetExprFromProto(const LinearExpressionProto &expr_proto) const
const std::vector< IntegerVariable > & GetVariableMapping() const
friend void ExtractEncoding(const CpModelProto &model_proto, Model *m)
std::vector< sat::Literal > Literals(const ProtoIndices &indices) const
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:47
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