Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
model.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 ORTOOLS_FLATZINC_MODEL_H_
15#define ORTOOLS_FLATZINC_MODEL_H_
16
17#include <cstdint>
18#include <map>
19#include <string>
20#include <utility>
21#include <vector>
22
23#include "absl/container/flat_hash_map.h"
24#include "absl/strings/string_view.h"
25#include "absl/types/span.h"
27
28namespace operations_research {
29namespace fz {
30
31struct Constraint;
32class Model;
33
34// A domain represents the possible values of a variable, and its type
35// (which carries display information, i.e. a Boolean will be displayed
36// differently than an integer with domain {0, 1}).
37// It can be:
38// - an explicit list of all possible values, in which case is_interval is
39// false. If the list is empty, then the domain is empty.
40// - an interval, in which case is_interval is true and values.size() == 2,
41// and the interval is [values[0], values[1]].
42// - all integers, in which case values is empty, and is_interval is true.
43// Note that semi-infinite intervals aren't supported.
44// - a Boolean domain({ 0, 1 } with Boolean display tag).
45// TODO(user): Rework domains, all int64_t should be kintmin..kint64max.
46// It is a bit tricky though as we must take care of overflows.
47// If is_a_set is true, then this domain has a set semantics. For a set
48// variable, any subset of the initial set of values is a valid assignment,
49// instead of exactly one value.
50struct Domain {
51 // The values will be sorted and duplicate values will be removed.
52 static Domain IntegerList(std::vector<int64_t> values);
53 static Domain AllInt64();
54 static Domain IntegerValue(int64_t value);
55 static Domain Interval(int64_t included_min, int64_t included_max);
56 static Domain Boolean();
57 static Domain SetOfIntegerList(std::vector<int64_t> values);
58 static Domain SetOfAllInt64();
59 static Domain SetOfIntegerValue(int64_t value);
60 static Domain SetOfInterval(int64_t included_min, int64_t included_max);
61 static Domain SetOfBoolean();
62 static Domain EmptyDomain();
63 static Domain AllFloats();
64 static Domain FloatValue(double value);
65 static Domain FloatInterval(double lb, double ub);
66 // TODO(user): Do we need SetOfFloats() ?
67
68 bool HasOneValue() const;
69 bool empty() const;
70
71 // Returns the min of the domain.
72 int64_t Min() const;
73
74 // Returns the max of the domain.
75 int64_t Max() const;
76
77 // Returns the value of the domain. HasOneValue() must return true.
78 int64_t Value() const;
79
80 // Returns true if the domain is [kint64min..kint64max]
81 bool IsAllInt64() const;
82
83 // Various inclusion tests on a domain.
84 bool Contains(int64_t value) const;
85 bool OverlapsIntList(const std::vector<int64_t>& vec) const;
86 bool OverlapsIntInterval(int64_t lb, int64_t ub) const;
87 bool OverlapsDomain(const Domain& other) const;
88
89 // All the following modifiers change the internal representation
90 // list to interval or interval to list.
91 bool IntersectWithSingleton(int64_t value);
92 bool IntersectWithDomain(const Domain& domain);
93 bool IntersectWithInterval(int64_t interval_min, int64_t interval_max);
94 bool IntersectWithListOfIntegers(absl::Span<const int64_t> integers);
95 bool IntersectWithFloatDomain(const Domain& domain);
96
97 // Returns true iff the value did belong to the domain, and was removed.
98 // Try to remove the value. It returns true if it was actually removed.
99 // If the value is inside a large interval, then it will not be removed.
100 bool RemoveValue(int64_t value);
101 // Sets the empty float domain. Returns true.
102 bool SetEmptyFloatDomain();
103 std::string DebugString() const;
104
105 // These should never be modified from outside the class.
106 std::vector<int64_t> values;
107 bool is_interval = false;
108 bool display_as_boolean = false;
109 // Indicates if the domain was created as a set domain.
110 bool is_a_set = false;
111 bool is_fixed_set = false;
112 // Float domain.
113 bool is_float = false;
114 std::vector<double> float_values;
115};
116
117// An int var is a name with a domain of possible values, along with
118// some tags. Typically, a Variable is on the heap, and owned by the
119// global Model object.
120struct Variable {
121 // This method tries to unify two variables. This can happen during the
122 // parsing of the model or during presolve. This is possible if at least one
123 // of the two variable is not the target of a constraint. (otherwise it
124 // returns false).
125 // The semantic of the merge is the following:
126 // - the resulting domain is the intersection of the two domains.
127 // - if one variable is not temporary, the result is not temporary.
128 // - if one variable is temporary, the name is the name of the other
129 // variable. If both variables are temporary or both variables are not
130 // temporary, the name is chosen arbitrarily between the two names.
131 bool Merge(absl::string_view other_name, const Domain& other_domain,
132 bool other_temporary);
133
134 std::string DebugString() const;
135
136 std::string name;
138 // Indicates if the variable is a temporary variable created when flattening
139 // the model. For instance, if you write x == y * z + y, then it will be
140 // expanded into y * z == t and x = t + y. And t will be a temporary variable.
141 bool temporary : 1;
142 // Indicates if the variable should be created at all. A temporary variable
143 // can be unreachable in the active model if nobody uses it. In that case,
144 // there is no need to create it.
145 bool active : 1;
146
147 private:
148 friend class Model;
149
150 Variable(absl::string_view name_, const Domain& domain_, bool temporary_);
151};
152
153// An argument is either an integer value, an integer domain, a
154// reference to a variable, or an array of variable references.
155struct Argument {
168
169 static Argument IntegerValue(int64_t value);
170 static Argument Interval(int64_t imin, int64_t imax);
171 static Argument IntegerList(std::vector<int64_t> values);
172 static Argument DomainList(std::vector<Domain> domains);
173 static Argument FloatValue(double value);
174 static Argument FloatInterval(double lb, double ub);
175 static Argument FloatList(std::vector<double> floats);
176 static Argument VarRef(Variable* var);
177 static Argument VarRefArray(std::vector<Variable*> vars);
178 static Argument VoidArgument();
179 static Argument FromDomain(const Domain& domain);
180
181 std::string DebugString() const;
182
183 // Returns true if the argument is a variable.
184 bool IsVariable() const;
185 // Returns true if the argument has only one value (integer value, integer
186 // list of size 1, interval of size 1, or variable with a singleton domain).
187 bool HasOneValue() const;
188 // Returns the value of the argument. Does DCHECK(HasOneValue()).
189 int64_t Value() const;
190 // Returns true if it an integer list, or an array of integer
191 // variables (or domain) each having only one value.
192 bool IsArrayOfValues() const;
193 // Returns true if the argument is an integer value, an integer
194 // list, or an interval, and it contains the given value.
195 // It will check that the type is actually one of the above.
196 bool Contains(int64_t value) const;
197 // Returns the value of the pos-th element.
198 int64_t ValueAt(int pos) const;
199 // Returns the variable inside the argument if the type is VAR_REF,
200 // or nullptr otherwise.
201 Variable* Var() const;
202 // Returns the variable at position pos inside the argument if the type is
203 // VAR_REF_ARRAY or nullptr otherwise.
204 Variable* VarAt(int pos) const;
205 // Returns true is the pos-th argument is fixed.
206 bool HasOneValueAt(int pos) const;
207 // Returns the number of object in the argument.
208 int Size() const;
209
211 std::vector<int64_t> values;
212 std::vector<Variable*> variables;
213 std::vector<Domain> domains;
214 std::vector<double> floats;
215};
216
217// A constraint has a type, some arguments, and a few tags. Typically, a
218// Constraint is on the heap, and owned by the global Model object.
220 Constraint(absl::string_view t, std::vector<Argument> args,
221 bool strong_propag, bool sym, bool redundant)
222 : type(t),
223 arguments(std::move(args)),
224 strong_propagation(strong_propag),
225 active(true),
227 is_redundant(redundant) {}
228
229 std::string DebugString() const;
230
231 // Helpers to be used during presolve.
232 void MarkAsInactive();
233 // Helper method to remove one argument.
234 void RemoveArg(int arg_pos);
235 // Set as a False constraint.
236 void SetAsFalse();
237
238 // The flatzinc type of the constraint (i.e. "int_eq" for integer equality)
239 // stored as a string.
240 std::string type;
241 std::vector<Argument> arguments;
242 // Is true if the constraint should use the strongest level of propagation.
243 // This is a hint in the model. For instance, in the AllDifferent constraint,
244 // there are different algorithms to propagate with different pruning/speed
245 // ratios. When strong_propagation is true, one should use, if possible, the
246 // algorithm with the strongest pruning.
248 // Indicates if the constraint is active. Presolve can make it inactive by
249 // propagating it, or by regrouping it. Once a constraint is inactive, it is
250 // logically removed from the model, it is not extracted, and it is ignored by
251 // presolve.
252 bool active : 1;
253
254 // Indicates if the constraint is a symmetric breaking constraint.
256
257 // Indicates if the constraint is a redundant constraint.
258 bool is_redundant : 1;
259};
260
261// An annotation is a set of information. It has two use cases. One during
262// parsing to store intermediate information on model objects (i.e. the defines
263// part of a constraint). The other use case is to store all search
264// declarations. This persists after model parsing.
277
278 static Annotation Empty();
279 static Annotation AnnotationList(std::vector<Annotation> list);
280 static Annotation Identifier(absl::string_view id);
281 static Annotation FunctionCallWithArguments(absl::string_view id,
282 std::vector<Annotation> args);
283 static Annotation FunctionCall(absl::string_view id);
284 static Annotation Interval(int64_t interval_min, int64_t interval_max);
285 static Annotation IntegerValue(int64_t value);
286 static Annotation IntegerList(const std::vector<int64_t>& values);
287 static Annotation VarRef(Variable* var);
288 static Annotation VarRefArray(std::vector<Variable*> variables);
289 static Annotation String(absl::string_view str);
290
291 std::string DebugString() const;
292 bool IsFunctionCallWithIdentifier(absl::string_view identifier) const {
293 return type == FUNCTION_CALL && id == identifier;
294 }
295 // Copy all the variable references contained in this annotation (and its
296 // children). Depending on the type of this annotation, there can be zero,
297 // one, or several.
298 void AppendAllVariables(std::vector<Variable*>* vars) const;
299
303 std::string id;
304 std::vector<Annotation> annotations;
305 std::vector<Variable*> variables;
306 std::vector<int64_t> values;
307 std::string string_value;
308};
309
310// Information on what should be displayed when a solution is found.
311// It follows the flatzinc specification (www.minizinc.org).
313 struct Bounds {
314 Bounds(int64_t min_value_, int64_t max_value_)
315 : min_value(min_value_), max_value(max_value_) {}
316 std::string DebugString() const;
317 int64_t min_value;
318 int64_t max_value;
319 };
320
321 // Will output: name = <variable value>.
322 static SolutionOutputSpecs SingleVariable(absl::string_view name,
324 bool display_as_boolean);
325 // Will output (for example):
326 // name = array2d(min1..max1, min2..max2, [list of variable values])
327 // for a 2d array (bounds.size() == 2).
329 absl::string_view name, std::vector<Bounds> bounds,
330 std::vector<Variable*> flat_variables, bool display_as_boolean);
331 // Empty output.
333
334 std::string DebugString() const;
335
336 std::string name;
338 std::vector<Variable*> flat_variables;
339 // These are the starts and ends of intervals for displaying (potentially
340 // multi-dimensional) arrays.
341 std::vector<Bounds> bounds;
343};
344
345class Model {
346 public:
347 explicit Model(absl::string_view name)
348 : name_(name), objective_(nullptr), maximize_(true) {}
349 ~Model();
350
351 // ----- Builder methods -----
352
353 // The objects returned by AddVariable(), AddConstant(), and AddConstraint()
354 // are owned by the model and will remain live for its lifetime.
355 Variable* AddVariable(absl::string_view name, const Domain& domain,
356 bool defined, bool set_is_fixed = false);
357 Variable* AddConstant(int64_t value);
358 Variable* AddFloatConstant(double value);
359 // Creates and add a constraint to the model.
360 void AddConstraint(absl::string_view id, std::vector<Argument> arguments,
361 bool is_domain, bool symmetry, bool redundant);
362 void AddConstraint(absl::string_view id, std::vector<Argument> arguments);
364
365 // Set the search annotations and the objective: either simply satisfy the
366 // problem, or minimize or maximize the given variable (which must have been
367 // added with AddVariable() already).
368 void Satisfy(std::vector<Annotation> search_annotations);
369 void Minimize(Variable* obj, std::vector<Annotation> search_annotations);
370 void Maximize(Variable* obj, std::vector<Annotation> search_annotations);
371
372 bool IsInconsistent() const;
373
374 // ----- Accessors and mutators -----
375
376 const std::vector<Variable*>& variables() const { return variables_; }
377 const std::vector<Constraint*>& constraints() const { return constraints_; }
378 const std::vector<Annotation>& search_annotations() const {
379 return search_annotations_;
380 }
381 const std::vector<SolutionOutputSpecs>& output() const { return output_; }
382 bool maximize() const { return maximize_; }
383 Variable* objective() const { return objective_; }
384 const std::vector<Variable*>& float_objective_variables() const {
385 return float_objective_variables_;
386 }
387 const std::vector<double>& float_objective_coefficients() const {
388 return float_objective_coefficients_;
389 }
390 double float_objective_offset() const { return float_objective_offset_; }
391 void SetObjective(Variable* obj) { objective_ = obj; }
392 void ClearObjective() { objective_ = nullptr; }
393 void AddFloatingPointObjectiveTerm(Variable* var, double coeff) {
394 float_objective_variables_.push_back(var);
395 float_objective_coefficients_.push_back(coeff);
396 }
398 float_objective_offset_ = offset;
399 }
400
401 // Services.
402 std::string DebugString() const;
403
404 const std::string& name() const { return name_; }
405
406 private:
407 const std::string name_;
408 // owned.
409 // TODO(user): use unique_ptr
410 std::vector<Variable*> variables_;
411 // owned.
412 // TODO(user): use unique_ptr
413 std::vector<Constraint*> constraints_;
414 // The objective variable (it belongs to variables_).
415 Variable* objective_;
416 bool maximize_;
417 std::vector<Variable*> float_objective_variables_;
418 std::vector<double> float_objective_coefficients_;
419 double float_objective_offset_ = 0.0;
420 // All search annotations are stored as a vector of Annotation.
421 std::vector<Annotation> search_annotations_;
422 std::vector<SolutionOutputSpecs> output_;
423};
424
425// Stand-alone statistics class on the model.
426// TODO(user): Clean up API to pass a Model* in argument.
428 public:
429 explicit ModelStatistics(const Model& model, SolverLogger* logger)
430 : model_(model), logger_(logger) {}
432 return constraints_per_variables_[var].size();
433 }
434 void BuildStatistics();
435 void PrintStatistics() const;
436
437 private:
438 const Model& model_;
439 SolverLogger* logger_;
440 std::map<std::string, std::vector<Constraint*>> constraints_per_type_;
441 absl::flat_hash_map<const Variable*, std::vector<Constraint*>>
442 constraints_per_variables_;
443};
444
445// Helper method to flatten Search annotations.
446void FlattenAnnotations(const Annotation& ann, std::vector<Annotation>* out);
447
448} // namespace fz
449} // namespace operations_research
450
451#endif // ORTOOLS_FLATZINC_MODEL_H_
Model(absl::string_view name)
Definition model.h:347
int NumVariableOccurrences(Variable *var)
Definition model.h:431
ModelStatistics(const Model &model, SolverLogger *logger)
Definition model.h:429
void AddConstraint(absl::string_view id, std::vector< Argument > arguments, bool is_domain, bool symmetry, bool redundant)
Definition model.cc:1046
const std::vector< double > & float_objective_coefficients() const
Definition model.h:387
void AddFloatingPointObjectiveTerm(Variable *var, double coeff)
Definition model.h:393
const std::vector< Variable * > & float_objective_variables() const
Definition model.h:384
Model(absl::string_view name)
Definition model.h:347
const std::vector< Constraint * > & constraints() const
Definition model.h:377
void SetObjective(Variable *obj)
Definition model.h:391
void SetFloatingPointObjectiveOffset(double offset)
Definition model.h:397
const std::vector< SolutionOutputSpecs > & output() const
Definition model.h:381
const std::vector< Variable * > & variables() const
Definition model.h:376
Variable * AddVariable(absl::string_view name, const Domain &domain, bool defined, bool set_is_fixed=false)
Definition model.cc:1020
Variable * AddFloatConstant(double value)
Definition model.cc:1039
std::string DebugString() const
Definition model.cc:1081
void AddOutput(SolutionOutputSpecs output)
Definition model.cc:1058
void Maximize(Variable *obj, std::vector< Annotation > search_annotations)
Definition model.cc:1074
double float_objective_offset() const
Definition model.h:390
void Satisfy(std::vector< Annotation > search_annotations)
Definition model.cc:1062
const std::string & name() const
Definition model.h:404
const std::vector< Annotation > & search_annotations() const
Definition model.h:378
Variable * objective() const
Definition model.h:383
void Minimize(Variable *obj, std::vector< Annotation > search_annotations)
Definition model.cc:1067
Variable * AddConstant(int64_t value)
Definition model.cc:1032
void FlattenAnnotations(const Annotation &ann, std::vector< Annotation > *out)
Definition model.cc:1221
OR-Tools root namespace.
STL namespace.
Constraint(absl::string_view t, std::vector< Argument > args, bool strong_propag, bool sym, bool redundant)
Definition model.h:220
std::vector< int64_t > values
Definition model.h:106
static Annotation String(absl::string_view str)
Definition model.cc:920
static Annotation FunctionCall(absl::string_view id)
Definition model.cc:870
void AppendAllVariables(std::vector< Variable * > *vars) const
Definition model.cc:929
static Annotation FunctionCallWithArguments(absl::string_view id, std::vector< Annotation > args)
Definition model.cc:859
static Annotation Empty()
Definition model.cc:833
static Annotation AnnotationList(std::vector< Annotation > list)
Definition model.cc:841
static Annotation IntegerList(const std::vector< int64_t > &values)
Definition model.cc:894
static Annotation VarRefArray(std::vector< Variable * > variables)
Definition model.cc:911
static Annotation Identifier(absl::string_view id)
Definition model.cc:850
std::vector< Variable * > variables
Definition model.h:305
std::vector< int64_t > values
Definition model.h:306
bool IsFunctionCallWithIdentifier(absl::string_view identifier) const
Definition model.h:292
static Annotation VarRef(Variable *var)
Definition model.cc:902
static Annotation IntegerValue(int64_t value)
Definition model.cc:887
static Annotation Interval(int64_t interval_min, int64_t interval_max)
Definition model.cc:879
std::vector< Annotation > annotations
Definition model.h:304
std::string DebugString() const
Definition model.cc:938
std::vector< Variable * > variables
Definition model.h:212
static Argument FloatList(std::vector< double > floats)
Definition model.cc:582
static Argument FloatValue(double value)
Definition model.cc:567
std::vector< Domain > domains
Definition model.h:213
bool HasOneValueAt(int pos) const
Definition model.cc:721
Variable * VarAt(int pos) const
Definition model.cc:747
std::string DebugString() const
Definition model.cc:589
static Argument VoidArgument()
Definition model.cc:548
static Argument IntegerValue(int64_t value)
Definition model.cc:505
int64_t ValueAt(int pos) const
Definition model.cc:699
static Argument Interval(int64_t imin, int64_t imax)
Definition model.cc:512
static Argument FromDomain(const Domain &domain)
Definition model.cc:554
static Argument IntegerList(std::vector< int64_t > values)
Definition model.cc:520
static Argument VarRef(Variable *var)
Definition model.cc:534
static Argument FloatInterval(double lb, double ub)
Definition model.cc:574
std::vector< double > floats
Definition model.h:214
bool Contains(int64_t value) const
Definition model.cc:684
static Argument DomainList(std::vector< Domain > domains)
Definition model.cc:527
static Argument VarRefArray(std::vector< Variable * > vars)
Definition model.cc:541
std::vector< int64_t > values
Definition model.h:211
std::string DebugString() const
Definition model.cc:805
Constraint(absl::string_view t, std::vector< Argument > args, bool strong_propag, bool sym, bool redundant)
Definition model.h:220
std::vector< Argument > arguments
Definition model.h:241
static Domain Boolean()
Definition model.cc:67
static Domain AllFloats()
Definition model.cc:107
bool IntersectWithSingleton(int64_t value)
Definition model.cc:155
static Domain IntegerList(std::vector< int64_t > values)
Definition model.cc:40
bool OverlapsDomain(const Domain &other) const
Definition model.cc:425
static Domain IntegerValue(int64_t value)
Definition model.cc:53
std::string DebugString() const
Definition model.cc:468
static Domain FloatValue(double value)
Definition model.cc:122
bool IntersectWithInterval(int64_t interval_min, int64_t interval_max)
Definition model.cc:159
bool IntersectWithDomain(const Domain &domain)
Definition model.cc:129
static Domain EmptyDomain()
Definition model.cc:105
bool IntersectWithFloatDomain(const Domain &domain)
Definition model.cc:254
bool RemoveValue(int64_t value)
Definition model.cc:437
static Domain FloatInterval(double lb, double ub)
Definition model.cc:114
std::vector< int64_t > values
Definition model.h:106
static Domain SetOfBoolean()
Definition model.cc:99
static Domain Interval(int64_t included_min, int64_t included_max)
Definition model.cc:59
static Domain SetOfAllInt64()
Definition model.cc:81
static Domain SetOfInterval(int64_t included_min, int64_t included_max)
Definition model.cc:93
bool Contains(int64_t value) const
Definition model.cc:363
bool OverlapsIntInterval(int64_t lb, int64_t ub) const
Definition model.cc:411
std::vector< double > float_values
Definition model.h:114
static Domain SetOfIntegerList(std::vector< int64_t > values)
Definition model.cc:75
static Domain SetOfIntegerValue(int64_t value)
Definition model.cc:87
static Domain AllInt64()
Definition model.cc:47
bool IntersectWithListOfIntegers(absl::Span< const int64_t > integers)
Definition model.cc:207
bool OverlapsIntList(const std::vector< int64_t > &vec) const
Definition model.cc:387
Bounds(int64_t min_value_, int64_t max_value_)
Definition model.h:314
std::vector< Variable * > flat_variables
Definition model.h:338
static SolutionOutputSpecs MultiDimensionalArray(absl::string_view name, std::vector< Bounds > bounds, std::vector< Variable * > flat_variables, bool display_as_boolean)
Definition model.cc:984
static SolutionOutputSpecs VoidOutput()
Definition model.cc:996
static SolutionOutputSpecs SingleVariable(absl::string_view name, Variable *variable, bool display_as_boolean)
Definition model.cc:975
bool Merge(absl::string_view other_name, const Domain &other_domain, bool other_temporary)
Definition model.cc:783
std::string DebugString() const
Definition model.cc:793