Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
circuit.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_SAT_CIRCUIT_H_
15#define ORTOOLS_SAT_CIRCUIT_H_
16
17#include <functional>
18#include <utility>
19#include <vector>
20
21#include "absl/container/btree_set.h"
22#include "absl/container/flat_hash_map.h"
23#include "absl/types/span.h"
27#include "ortools/sat/integer.h"
28#include "ortools/sat/model.h"
30#include "ortools/sat/util.h"
31#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 constraint 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, absl::Span<const int> tails,
57 absl::Span<const int> heads,
58 absl::Span<const Literal> enforcement_literals,
59 absl::Span<const Literal> literals, Options options,
60 Model* model);
61
62 // This type is neither copyable nor movable.
65
66 void SetLevel(int level) final;
67 bool Propagate() final;
68 bool IncrementalPropagate(const std::vector<int>& watch_indices) final;
69
70 private:
71 int RegisterWith(GenericLiteralWatcher* watcher);
72
73 // Updates the structures when the given arc is added to the paths.
74 void AddArc(int tail, int head, LiteralIndex literal_index);
75
76 // Clears and fills reason with the literals of the arcs that form a path from
77 // the given node. The path can be a cycle, but in this case it must end at
78 // start (not like a rho shape).
79 void FillReasonForPath(int start_node, std::vector<Literal>* reason) const;
80
81 // Reports a conflict if the constraint is enforced, or propagates the unique
82 // unassigned enforcement literal otherwise.
83 bool ReportConflictOrPropagateEnforcement(std::vector<Literal>* reason);
84
85 const int num_nodes_;
86 const Options options_;
87 Trail& trail_;
88 EnforcementHelper& enforcement_helper_;
89 EnforcementId enforcement_id_;
90 const VariablesAssignment& assignment_;
91 bool enabled_;
92
93 // We use this to query in O(1) for an arc existence. The self-arcs are
94 // accessed often, so we use a more efficient std::vector<> for them. Note
95 // that we do not add self-arcs to graph_.
96 //
97 // TODO(user): for large dense graph, using a matrix is faster and uses less
98 // memory. If the need arise we can have the two implementations.
99 std::vector<LiteralIndex> self_arcs_;
100 absl::flat_hash_map<std::pair<int, int>, Literal> graph_;
101
102 // Data used to interpret the watch indices passed to IncrementalPropagate().
103 struct Arc {
104 int tail;
105 int head;
106 };
107 std::vector<Literal> watch_index_to_literal_;
108 CompactVectorVector<int, Arc> watch_index_to_arcs_;
109
110 // Current partial chains of arc that are present.
111 std::vector<int> next_; // -1 if not assigned yet.
112 std::vector<int> prev_; // -1 if not assigned yet.
113 std::vector<LiteralIndex> next_literal_;
114
115 // Backtrack support for the partial chains of arcs, level_ends_[level] is an
116 // index in added_arcs_;
117 std::vector<int> level_ends_;
118 std::vector<Arc> added_arcs_;
119
120 // Reversible list of node that must be in a cycle. A node must be in a cycle
121 // iff self_arcs_[node] is false. This graph entry can be used as a reason.
122 int rev_must_be_in_cycle_size_ = 0;
123 std::vector<int> must_be_in_cycle_;
124
125 // Temporary vectors.
126 std::vector<bool> processed_;
127 std::vector<bool> in_current_path_;
128 std::vector<Literal> temp_reason_;
129};
130
131// Enforce the fact that there is no cycle in the given directed graph.
133 public:
134 NoCyclePropagator(int num_nodes, absl::Span<const int> tails,
135 absl::Span<const int> heads,
136 absl::Span<const Literal> literals, Model* model);
137
138 void SetLevel(int level) final;
139 bool Propagate() final;
140 bool IncrementalPropagate(const std::vector<int>& watch_indices) final;
141
142 private:
143 void RegisterWith(GenericLiteralWatcher* watcher);
144
145 const int num_nodes_;
146 Trail* trail_;
147 const VariablesAssignment& assignment_;
148
149 // The set of all watched literals and to what arc they correspond.
150 std::vector<Literal> watch_index_to_literal_;
151 std::vector<std::vector<std::pair<int, int>>> watch_index_to_arcs_;
152
153 // This will only contains the subgraph with all the arc at true.
154 // We maintain it incrementally and update this on SetLevel()/Propagate().
155 std::vector<std::vector<int>> graph_;
156 std::vector<std::vector<Literal>> graph_literals_;
157
158 // For now we redo a strongly connected component on the graph formed of arcs
159 // at one.
160 //
161 // TODO(user): code a true algo.
162 std::vector<std::vector<int>> components_;
164 std::vector<std::vector<int>>>
165 ssc_;
166
167 // SAT incremental state.
168 std::vector<int> level_ends_;
169 std::vector<int> touched_nodes_;
170};
171
172// This constraint ensures that the graph is a covering of all nodes by
173// circuits and loops, such that all circuits contain exactly one distinguished
174// node. Those distinguished nodes are meant to be depots.
175//
176// This constraint does not need ExactlyOnePerRowAndPerColumn() to be correct,
177// but it does not propagate degree deductions (only fails if a node has more
178// than one outgoing arc or more than one incoming arc), so that adding
179// ExactlyOnePerRowAndPerColumn() should work better.
180//
181// TODO(user): Make distinguished nodes an array of Boolean variables,
182// so this can be used for facility location problems.
184 public:
185 CircuitCoveringPropagator(std::vector<std::vector<Literal>> graph,
186 absl::Span<const int> distinguished_nodes,
187 Model* model);
188
189 void SetLevel(int level) final;
190 bool Propagate() final;
191 bool IncrementalPropagate(const std::vector<int>& watch_indices) final;
192 void RegisterWith(GenericLiteralWatcher* watcher);
193
194 private:
195 // Adds all literals on the path/circuit from tail to head in the graph of
196 // literals set to true.
197 // next_[i] should be filled with a node j s.t. graph_[i][j] is true, or -1.
198 void FillFixedPathInReason(int start, int end, std::vector<Literal>* reason);
199
200 // Input data.
201 const std::vector<std::vector<Literal>> graph_;
202 const int num_nodes_;
203 std::vector<bool> node_is_distinguished_;
204
205 // SAT incremental state.
206 Trail* trail_;
207 std::vector<std::pair<int, int>> watch_index_to_arc_;
208 std::vector<std::pair<int, int>> fixed_arcs_;
209 std::vector<int> level_ends_;
210
211 // Used in Propagate() to represent paths and circuits.
212 std::vector<int> next_;
213 std::vector<int> prev_;
214 std::vector<bool> visited_;
215};
216
217// Changes the node indices so that we get a graph in [0, num_nodes) where every
218// node has at least one incoming or outgoing arc. Returns the number of nodes.
219template <class IntContainer>
220int ReindexArcs(IntContainer* tails, IntContainer* heads,
221 absl::flat_hash_map<int, int>* mapping_output = nullptr) {
222 const int num_arcs = tails->size();
223 if (num_arcs == 0) return 0;
224
225 // Put all nodes in a set.
226 absl::btree_set<int> nodes;
227 for (int arc = 0; arc < num_arcs; ++arc) {
228 nodes.insert((*tails)[arc]);
229 nodes.insert((*heads)[arc]);
230 }
231
232 // Compute the new indices while keeping a stable order.
233 int new_index = 0;
234 absl::flat_hash_map<int, int> mapping;
235 for (const int node : nodes) {
236 mapping[node] = new_index++;
237 }
238
239 // Remap the arcs.
240 for (int arc = 0; arc < num_arcs; ++arc) {
241 (*tails)[arc] = mapping[(*tails)[arc]];
242 (*heads)[arc] = mapping[(*heads)[arc]];
243 }
244
245 if (mapping_output != nullptr) {
246 *mapping_output = std::move(mapping);
247 }
248
249 return nodes.size();
250}
251
252// ============================================================================
253// Model based functions.
254// ============================================================================
255
256// This just wraps CircuitPropagator. See the comment there to see what this
257// does. Note that any nodes with no outgoing or no incoming arc will cause the
258// problem to be UNSAT. One can call ReindexArcs() first to ignore such nodes.
259void LoadSubcircuitConstraint(int num_nodes, absl::Span<const int> tails,
260 absl::Span<const int> heads,
261 absl::Span<const Literal> enforcement_literals,
262 absl::Span<const Literal> literals, Model* model,
263 bool multiple_subcircuit_through_zero = false);
264
265// TODO(user): Change to a sparse API like for the function above.
266std::function<void(Model*)> ExactlyOnePerRowAndPerColumn(
267 absl::Span<const std::vector<Literal>> graph);
268std::function<void(Model*)> CircuitCovering(
269 absl::Span<const std::vector<Literal>> graph,
270 absl::Span<const int> distinguished_nodes);
271
272} // namespace sat
273} // namespace operations_research
274
275#endif // ORTOOLS_SAT_CIRCUIT_H_
Definition model.h:345
CircuitCoveringPropagator(std::vector< std::vector< Literal > > graph, absl::Span< const int > distinguished_nodes, Model *model)
Definition circuit.cc:537
void RegisterWith(GenericLiteralWatcher *watcher)
Definition circuit.cc:549
bool IncrementalPropagate(const std::vector< int > &watch_indices) final
Definition circuit.cc:582
bool IncrementalPropagate(const std::vector< int > &watch_indices) final
Definition circuit.cc:204
CircuitPropagator(int num_nodes, absl::Span< const int > tails, absl::Span< const int > heads, absl::Span< const Literal > enforcement_literals, absl::Span< const Literal > literals, Options options, Model *model)
Definition circuit.cc:39
CircuitPropagator & operator=(const CircuitPropagator &)=delete
CircuitPropagator(const CircuitPropagator &)=delete
bool IncrementalPropagate(const std::vector< int > &watch_indices) final
Definition circuit.cc:486
NoCyclePropagator(int num_nodes, absl::Span< const int > tails, absl::Span< const int > heads, absl::Span< const Literal > literals, Model *model)
Definition circuit.cc:413
std::function< void(Model *)> CircuitCovering(absl::Span< const std::vector< Literal > > graph, absl::Span< const int > distinguished_nodes)
Definition circuit.cc:779
int ReindexArcs(IntContainer *tails, IntContainer *heads, absl::flat_hash_map< int, int > *mapping_output=nullptr)
Definition circuit.h:220
void LoadSubcircuitConstraint(int num_nodes, absl::Span< const int > tails, absl::Span< const int > heads, absl::Span< const Literal > enforcement_literals, absl::Span< const Literal > literals, Model *model, bool multiple_subcircuit_through_zero)
Definition circuit.cc:720
std::function< void(Model *)> ExactlyOnePerRowAndPerColumn(absl::Span< const std::vector< Literal > > graph)
Definition circuit.cc:681
OR-Tools root namespace.
ClosedInterval::Iterator end(ClosedInterval interval)
STL namespace.