Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cp_model_mapping.h
Go to the documentation of this file.
1// Copyright 2010-2025 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 <vector>
18
19#include "absl/container/flat_hash_set.h"
20#include "absl/log/check.h"
23#include "ortools/sat/cp_model.pb.h"
28#include "ortools/sat/model.h"
31
32namespace operations_research {
33namespace sat {
34
35// For an optimization problem, this contains the internal integer objective
36// to minimize and information on how to display it correctly in the logs.
38 double scaling_factor = 1.0;
39 double offset = 0.0;
41
42 // The objective linear expression that should be equal to objective_var.
43 // If not all proto variable have an IntegerVariable view, then some vars
44 // will be set to kNoIntegerVariable. In practice, when this is used, we make
45 // sure there is a view though.
46 std::vector<IntegerVariable> vars;
47 std::vector<IntegerValue> coeffs;
48
49 // List of variable that when set to their lower bound should help getting a
50 // better objective. This is used by some search heuristic to preferably
51 // assign any of the variable here to their lower bound first.
52 absl::flat_hash_set<IntegerVariable> objective_impacting_variables;
53
54 double ScaleIntegerObjective(IntegerValue value) const {
55 return (ToDouble(value) + offset) * scaling_factor;
56 }
57
58 double ScaleObjective(double value) const {
59 return (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 result.reserve(list.size());
115 for (const auto i : list) result.push_back(Integer(i));
116 return result;
117 }
118
119 template <typename ProtoIndices>
120 std::vector<sat::Literal> Literals(const ProtoIndices& indices) const {
121 std::vector<sat::Literal> result;
122 result.reserve(indices.size());
123 for (const int i : indices) result.push_back(CpModelMapping::Literal(i));
124 return result;
125 }
126
127 template <typename List>
128 std::vector<AffineExpression> Affines(const List& list) const {
129 std::vector<AffineExpression> result;
130 result.reserve(list.size());
131 for (const auto& i : list) result.push_back(Affine(i));
132 return result;
133 }
134
135 template <typename ProtoIndices>
136 std::vector<IntervalVariable> Intervals(const ProtoIndices& indices) const {
137 std::vector<IntervalVariable> result;
138 result.reserve(indices.size());
139 for (const int i : indices) result.push_back(Interval(i));
140 return result;
141 }
142
143 // Depending on the option, we will load constraints in stages. This is used
144 // to detect constraints that are already loaded. For instance the interval
145 // constraints and the linear constraint of size 1 (encodings) are usually
146 // loaded first.
147 bool ConstraintIsAlreadyLoaded(const ConstraintProto* ct) const {
148 return already_loaded_ct_.contains(ct);
149 }
150
151 // Returns true if the given constraint is a "half-encoding" constraint. That
152 // is, if it is of the form (b => size 1 linear) but there is no (<=) side in
153 // the model. Such constraint are detected while we extract integer encoding
154 // and are cached here so that we can deal properly with them during the
155 // linear relaxation.
156 bool IsHalfEncodingConstraint(const ConstraintProto* ct) const {
157 return is_half_encoding_ct_.contains(ct);
158 }
159
160 // Note that both these functions returns positive reference or -1.
161 int GetProtoVariableFromBooleanVariable(BooleanVariable var) const {
162 if (var.value() >= reverse_boolean_map_.size()) return -1;
163 return reverse_boolean_map_[var];
164 }
165 int GetProtoVariableFromIntegerVariable(IntegerVariable var) const {
166 if (var.value() >= reverse_integer_map_.size()) return -1;
167 return reverse_integer_map_[var];
168 }
169
170 // This one should only be used when we have a mapping.
172 const int proto_var = GetProtoVariableFromBooleanVariable(lit.Variable());
173 DCHECK_NE(proto_var, -1);
174 return lit.IsPositive() ? proto_var : NegatedRef(proto_var);
175 }
176
177 const std::vector<IntegerVariable>& GetVariableMapping() const {
178 return integers_;
179 }
180
182 const LinearExpressionProto& expr_proto) const {
183 LinearExpression expr;
184 expr.vars = Integers(expr_proto.vars());
185 for (int j = 0; j < expr_proto.coeffs_size(); ++j) {
186 expr.coeffs.push_back(IntegerValue(expr_proto.coeffs(j)));
187 }
188 expr.offset = IntegerValue(expr_proto.offset());
189 return CanonicalizeExpr(expr);
190 }
191
192 // For logging only, these are not super efficient.
194 int result = 0;
195 for (const IntegerVariable var : integers_) {
196 if (var != kNoIntegerVariable) result++;
197 }
198 return result;
199 }
201 int result = 0;
202 for (const BooleanVariable var : booleans_) {
203 if (var != kNoBooleanVariable) result++;
204 }
205 return result;
206 }
207
208 // Returns the number of variables in the loaded proto.
209 int NumProtoVariables() const { return integers_.size(); }
210
211 private:
212 friend void LoadVariables(const CpModelProto& model_proto,
213 bool view_all_booleans_as_integers, Model* m);
214 friend void ExtractEncoding(const CpModelProto& model_proto, Model* m);
215
216 // Note that only the variables used by at least one constraint will be
217 // created, the other will have a kNo[Integer,Interval,Boolean]VariableValue.
218 std::vector<IntegerVariable> integers_;
219 std::vector<IntervalVariable> intervals_;
220 std::vector<BooleanVariable> booleans_;
221
222 // Recover from a IntervalVariable/BooleanVariable its associated CpModelProto
223 // index. The value of -1 is used to indicate that there is no correspondence
224 // (i.e. this variable is only used internally).
227
228 // Set of constraints to ignore because they were already dealt with by
229 // ExtractEncoding().
230 absl::flat_hash_set<const ConstraintProto*> already_loaded_ct_;
231 absl::flat_hash_set<const ConstraintProto*> is_half_encoding_ct_;
232};
233
234} // namespace sat
235} // namespace operations_research
236
237#endif // OR_TOOLS_SAT_CP_MODEL_MAPPING_H_
friend void LoadVariables(const CpModelProto &model_proto, bool view_all_booleans_as_integers, Model *m)
int NumIntegerVariables() const
For logging only, these are not super efficient.
std::vector< IntegerVariable > Integers(const List &list) const
AffineExpression Affine(const LinearExpressionProto &exp) const
int GetProtoVariableFromBooleanVariable(BooleanVariable var) const
int GetProtoLiteralFromLiteral(sat::Literal lit) const
This one should only be used when we have a mapping.
bool ConstraintIsAlreadyLoaded(const ConstraintProto *ct) const
bool IsHalfEncodingConstraint(const ConstraintProto *ct) const
std::vector< IntervalVariable > Intervals(const ProtoIndices &indices) const
int NumProtoVariables() const
Returns the number of variables in the loaded proto.
int GetProtoVariableFromIntegerVariable(IntegerVariable var) const
LinearExpression GetExprFromProto(const LinearExpressionProto &expr_proto) const
friend void ExtractEncoding(const CpModelProto &model_proto, Model *m)
std::vector< sat::Literal > Literals(const ProtoIndices &indices) const
std::vector< AffineExpression > Affines(const List &list) const
IntervalVariable Interval(int i) const
IntegerVariable Integer(int ref) const
const std::vector< IntegerVariable > & GetVariableMapping() const
BooleanVariable Variable() const
Definition sat_base.h:87
std::vector< IntegerVariable > NegationOf(absl::Span< const IntegerVariable > vars)
Returns the vector of the negated variables.
Definition integer.cc:52
const IntegerVariable kNoIntegerVariable(-1)
const IntervalVariable kNoIntervalVariable(-1)
LinearExpression CanonicalizeExpr(const LinearExpression &expr)
const BooleanVariable kNoBooleanVariable(-1)
int NegatedRef(int ref)
Small utility functions to deal with negative variable/literal references.
double ToDouble(IntegerValue value)
In SWIG mode, we don't want anything besides these top-level includes.
absl::flat_hash_set< IntegerVariable > objective_impacting_variables
double ScaleIntegerObjective(IntegerValue value) const