OR-Tools  9.3
flatzinc/model.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_FLATZINC_MODEL_H_
15#define OR_TOOLS_FLATZINC_MODEL_H_
16
17#include <cstdint>
18#include <map>
19#include <string>
20
21#include "absl/container/flat_hash_map.h"
22#include "absl/strings/string_view.h"
28
29namespace operations_research {
30namespace fz {
31
32struct Constraint;
33class Model;
34
35// A domain represents the possible values of a variable, and its type
36// (which carries display information, i.e. a Boolean will be displayed
37// differently than an integer with domain {0, 1}).
38// It can be:
39// - an explicit list of all possible values, in which case is_interval is
40// false. If the list is empty, then the domain is empty.
41// - an interval, in which case is_interval is true and values.size() == 2,
42// and the interval is [values[0], values[1]].
43// - all integers, in which case values is empty, and is_interval is true.
44// Note that semi-infinite intervals aren't supported.
45// - a Boolean domain({ 0, 1 } with Boolean display tag).
46// TODO(user): Rework domains, all int64_t should be kintmin..kint64max.
47// It is a bit tricky though as we must take care of overflows.
48// If is_a_set is true, then this domain has a set semantics. For a set
49// variable, any subset of the initial set of values is a valid assignment,
50// instead of exactly one value.
51struct Domain {
52 // The values will be sorted and duplicate values will be removed.
53 static Domain IntegerList(std::vector<int64_t> values);
54 static Domain AllInt64();
55 static Domain IntegerValue(int64_t value);
56 static Domain Interval(int64_t included_min, int64_t included_max);
57 static Domain Boolean();
58 static Domain SetOfIntegerList(std::vector<int64_t> values);
59 static Domain SetOfAllInt64();
60 static Domain SetOfIntegerValue(int64_t value);
61 static Domain SetOfInterval(int64_t included_min, int64_t included_max);
62 static Domain SetOfBoolean();
63 static Domain EmptyDomain();
64 static Domain AllFloats();
65 static Domain FloatValue(double value);
66 static Domain FloatInterval(double lb, double ub);
67 // TODO(user): Do we need SetOfFloats() ?
68
69 bool HasOneValue() const;
70 bool empty() const;
71
72 // Returns the min of the domain.
73 int64_t Min() const;
74
75 // Returns the max of the domain.
76 int64_t Max() const;
77
78 // Returns the value of the domain. HasOneValue() must return true.
79 int64_t Value() const;
80
81 // Returns true if the domain is [kint64min..kint64max]
82 bool IsAllInt64() const;
83
84 // Various inclusion tests on a domain.
85 bool Contains(int64_t value) const;
86 bool OverlapsIntList(const std::vector<int64_t>& vec) const;
87 bool OverlapsIntInterval(int64_t lb, int64_t ub) const;
88 bool OverlapsDomain(const Domain& other) const;
89
90 // All the following modifiers change the internal representation
91 // list to interval or interval to list.
92 bool IntersectWithSingleton(int64_t value);
93 bool IntersectWithDomain(const Domain& domain);
94 bool IntersectWithInterval(int64_t interval_min, int64_t interval_max);
95 bool IntersectWithListOfIntegers(const std::vector<int64_t>& integers);
96 bool IntersectWithFloatDomain(const Domain& domain);
97
98 // Returns true iff the value did belong to the domain, and was removed.
99 // Try to remove the value. It returns true if it was actually removed.
100 // If the value is inside a large interval, then it will not be removed.
101 bool RemoveValue(int64_t value);
102 // Sets the empty float domain. Returns true.
103 bool SetEmptyFloatDomain();
104 std::string DebugString() const;
105
106 // These should never be modified from outside the class.
107 std::vector<int64_t> values;
108 bool is_interval = false;
109 bool display_as_boolean = false;
110 // Indicates if the domain was created as a set domain.
111 bool is_a_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, an 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 {
156 enum Type {
167 };
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* const 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)
222 : type(t),
223 arguments(std::move(args)),
224 strong_propagation(strong_propag),
225 active(true),
227
228 std::string DebugString() const;
229
230 // Helpers to be used during presolve.
231 void MarkAsInactive();
232 // Helper method to remove one argument.
233 void RemoveArg(int arg_pos);
234 // Set as a False constraint.
235 void SetAsFalse();
236
237 // The flatzinc type of the constraint (i.e. "int_eq" for integer equality)
238 // stored as a string.
239 std::string type;
240 std::vector<Argument> arguments;
241 // Is true if the constraint should use the strongest level of propagation.
242 // This is a hint in the model. For instance, in the AllDifferent constraint,
243 // there are different algorithms to propagate with different pruning/speed
244 // ratios. When strong_propagation is true, one should use, if possible, the
245 // algorithm with the strongest pruning.
247 // Indicates if the constraint is active. Presolve can make it inactive by
248 // propagating it, or by regrouping it. Once a constraint is inactive, it is
249 // logically removed from the model, it is not extracted, and it is ignored by
250 // presolve.
251 bool active : 1;
252
253 // Indicates if presolve has finished propagating this constraint.
255};
256
257// An annotation is a set of information. It has two use cases. One during
258// parsing to store intermediate information on model objects (i.e. the defines
259// part of a constraint). The other use case is to store all search
260// declarations. This persists after model parsing.
262 enum Type {
271 };
272
273 static Annotation Empty();
274 static Annotation AnnotationList(std::vector<Annotation> list);
275 static Annotation Identifier(absl::string_view id);
276 static Annotation FunctionCallWithArguments(absl::string_view id,
277 std::vector<Annotation> args);
278 static Annotation FunctionCall(absl::string_view id);
279 static Annotation Interval(int64_t interval_min, int64_t interval_max);
280 static Annotation IntegerValue(int64_t value);
281 static Annotation VarRef(Variable* const var);
282 static Annotation VarRefArray(std::vector<Variable*> variables);
283 static Annotation String(absl::string_view str);
284
285 std::string DebugString() const;
286 bool IsFunctionCallWithIdentifier(absl::string_view identifier) const {
287 return type == FUNCTION_CALL && id == identifier;
288 }
289 // Copy all the variable references contained in this annotation (and its
290 // children). Depending on the type of this annotation, there can be zero,
291 // one, or several.
292 void AppendAllVariables(std::vector<Variable*>* vars) const;
293
297 std::string id;
298 std::vector<Annotation> annotations;
299 std::vector<Variable*> variables;
300 std::string string_value;
301};
302
303// Information on what should be displayed when a solution is found.
304// It follows the flatzinc specification (www.minizinc.org).
306 struct Bounds {
307 Bounds(int64_t min_value_, int64_t max_value_)
308 : min_value(min_value_), max_value(max_value_) {}
309 std::string DebugString() const;
310 int64_t min_value;
311 int64_t max_value;
312 };
313
314 // Will output: name = <variable value>.
315 static SolutionOutputSpecs SingleVariable(absl::string_view name,
317 bool display_as_boolean);
318 // Will output (for example):
319 // name = array2d(min1..max1, min2..max2, [list of variable values])
320 // for a 2d array (bounds.size() == 2).
322 absl::string_view name, std::vector<Bounds> bounds,
323 std::vector<Variable*> flat_variables, bool display_as_boolean);
324 // Empty output.
326
327 std::string DebugString() const;
328
329 std::string name;
331 std::vector<Variable*> flat_variables;
332 // These are the starts and ends of intervals for displaying (potentially
333 // multi-dimensional) arrays.
334 std::vector<Bounds> bounds;
336};
337
338class Model {
339 public:
340 explicit Model(absl::string_view name)
341 : name_(name), objective_(nullptr), maximize_(true) {}
342 ~Model();
343
344 // ----- Builder methods -----
345
346 // The objects returned by AddVariable(), AddConstant(), and AddConstraint()
347 // are owned by the model and will remain live for its lifetime.
348 Variable* AddVariable(absl::string_view name, const Domain& domain,
349 bool defined);
350 Variable* AddConstant(int64_t value);
352 // Creates and add a constraint to the model.
353 void AddConstraint(absl::string_view id, std::vector<Argument> arguments,
354 bool is_domain);
355 void AddConstraint(const std::string& id, std::vector<Argument> arguments);
357
358 // Set the search annotations and the objective: either simply satisfy the
359 // problem, or minimize or maximize the given variable (which must have been
360 // added with AddVariable() already).
361 void Satisfy(std::vector<Annotation> search_annotations);
362 void Minimize(Variable* obj, std::vector<Annotation> search_annotations);
363 void Maximize(Variable* obj, std::vector<Annotation> search_annotations);
364
365 bool IsInconsistent() const;
366
367 // ----- Accessors and mutators -----
368
369 const std::vector<Variable*>& variables() const { return variables_; }
370 const std::vector<Constraint*>& constraints() const { return constraints_; }
371 const std::vector<Annotation>& search_annotations() const {
372 return search_annotations_;
373 }
374#if !defined(SWIG)
376 return util::MutableVectorIteration<Annotation>(&search_annotations_);
377 }
378#endif
379 const std::vector<SolutionOutputSpecs>& output() const { return output_; }
380#if !defined(SWIG)
383 }
384#endif
385 bool maximize() const { return maximize_; }
386 Variable* objective() const { return objective_; }
387 void SetObjective(Variable* obj) { objective_ = obj; }
388
389 // Services.
390 std::string DebugString() const;
391
392 const std::string& name() const { return name_; }
393
394 private:
395 const std::string name_;
396 // owned.
397 // TODO(user): use unique_ptr
398 std::vector<Variable*> variables_;
399 // owned.
400 // TODO(user): use unique_ptr
401 std::vector<Constraint*> constraints_;
402 // The objective variable (it belongs to variables_).
403 Variable* objective_;
404 bool maximize_;
405 // All search annotations are stored as a vector of Annotation.
406 std::vector<Annotation> search_annotations_;
407 std::vector<SolutionOutputSpecs> output_;
408};
409
410// Stand-alone statistics class on the model.
411// TODO(user): Clean up API to pass a Model* in argument.
413 public:
414 explicit ModelStatistics(const Model& model, SolverLogger* logger)
415 : model_(model), logger_(logger) {}
417 return constraints_per_variables_[var].size();
418 }
419 void BuildStatistics();
420 void PrintStatistics() const;
421
422 private:
423 const Model& model_;
424 SolverLogger* logger_;
425 std::map<std::string, std::vector<Constraint*>> constraints_per_type_;
426 absl::flat_hash_map<const Variable*, std::vector<Constraint*>>
427 constraints_per_variables_;
428};
429
430// Helper method to flatten Search annotations.
431void FlattenAnnotations(const Annotation& ann, std::vector<Annotation>* out);
432
433} // namespace fz
434} // namespace operations_research
435
436#endif // OR_TOOLS_FLATZINC_MODEL_H_
util::MutableVectorIteration< SolutionOutputSpecs > mutable_output()
Model(absl::string_view name)
void AddConstraint(absl::string_view id, std::vector< Argument > arguments, bool is_domain)
const std::string & name() const
const std::vector< Annotation > & search_annotations() const
const std::vector< SolutionOutputSpecs > & output() const
void SetObjective(Variable *obj)
Variable * AddConstant(int64_t value)
void Satisfy(std::vector< Annotation > search_annotations)
void AddOutput(SolutionOutputSpecs output)
util::MutableVectorIteration< Annotation > mutable_search_annotations()
Variable * AddVariable(absl::string_view name, const Domain &domain, bool defined)
void Maximize(Variable *obj, std::vector< Annotation > search_annotations)
void Minimize(Variable *obj, std::vector< Annotation > search_annotations)
Variable * AddFloatConstant(double value)
const std::vector< Constraint * > & constraints() const
const std::vector< Variable * > & variables() const
ModelStatistics(const Model &model, SolverLogger *logger)
int64_t value
IntVar * var
Definition: expr_array.cc:1874
GRBmodel * model
void FlattenAnnotations(const Annotation &ann, std::vector< Annotation > *out)
Collection of objects used to extend the Constraint Solver library.
STL namespace.
static Annotation IntegerValue(int64_t value)
void AppendAllVariables(std::vector< Variable * > *vars) const
static Annotation String(absl::string_view str)
static Annotation FunctionCallWithArguments(absl::string_view id, std::vector< Annotation > args)
bool IsFunctionCallWithIdentifier(absl::string_view identifier) const
static Annotation FunctionCall(absl::string_view id)
static Annotation AnnotationList(std::vector< Annotation > list)
std::vector< Variable * > variables
std::vector< Annotation > annotations
static Annotation Interval(int64_t interval_min, int64_t interval_max)
static Annotation VarRefArray(std::vector< Variable * > variables)
static Annotation VarRef(Variable *const var)
static Annotation Identifier(absl::string_view id)
static Argument FloatInterval(double lb, double ub)
static Argument DomainList(std::vector< Domain > domains)
Variable * VarAt(int pos) const
static Argument VarRef(Variable *const var)
bool Contains(int64_t value) const
static Argument IntegerList(std::vector< int64_t > values)
static Argument VarRefArray(std::vector< Variable * > vars)
static Argument IntegerValue(int64_t value)
static Argument Interval(int64_t imin, int64_t imax)
std::vector< Variable * > variables
static Argument FloatValue(double value)
std::vector< int64_t > values
int64_t ValueAt(int pos) const
static Argument FloatList(std::vector< double > floats)
static Argument FromDomain(const Domain &domain)
std::vector< Argument > arguments
Constraint(absl::string_view t, std::vector< Argument > args, bool strong_propag)
static Domain IntegerValue(int64_t value)
bool Contains(int64_t value) const
bool OverlapsDomain(const Domain &other) const
bool IntersectWithSingleton(int64_t value)
static Domain SetOfInterval(int64_t included_min, int64_t included_max)
static Domain IntegerList(std::vector< int64_t > values)
bool IntersectWithInterval(int64_t interval_min, int64_t interval_max)
bool IntersectWithFloatDomain(const Domain &domain)
bool IntersectWithDomain(const Domain &domain)
std::vector< double > float_values
static Domain FloatInterval(double lb, double ub)
bool OverlapsIntInterval(int64_t lb, int64_t ub) const
static Domain SetOfIntegerValue(int64_t value)
bool OverlapsIntList(const std::vector< int64_t > &vec) const
static Domain Interval(int64_t included_min, int64_t included_max)
std::vector< int64_t > values
static Domain SetOfIntegerList(std::vector< int64_t > values)
static Domain FloatValue(double value)
bool IntersectWithListOfIntegers(const std::vector< int64_t > &integers)
Bounds(int64_t min_value_, int64_t max_value_)
static SolutionOutputSpecs MultiDimensionalArray(absl::string_view name, std::vector< Bounds > bounds, std::vector< Variable * > flat_variables, bool display_as_boolean)
static SolutionOutputSpecs SingleVariable(absl::string_view name, Variable *variable, bool display_as_boolean)
bool Merge(absl::string_view other_name, const Domain &other_domain, bool other_temporary)