OR-Tools  9.3
circuit.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_CIRCUIT_H_
15#define OR_TOOLS_SAT_CIRCUIT_H_
16
17#include <functional>
18#include <memory>
19#include <utility>
20#include <vector>
21
22#include "absl/container/btree_set.h"
23#include "absl/container/flat_hash_map.h"
26#include "ortools/base/macros.h"
27#include "ortools/sat/integer.h"
28#include "ortools/sat/model.h"
30#include "ortools/util/rev.h"
32
33namespace operations_research {
34namespace sat {
35
36// Circuit/sub-circuit constraint.
37//
38// Nodes that are not in the unique allowed sub-circuit must point to themseves.
39// A nodes that has no self-arc must thus be inside the sub-circuit. If there is
40// no self-arc at all, then this constaint forces the circuit to go through all
41// the nodes. Multi-arcs are NOT supported.
42//
43// Important: for correctness, this constraint requires that "exactly one"
44// constraints have been added for all the incoming (resp. outgoing) arcs of
45// each node. Also, such constraint must propagate before this one.
47 public:
48 struct Options {
49 // Hack for the VRP to allow for more than one sub-circuit and forces all
50 // the subcircuits to go through the node zero.
52 };
53
54 // The constraints take a sparse representation of a graph on [0, n). Each arc
55 // being present when the given literal is true.
56 CircuitPropagator(int num_nodes, const std::vector<int>& tails,
57 const std::vector<int>& heads,
58 const std::vector<Literal>& literals, Options options,
59 Model* model);
60
61 void SetLevel(int level) final;
62 bool Propagate() final;
63 bool IncrementalPropagate(const std::vector<int>& watch_indices) final;
65
66 private:
67 // Updates the structures when the given arc is added to the paths.
68 void AddArc(int tail, int head, LiteralIndex literal_index);
69
70 // Clears and fills reason with the literals of the arcs that form a path from
71 // the given node. The path can be a cycle, but in this case it must end at
72 // start (not like a rho shape).
73 void FillReasonForPath(int start_node, std::vector<Literal>* reason) const;
74
75 const int num_nodes_;
76 const Options options_;
77 Trail* trail_;
78 const VariablesAssignment& assignment_;
79
80 // We use this to query in O(1) for an arc existence. The self-arcs are
81 // accessed often, so we use a more efficient std::vector<> for them. Note
82 // that we do not add self-arcs to graph_.
83 //
84 // TODO(user): for large dense graph, using a matrix is faster and uses less
85 // memory. If the need arise we can have the two implementations.
86 std::vector<Literal> self_arcs_;
87 absl::flat_hash_map<std::pair<int, int>, Literal> graph_;
88
89 // Data used to interpret the watch indices passed to IncrementalPropagate().
90 struct Arc {
91 int tail;
92 int head;
93 };
94 std::vector<Literal> watch_index_to_literal_;
95 std::vector<std::vector<Arc>> watch_index_to_arcs_;
96
97 // Index in trail_ up to which we propagated all the assigned Literals.
98 int propagation_trail_index_ = 0;
99
100 // Current partial chains of arc that are present.
101 std::vector<int> next_; // -1 if not assigned yet.
102 std::vector<int> prev_; // -1 if not assigned yet.
103 std::vector<LiteralIndex> next_literal_;
104
105 // Backtrack support for the partial chains of arcs, level_ends_[level] is an
106 // index in added_arcs_;
107 std::vector<int> level_ends_;
108 std::vector<Arc> added_arcs_;
109
110 // Reversible list of node that must be in a cycle. A node must be in a cycle
111 // iff self_arcs_[node] is false. This graph entry can be used as a reason.
112 int rev_must_be_in_cycle_size_ = 0;
113 std::vector<int> must_be_in_cycle_;
114
115 // Temporary vectors.
116 std::vector<bool> processed_;
117 std::vector<bool> in_current_path_;
118
119 DISALLOW_COPY_AND_ASSIGN(CircuitPropagator);
120};
121
122// This constraint ensures that the graph is a covering of all nodes by
123// circuits and loops, such that all circuits contain exactly one distinguished
124// node. Those distinguished nodes are meant to be depots.
125//
126// This constraint does not need ExactlyOnePerRowAndPerColumn() to be correct,
127// but it does not propagate degree deductions (only fails if a node has more
128// than one outgoing arc or more than one incoming arc), so that adding
129// ExactlyOnePerRowAndPerColumn() should work better.
130//
131// TODO(user): Make distinguished nodes an array of Boolean variables,
132// so this can be used for facility location problems.
134 public:
135 CircuitCoveringPropagator(std::vector<std::vector<Literal>> graph,
136 const std::vector<int>& distinguished_nodes,
137 Model* model);
138
139 void SetLevel(int level) final;
140 bool Propagate() final;
141 bool IncrementalPropagate(const std::vector<int>& watch_indices) final;
142 void RegisterWith(GenericLiteralWatcher* watcher);
143
144 private:
145 // Adds all literals on the path/circuit from tail to head in the graph of
146 // literals set to true.
147 // next_[i] should be filled with a node j s.t. graph_[i][j] is true, or -1.
148 void FillFixedPathInReason(int start, int end, std::vector<Literal>* reason);
149
150 // Input data.
151 const std::vector<std::vector<Literal>> graph_;
152 const int num_nodes_;
153 std::vector<bool> node_is_distinguished_;
154
155 // SAT incremental state.
156 Trail* trail_;
157 std::vector<std::pair<int, int>> watch_index_to_arc_;
158 std::vector<std::pair<int, int>> fixed_arcs_;
159 std::vector<int> level_ends_;
160
161 // Used in Propagate() to represent paths and circuits.
162 std::vector<int> next_;
163 std::vector<int> prev_;
164 std::vector<bool> visited_;
165};
166
167// Changes the node indices so that we get a graph in [0, num_nodes) where every
168// node has at least one incoming or outgoing arc. Returns the number of nodes.
169template <class IntContainer>
170int ReindexArcs(IntContainer* tails, IntContainer* heads) {
171 const int num_arcs = tails->size();
172 if (num_arcs == 0) return 0;
173
174 // Put all nodes in a set.
175 absl::btree_set<int> nodes;
176 for (int arc = 0; arc < num_arcs; ++arc) {
177 nodes.insert((*tails)[arc]);
178 nodes.insert((*heads)[arc]);
179 }
180
181 // Compute the new indices while keeping a stable order.
182 int new_index = 0;
183 absl::flat_hash_map<int, int> mapping;
184 for (const int node : nodes) {
185 mapping[node] = new_index++;
186 }
187
188 // Remap the arcs.
189 for (int arc = 0; arc < num_arcs; ++arc) {
190 (*tails)[arc] = mapping[(*tails)[arc]];
191 (*heads)[arc] = mapping[(*heads)[arc]];
192 }
193 return nodes.size();
194}
195
196// ============================================================================
197// Model based functions.
198// ============================================================================
199
200// This just wraps CircuitPropagator. See the comment there to see what this
201// does. Note that any nodes with no outoing or no incoming arc will cause the
202// problem to be UNSAT. One can call ReindexArcs() first to ignore such nodes.
203std::function<void(Model*)> SubcircuitConstraint(
204 int num_nodes, const std::vector<int>& tails, const std::vector<int>& heads,
205 const std::vector<Literal>& literals,
206 bool multiple_subcircuit_through_zero = false);
207
208// TODO(user): Change to a sparse API like for the function above.
209std::function<void(Model*)> ExactlyOnePerRowAndPerColumn(
210 const std::vector<std::vector<Literal>>& graph);
211std::function<void(Model*)> CircuitCovering(
212 const std::vector<std::vector<Literal>>& graph,
213 const std::vector<int>& distinguished_nodes);
214
215} // namespace sat
216} // namespace operations_research
217
218#endif // OR_TOOLS_SAT_CIRCUIT_H_
CircuitCoveringPropagator(std::vector< std::vector< Literal > > graph, const std::vector< int > &distinguished_nodes, Model *model)
Definition: circuit.cc:344
bool IncrementalPropagate(const std::vector< int > &watch_indices) final
Definition: circuit.cc:389
void RegisterWith(GenericLiteralWatcher *watcher)
Definition: circuit.cc:356
bool IncrementalPropagate(const std::vector< int > &watch_indices) final
Definition: circuit.cc:161
void RegisterWith(GenericLiteralWatcher *watcher)
Definition: circuit.cc:100
CircuitPropagator(int num_nodes, const std::vector< int > &tails, const std::vector< int > &heads, const std::vector< Literal > &literals, Options options, Model *model)
Definition: circuit.cc:33
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:42
GRBmodel * model
int arc
Definition: cleanup.h:22
std::function< void(Model *)> SubcircuitConstraint(int num_nodes, const std::vector< int > &tails, const std::vector< int > &heads, const std::vector< Literal > &literals, bool multiple_subcircuit_through_zero)
Definition: circuit.cc:507
std::function< void(Model *)> CircuitCovering(const std::vector< std::vector< Literal > > &graph, const std::vector< int > &distinguished_nodes)
Definition: circuit.cc:549
std::function< void(Model *)> ExactlyOnePerRowAndPerColumn(const std::vector< std::vector< Literal > > &graph)
Definition: circuit.cc:488
int ReindexArcs(IntContainer *tails, IntContainer *heads)
Definition: circuit.h:170
Collection of objects used to extend the Constraint Solver library.
std::pair< int64_t, int64_t > Arc
Definition: search.cc:3434
STL namespace.
int64_t tail
int64_t head
int nodes
std::optional< int64_t > end
int64_t start