Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cp_model_utils.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_UTILS_H_
15#define OR_TOOLS_SAT_CP_MODEL_UTILS_H_
16
17#include <algorithm>
18#include <cstdint>
19#include <functional>
20#include <limits>
21#include <string>
22#include <vector>
23
24#if !defined(__PORTABLE_PLATFORM__)
26#endif // !defined(__PORTABLE_PLATFORM__)
27#include "absl/log/check.h"
28#include "absl/status/status.h"
29#include "absl/strings/match.h"
30#include "absl/strings/string_view.h"
31#include "absl/types/span.h"
32#include "google/protobuf/message.h"
33#include "google/protobuf/text_format.h"
34#include "ortools/base/hash.h"
36#include "ortools/sat/cp_model.pb.h"
37#include "ortools/util/bitset.h"
39
40namespace operations_research {
41namespace sat {
42
43// Small utility functions to deal with negative variable/literal references.
44inline int NegatedRef(int ref) { return -ref - 1; }
45inline int PositiveRef(int ref) { return std::max(ref, NegatedRef(ref)); }
46inline bool RefIsPositive(int ref) { return ref >= 0; }
47
48// Small utility functions to deal with half-reified constraints.
49inline bool HasEnforcementLiteral(const ConstraintProto& ct) {
50 return !ct.enforcement_literal().empty();
51}
52inline int EnforcementLiteral(const ConstraintProto& ct) {
53 return ct.enforcement_literal(0);
54}
55
56// Returns the gcd of the given LinearExpressionProto.
57// Specifying the second argument will take the gcd with it.
58int64_t LinearExpressionGcd(const LinearExpressionProto& expr, int64_t gcd = 0);
59
60// Divide the expression in place by 'divisor'.
61// It will DCHECK that 'divisor' divides all constants.
62void DivideLinearExpression(int64_t divisor, LinearExpressionProto* expr);
63
64// Fills the target as negated ref.
65void SetToNegatedLinearExpression(const LinearExpressionProto& input_expr,
66 LinearExpressionProto* output_negated_expr);
67
68// Collects all the references used by a constraint. This function is used in a
69// few places to have a "generic" code dealing with constraints. Note that the
70// enforcement_literal is NOT counted here and that the vectors can have
71// duplicates.
73 std::vector<int> variables;
74 std::vector<int> literals;
75};
76IndexReferences GetReferencesUsedByConstraint(const ConstraintProto& ct);
77void GetReferencesUsedByConstraint(const ConstraintProto& ct,
78 std::vector<int>* variables,
79 std::vector<int>* literals);
80
81// Applies the given function to all variables/literals/intervals indices of the
82// constraint. This function is used in a few places to have a "generic" code
83// dealing with constraints.
84void ApplyToAllVariableIndices(const std::function<void(int*)>& function,
85 ConstraintProto* ct);
86void ApplyToAllLiteralIndices(const std::function<void(int*)>& function,
87 ConstraintProto* ct);
88void ApplyToAllIntervalIndices(const std::function<void(int*)>& function,
89 ConstraintProto* ct);
90
91// Returns the name of the ConstraintProto::ConstraintCase oneof enum.
92// Note(user): There is no such function in the proto API as of 16/01/2017.
93absl::string_view ConstraintCaseName(
94 ConstraintProto::ConstraintCase constraint_case);
95
96// Returns the sorted list of variables used by a constraint.
97// Note that this include variable used as a literal.
98std::vector<int> UsedVariables(const ConstraintProto& ct);
99
100// Returns the sorted list of interval used by a constraint.
101std::vector<int> UsedIntervals(const ConstraintProto& ct);
102
103// Insert/Remove variables from an interval constraint into a bitset.
104inline void InsertVariablesFromInterval(const CpModelProto& model_proto,
105 int index, Bitset64<int>& output) {
106 const ConstraintProto& ct = model_proto.constraints(index);
107 for (const int ref : ct.enforcement_literal()) output.Set(PositiveRef(ref));
108 for (const int var : ct.interval().start().vars()) output.Set(var);
109 for (const int var : ct.interval().size().vars()) output.Set(var);
110 for (const int var : ct.interval().end().vars()) output.Set(var);
111}
112inline void RemoveVariablesFromInterval(const CpModelProto& model_proto,
113 int index, Bitset64<int>& output) {
114 const ConstraintProto& ct = model_proto.constraints(index);
115 for (const int ref : ct.enforcement_literal()) output.Clear(PositiveRef(ref));
116 for (const int var : ct.interval().start().vars()) output.Clear(var);
117 for (const int var : ct.interval().size().vars()) output.Clear(var);
118 for (const int var : ct.interval().end().vars()) output.Clear(var);
119}
120
121// Returns true if a proto.domain() contain the given value.
122// The domain is expected to be encoded as a sorted disjoint interval list.
123template <typename ProtoWithDomain>
124bool DomainInProtoContains(const ProtoWithDomain& proto, int64_t value) {
125 for (int i = 0; i < proto.domain_size(); i += 2) {
126 if (value >= proto.domain(i) && value <= proto.domain(i + 1)) return true;
127 }
128 return false;
129}
130
131// Serializes a Domain into the domain field of a proto.
132template <typename ProtoWithDomain>
133void FillDomainInProto(const Domain& domain, ProtoWithDomain* proto) {
134 proto->clear_domain();
135 proto->mutable_domain()->Reserve(domain.NumIntervals());
136 for (const ClosedInterval& interval : domain) {
137 proto->add_domain(interval.start);
138 proto->add_domain(interval.end);
139 }
140}
141
142// Reads a Domain from the domain field of a proto.
143template <typename ProtoWithDomain>
144Domain ReadDomainFromProto(const ProtoWithDomain& proto) {
145#if defined(__PORTABLE_PLATFORM__)
147 {proto.domain().begin(), proto.domain().end()});
148#else
149 return Domain::FromFlatSpanOfIntervals(proto.domain());
150#endif
151}
152
153// Returns the list of values in a given domain.
154// This will fail if the domain contains more than one millions values.
155//
156// TODO(user): work directly on the Domain class instead.
157template <typename ProtoWithDomain>
158std::vector<int64_t> AllValuesInDomain(const ProtoWithDomain& proto) {
159 std::vector<int64_t> result;
160 for (int i = 0; i < proto.domain_size(); i += 2) {
161 for (int64_t v = proto.domain(i); v <= proto.domain(i + 1); ++v) {
162 CHECK_LE(result.size(), 1e6);
163 result.push_back(v);
164 }
165 }
166 return result;
167}
168
169// Scales back a objective value to a double value from the original model.
170inline double ScaleObjectiveValue(const CpObjectiveProto& proto,
171 int64_t value) {
172 double result = static_cast<double>(value);
173 if (value == std::numeric_limits<int64_t>::min())
174 result = -std::numeric_limits<double>::infinity();
175 if (value == std::numeric_limits<int64_t>::max())
176 result = std::numeric_limits<double>::infinity();
177 result += proto.offset();
178 if (proto.scaling_factor() == 0) return result;
179 return proto.scaling_factor() * result;
180}
181
182// Similar to ScaleObjectiveValue() but uses the integer version.
183inline int64_t ScaleInnerObjectiveValue(const CpObjectiveProto& proto,
184 int64_t value) {
185 if (proto.integer_scaling_factor() == 0) {
186 return value + proto.integer_before_offset();
187 }
188 return (value + proto.integer_before_offset()) *
189 proto.integer_scaling_factor() +
190 proto.integer_after_offset();
191}
192
193// Removes the objective scaling and offset from the given value.
194inline double UnscaleObjectiveValue(const CpObjectiveProto& proto,
195 double value) {
196 double result = value;
197 if (proto.scaling_factor() != 0) {
198 result /= proto.scaling_factor();
199 }
200 return result - proto.offset();
201}
202
203// Computes the "inner" objective of a response that contains a solution.
204// This is the objective without offset and scaling. Call ScaleObjectiveValue()
205// to get the user facing objective.
206int64_t ComputeInnerObjective(const CpObjectiveProto& objective,
207 absl::Span<const int64_t> solution);
208
209// Returns true if a linear expression can be reduced to a single ref.
210bool ExpressionContainsSingleRef(const LinearExpressionProto& expr);
211
212// Checks if the expression is affine or constant.
213bool ExpressionIsAffine(const LinearExpressionProto& expr);
214
215// Returns the reference the expression can be reduced to. It will DCHECK that
216// ExpressionContainsSingleRef(expr) is true.
217int GetSingleRefFromExpression(const LinearExpressionProto& expr);
218
219// Evaluates an affine expression at the given value.
220inline int64_t AffineExpressionValueAt(const LinearExpressionProto& expr,
221 int64_t value) {
222 CHECK_EQ(1, expr.vars_size());
223 return expr.offset() + value * expr.coeffs(0);
224}
225
226// Returns the value of the inner variable of an affine expression from the
227// value of the expression. It will DCHECK that the result is valid.
228inline int64_t GetInnerVarValue(const LinearExpressionProto& expr,
229 int64_t value) {
230 DCHECK_EQ(expr.vars_size(), 1);
231 const int64_t var_value = (value - expr.offset()) / expr.coeffs(0);
232 DCHECK_EQ(value, var_value * expr.coeffs(0) + expr.offset());
233 return var_value;
234}
235
236// Returns true if the expression is a * var + b.
237inline bool AffineExpressionContainsVar(const LinearExpressionProto& expr,
238 int var) {
239 return expr.vars_size() == 1 && expr.vars(0) == var;
240}
241
242// Adds a linear expression proto to a linear constraint in place.
243//
244// Important: The domain must already be set, otherwise the offset will be lost.
245// We also do not do any duplicate detection, so the constraint might need
246// presolving afterwards.
247void AddLinearExpressionToLinearConstraint(const LinearExpressionProto& expr,
248 int64_t coefficient,
249 LinearConstraintProto* linear);
250
251// Same as above, but with a single term (lit, coeff). Note that lit can be
252// negative. The offset is relative to the linear expression (and should be
253// negated when added to the rhs of the linear constraint proto).
254void AddWeightedLiteralToLinearConstraint(int lit, int64_t coeff,
255 LinearConstraintProto* linear,
256 int64_t* offset);
257
258// Same method, but returns if the addition was possible without overflowing.
260 const LinearExpressionProto& expr, int64_t coefficient,
261 LinearConstraintProto* linear);
262
263// Returns true iff a == b * b_scaling.
264bool LinearExpressionProtosAreEqual(const LinearExpressionProto& a,
265 const LinearExpressionProto& b,
266 int64_t b_scaling = 1);
267
268// Returns true if there exactly one variable appearing in all the expressions.
269template <class ExpressionList>
270bool ExpressionsContainsOnlyOneVar(const ExpressionList& exprs) {
271 int unique_var = -1;
272 for (const LinearExpressionProto& expr : exprs) {
273 for (const int var : expr.vars()) {
274 CHECK(RefIsPositive(var));
275 if (unique_var == -1) {
276 unique_var = var;
277 } else if (var != unique_var) {
278 return false;
279 }
280 }
281 }
282 return unique_var != -1;
283}
284
285// Default seed for fingerprints.
286constexpr uint64_t kDefaultFingerprintSeed = 0xa5b85c5e198ed849;
287
288template <class T>
290 const google::protobuf::RepeatedField<T>& sequence, uint64_t seed) {
291 if (sequence.empty()) return seed;
292 return fasthash64(reinterpret_cast<const char*>(sequence.data()),
293 sequence.size() * sizeof(T), seed);
294}
295
296template <class T>
297inline uint64_t FingerprintSingleField(const T& field, uint64_t seed) {
298 return fasthash64(reinterpret_cast<const char*>(&field), sizeof(T), seed);
299}
300
301// Returns a stable fingerprint of a linear expression.
302uint64_t FingerprintExpression(const LinearExpressionProto& lin, uint64_t seed);
303
304// Returns a stable fingerprint of a model.
305uint64_t FingerprintModel(const CpModelProto& model,
306 uint64_t seed = kDefaultFingerprintSeed);
307
308#if !defined(__PORTABLE_PLATFORM__)
309
310// We register a few custom printers to display variables and linear
311// expression on one line. This is especially nice for variables where it is
312// easy to recover their indices from the line number now.
313//
314// ex:
315//
316// variables { domain: [0, 1] }
317// variables { domain: [0, 1] }
318// variables { domain: [0, 1] }
319//
320// constraints {
321// linear {
322// vars: [0, 1, 2]
323// coeffs: [2, 4, 5 ]
324// domain: [11, 11]
325// }
326// }
327void SetupTextFormatPrinter(google::protobuf::TextFormat::Printer* printer);
328#endif // !defined(__PORTABLE_PLATFORM__)
329
330template <class M>
331bool WriteModelProtoToFile(const M& proto, absl::string_view filename) {
332#if defined(__PORTABLE_PLATFORM__)
333 return false;
334#else // !defined(__PORTABLE_PLATFORM__)
335 if (absl::EndsWith(filename, "txt") ||
336 absl::EndsWith(filename, "textproto")) {
337 std::string proto_string;
338 google::protobuf::TextFormat::Printer printer;
339 SetupTextFormatPrinter(&printer);
340 printer.PrintToString(proto, &proto_string);
341 return file::SetContents(filename, proto_string, file::Defaults()).ok();
342 } else {
343 return file::SetBinaryProto(filename, proto, file::Defaults()).ok();
344 }
345#endif // !defined(__PORTABLE_PLATFORM__)
346}
347
348// hashing support.
349//
350// Currently limited to a few inner types of ConstraintProto.
351inline bool operator==(const BoolArgumentProto& lhs,
352 const BoolArgumentProto& rhs) {
353 if (absl::MakeConstSpan(lhs.literals()) !=
354 absl::MakeConstSpan(rhs.literals())) {
355 return false;
356 }
357 if (lhs.literals_size() != rhs.literals_size()) return false;
358 for (int i = 0; i < lhs.literals_size(); ++i) {
359 if (lhs.literals(i) != rhs.literals(i)) return false;
360 }
361 return true;
362}
363
364template <typename H>
365H AbslHashValue(H h, const BoolArgumentProto& m) {
366 for (const int lit : m.literals()) {
367 h = H::combine(std::move(h), lit);
368 }
369 return h;
370}
371
372inline bool operator==(const LinearConstraintProto& lhs,
373 const LinearConstraintProto& rhs) {
374 if (absl::MakeConstSpan(lhs.vars()) != absl::MakeConstSpan(rhs.vars())) {
375 return false;
376 }
377 if (absl::MakeConstSpan(lhs.coeffs()) != absl::MakeConstSpan(rhs.coeffs())) {
378 return false;
379 }
380 if (absl::MakeConstSpan(lhs.domain()) != absl::MakeConstSpan(rhs.domain())) {
381 return false;
382 }
383 return true;
384}
385
386template <typename H>
387H AbslHashValue(H h, const LinearConstraintProto& m) {
388 for (const int var : m.vars()) {
389 h = H::combine(std::move(h), var);
390 }
391 for (const int64_t coeff : m.coeffs()) {
392 h = H::combine(std::move(h), coeff);
393 }
394 for (const int64_t bound : m.domain()) {
395 h = H::combine(std::move(h), bound);
396 }
397 return h;
398}
399
400bool ConvertCpModelProtoToCnf(const CpModelProto& cp_mode, std::string* out);
401
402// We assume delta >= 0 and we only use the low bit of delta.
403int CombineSeed(int base_seed, int64_t delta);
404
405} // namespace sat
406} // namespace operations_research
407
408#endif // OR_TOOLS_SAT_CP_MODEL_UTILS_H_
void Clear(IndexType i)
Sets the bit at position i to 0.
Definition bitset.h:506
void Set(IndexType i)
Sets the bit at position i to 1.
Definition bitset.h:544
static Domain FromFlatIntervals(const std::vector< int64_t > &flat_intervals)
static Domain FromFlatSpanOfIntervals(absl::Span< const int64_t > flat_intervals)
absl::Status SetBinaryProto(absl::string_view filename, const google::protobuf::Message &proto, Options options)
Definition file.cc:360
absl::Status SetContents(absl::string_view filename, absl::string_view contents, Options options)
Definition file.cc:242
Options Defaults()
Definition file.h:107
void SetToNegatedLinearExpression(const LinearExpressionProto &input_expr, LinearExpressionProto *output_negated_expr)
Fills the target as negated ref.
constexpr uint64_t kDefaultFingerprintSeed
Default seed for fingerprints.
uint64_t FingerprintRepeatedField(const google::protobuf::RepeatedField< T > &sequence, uint64_t seed)
void RemoveVariablesFromInterval(const CpModelProto &model_proto, int index, Bitset64< int > &output)
double UnscaleObjectiveValue(const CpObjectiveProto &proto, double value)
Removes the objective scaling and offset from the given value.
int64_t ComputeInnerObjective(const CpObjectiveProto &objective, absl::Span< const int64_t > solution)
bool operator==(const BoolArgumentProto &lhs, const BoolArgumentProto &rhs)
bool HasEnforcementLiteral(const ConstraintProto &ct)
Small utility functions to deal with half-reified constraints.
int CombineSeed(int base_seed, int64_t delta)
We assume delta >= 0 and we only use the low bit of delta.
bool WriteModelProtoToFile(const M &proto, absl::string_view filename)
bool DomainInProtoContains(const ProtoWithDomain &proto, int64_t value)
void ApplyToAllIntervalIndices(const std::function< void(int *)> &f, ConstraintProto *ct)
bool SafeAddLinearExpressionToLinearConstraint(const LinearExpressionProto &expr, int64_t coefficient, LinearConstraintProto *linear)
Same method, but returns if the addition was possible without overflowing.
int64_t GetInnerVarValue(const LinearExpressionProto &expr, int64_t value)
uint64_t FingerprintSingleField(const T &field, uint64_t seed)
double ScaleObjectiveValue(const CpObjectiveProto &proto, int64_t value)
Scales back a objective value to a double value from the original model.
bool ConvertCpModelProtoToCnf(const CpModelProto &cp_model, std::string *out)
uint64_t FingerprintExpression(const LinearExpressionProto &lin, uint64_t seed)
Returns a stable fingerprint of a linear expression.
uint64_t FingerprintModel(const CpModelProto &model, uint64_t seed)
Returns a stable fingerprint of a model.
bool ExpressionIsAffine(const LinearExpressionProto &expr)
Checks if the expression is affine or constant.
std::vector< int > UsedVariables(const ConstraintProto &ct)
std::vector< int > UsedIntervals(const ConstraintProto &ct)
Returns the sorted list of interval used by a constraint.
void FillDomainInProto(const Domain &domain, ProtoWithDomain *proto)
Serializes a Domain into the domain field of a proto.
int64_t AffineExpressionValueAt(const LinearExpressionProto &expr, int64_t value)
Evaluates an affine expression at the given value.
H AbslHashValue(H h, const IntVar &i)
– ABSL HASHING SUPPORT --------------------------------------------------—
Definition cp_model.h:515
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
Reads a Domain from the domain field of a proto.
bool ExpressionsContainsOnlyOneVar(const ExpressionList &exprs)
Returns true if there exactly one variable appearing in all the expressions.
void SetupTextFormatPrinter(google::protobuf::TextFormat::Printer *printer)
absl::string_view ConstraintCaseName(ConstraintProto::ConstraintCase constraint_case)
bool ExpressionContainsSingleRef(const LinearExpressionProto &expr)
Returns true if a linear expression can be reduced to a single ref.
int64_t LinearExpressionGcd(const LinearExpressionProto &expr, int64_t gcd)
void ApplyToAllLiteralIndices(const std::function< void(int *)> &f, ConstraintProto *ct)
void DivideLinearExpression(int64_t divisor, LinearExpressionProto *expr)
void AddLinearExpressionToLinearConstraint(const LinearExpressionProto &expr, int64_t coefficient, LinearConstraintProto *linear)
int GetSingleRefFromExpression(const LinearExpressionProto &expr)
int64_t ScaleInnerObjectiveValue(const CpObjectiveProto &proto, int64_t value)
Similar to ScaleObjectiveValue() but uses the integer version.
int EnforcementLiteral(const ConstraintProto &ct)
int NegatedRef(int ref)
Small utility functions to deal with negative variable/literal references.
void InsertVariablesFromInterval(const CpModelProto &model_proto, int index, Bitset64< int > &output)
Insert/Remove variables from an interval constraint into a bitset.
bool LinearExpressionProtosAreEqual(const LinearExpressionProto &a, const LinearExpressionProto &b, int64_t b_scaling)
Returns true iff a == b * b_scaling.
IndexReferences GetReferencesUsedByConstraint(const ConstraintProto &ct)
void ApplyToAllVariableIndices(const std::function< void(int *)> &f, ConstraintProto *ct)
void AddWeightedLiteralToLinearConstraint(int lit, int64_t coeff, LinearConstraintProto *linear, int64_t *offset)
bool AffineExpressionContainsVar(const LinearExpressionProto &expr, int var)
Returns true if the expression is a * var + b.
std::vector< int64_t > AllValuesInDomain(const ProtoWithDomain &proto)
In SWIG mode, we don't want anything besides these top-level includes.
Select next search node to expand Select next item_i to add this new search node to the search Generate a new search node where item_i is not in the knapsack Check validity of this new partial solution(using propagators) - If valid
uint64_t fasthash64(const void *buf, size_t len, uint64_t seed)
Definition hash.cc:36