OR-Tools  9.1
perfect_matching.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// Implementation of the Blossom V min-cost perfect matching algorithm. The
15// main source for the algo is the paper: "Blossom V: A new implementation
16// of a minimum cost perfect matching algorithm", Vladimir Kolmogorov.
17//
18// The Algorithm is a primal-dual algorithm. It always maintains a dual-feasible
19// solution. We recall some notations here, but see the paper for more details
20// as it is well written.
21//
22// TODO(user): This is a work in progress. The algo is not fully implemented
23// yet. The initial version is closer to Blossom IV since we update the dual
24// values for all trees at once with the same delta.
25
26#ifndef OR_TOOLS_GRAPH_PERFECT_MATCHING_H_
27#define OR_TOOLS_GRAPH_PERFECT_MATCHING_H_
28
29#include <cstdint>
30#include <limits>
31#include <vector>
32
33#include "absl/strings/str_cat.h"
34#include "absl/strings/str_join.h"
40#include "ortools/base/macros.h"
42
43namespace operations_research {
44
45class BlossomGraph;
46
47// Given an undirected graph with costs on each edges, this class allows to
48// compute a perfect matching with minimum cost. A matching is a set of disjoint
49// pairs of nodes connected by an edge. The matching is perfect if all nodes are
50// matched to each others.
52 public:
53 // TODO(user): For now we ask the number of nodes at construction, but we
54 // could automatically infer it from the added edges if needed.
56 explicit MinCostPerfectMatching(int num_nodes) { Reset(num_nodes); }
57
58 // Resets the class for a new graph.
59 //
60 // TODO(user): Eventually, we may support incremental Solves(). Or at least
61 // memory reuse if one wants to solve many problems in a row.
62 void Reset(int num_nodes);
63
64 // Adds an undirected edges between the two given nodes.
65 //
66 // For now we only accept non-negative cost.
67 // TODO(user): We can easily shift all costs if negative costs are needed.
68 //
69 // Important: The algorithm supports multi-edges, but it will be slower. So it
70 // is better to only add one edge with a minimum cost between two nodes. In
71 // particular, do not add both AddEdge(a, b, cost) and AddEdge(b, a, cost).
72 // TODO(user): We could just presolve them away.
73 void AddEdgeWithCost(int tail, int head, int64_t cost);
74
75 // Solves the min-cost perfect matching problem on the given graph.
76 //
77 // NOTE(user): If needed we could support a time limit. Aborting early will
78 // not provide a perfect matching, but the algorithm does maintain a valid
79 // lower bound on the optimal cost that gets better and better during
80 // execution until it reaches the optimal value. Similarly, it is easy to
81 // support an early stop if this bound crosses a preset threshold.
82 enum Status {
83 // A perfect matching with min-cost has been found.
85
86 // There is no perfect matching in this graph.
88
89 // The costs are too large and caused an overflow during the algorithm
90 // execution.
92
93 // Advanced usage: the matching is OPTIMAL and was computed without
94 // overflow, but its OptimalCost() does not fit on an int64_t. Note that
95 // Match() still work and you can re-compute the cost in double for
96 // instance.
98 };
99 ABSL_MUST_USE_RESULT Status Solve();
100
101 // Returns the cost of the perfect matching. Only valid when the last solve
102 // status was OPTIMAL.
103 int64_t OptimalCost() const {
104 DCHECK(optimal_solution_found_);
105 return optimal_cost_;
106 }
107
108 // Returns the node matched to the given node. In a perfect matching all nodes
109 // have a match. Only valid when the last solve status was OPTIMAL.
110 int Match(int node) const {
111 DCHECK(optimal_solution_found_);
112 return matches_[node];
113 }
114 const std::vector<int>& Matches() const {
115 DCHECK(optimal_solution_found_);
116 return matches_;
117 }
118
119 private:
120 std::unique_ptr<BlossomGraph> graph_;
121
122 // Fields used to report the optimal solution. Most of it could be read on
123 // the fly from BlossomGraph, but we prefer to copy them here. This allows to
124 // reclaim the memory of graph_ early or allows to still query the last
125 // solution if we later allow re-solve with incremental changes to the graph.
126 bool optimal_solution_found_ = false;
127 int64_t optimal_cost_ = 0;
128 int64_t maximum_edge_cost_ = 0;
129 std::vector<int> matches_;
130};
131
132// Class containing the main data structure used by the Blossom algorithm.
133//
134// At the core is the original undirected graph. During the algorithm execution
135// we might collapse nodes into so-called Blossoms. A Blossom is a cycle of
136// external nodes (which can be blossom nodes) of odd length (>= 3). The edges
137// of the cycle are called blossom-forming eges and will always be tight
138// (i.e. have a slack of zero). Once a Blossom is created, its nodes become
139// "internal" and are basically considered merged into the blossom node for the
140// rest of the algorithm (except if we later re-expand the blossom).
141//
142// Moreover, external nodes of the graph will have 3 possible types ([+], [-]
143// and free [0]). Free nodes will always be matched together in pairs. Nodes of
144// type [+] and [-] are arranged in a forest of alternating [+]/[-] disjoint
145// trees. Each unmatched node is the root of a tree, and of type [+]. Nodes [-]
146// will always have exactly one child to witch they are matched. [+] nodes can
147// have any number of [-] children, to which they are not matched. All the edges
148// of the trees will always be tight. Some examples below, double edges are used
149// for matched nodes:
150//
151// A matched pair of free nodes: [0] === [0]
152//
153// A possible rooted tree: [+] -- [-] ==== [+]
154// \
155// [-] ==== [+] ---- [-] === [+]
156// \
157// [-] === [+]
158//
159// A single unmatched node is also a tree: [+]
160//
161// TODO(user): For now this class does not maintain a second graph of edges
162// between the trees nor does it maintains priority queue of edges.
163//
164// TODO(user): For now we use CHECKs in many places to facilitate development.
165// Switch them to DCHECKs for speed once the code is more stable.
167 public:
168 // Typed index used by this class.
170 DEFINE_INT_TYPE(EdgeIndex, int);
172
173 // Basic constants.
174 // NOTE(user): Those can't be constexpr because of the or-tools export,
175 // which complains for constexpr DEFINE_INT_TYPE.
177 static const EdgeIndex kNoEdgeIndex;
179
180 // Node related data.
181 // We store the edges incident to a node separately in the graph_ member.
182 struct Node {
183 explicit Node(NodeIndex n) : parent(n), match(n), root(n) {}
184
185 // A node can be in one of these 4 exclusive states. Internal nodes are part
186 // of a Blossom and should be ignored until this Blossom is expanded. All
187 // the other nodes are "external". A free node is always matched to another
188 // free node. All the other external node are in alternating [+]/[-] trees
189 // rooted at the only unmatched node of the tree (always of type [+]).
190 bool IsInternal() const {
191 DCHECK(!is_internal || type == 0);
192 return is_internal;
193 }
194 bool IsFree() const { return type == 0 && !is_internal; }
195 bool IsPlus() const { return type == 1; }
196 bool IsMinus() const { return type == -1; }
197
198 // Is this node a blossom? if yes, it was formed by merging the node.blossom
199 // nodes together. Note that we reuse the index of node.blossom[0] for this
200 // blossom node. A blossom node can be of any type.
201 bool IsBlossom() const { return !blossom.empty(); }
202
203 // The type of this node. We use an int for convenience in the update
204 // formulas. This is 1 for [+] nodes, -1 for [-] nodes and 0 for all the
205 // others.
206 //
207 // Internal node also have a type of zero so the dual formula are correct.
208 int type = 0;
209
210 // Whether this node is part of a blossom.
211 bool is_internal = false;
212
213 // The parent of this node in its tree or itself otherwise.
214 // Unused for internal nodes.
216
217 // Itself if not matched, or this node match otherwise.
218 // Unused for internal nodes.
220
221 // The root of this tree which never changes until a tree is disassambled by
222 // an Augment(). Unused for internal nodes.
224
225 // The "delta" to apply to get the dual for nodes of this tree.
226 // This is only filled for root nodes (i.e unmatched nodes).
228
229 // See the formula in Dual() used to derive the true dual of this node.
230 // This is the equal to the "true" dual for free exterior node and internal
231 // node.
233
234#ifndef NDEBUG
235 // The true dual of this node. We only maintain this in debug mode.
237#endif
238
239 // Non-empty for Blossom only. The odd-cycle of blossom nodes that form this
240 // blossom. The first element should always be the current blossom node, and
241 // all the other nodes are internal nodes.
242 std::vector<NodeIndex> blossom;
243
244 // This allows to store information about a new blossom node created by
245 // Shrink() so that we can properly restore it on Expand(). Note that we
246 // store the saved information on the second node of a blossom cycle (and
247 // not the blossom node itself) because that node will be "hidden" until the
248 // blossom is expanded so this way, we do not need more than one set of
249 // saved information per node.
250#ifndef NDEBUG
252#endif
254 std::vector<NodeIndex> saved_blossom;
255 };
256
257 // An undirected edge between two nodes: tail <-> head.
258 struct Edge {
260 : pseudo_slack(c),
261#ifndef NDEBUG
262 slack(c),
263#endif
264 tail(t),
265 head(h) {
266 }
267
268 // Returns the "other" end of this edge.
270 DCHECK(n == tail || n == head);
271 return NodeIndex(tail.value() ^ head.value() ^ n.value());
272 }
273
274 // AdjustablePriorityQueue interface. Note that we use std::greater<> in
275 // our queues since we want the lowest pseudo_slack first.
277 int GetHeapIndex() const { return pq_position; }
278 bool operator>(const Edge& other) const {
279 return pseudo_slack > other.pseudo_slack;
280 }
281
282 // See the formula is Slack() used to derive the true slack of this edge.
284
285#ifndef NDEBUG
286 // We only maintain this in debug mode.
288#endif
289
290 // These are the current tail/head of this edges. These are changed when
291 // creating or expanding blossoms. The order do not matter.
292 //
293 // TODO(user): Consider using node_a/node_b instead to remove the "directed"
294 // meaning. I do need to think a bit more about it though.
297
298 // Position of this Edge in the underlying std::vector<> used to encode the
299 // heap of one priority queue. An edge can be in at most one priority queue
300 // which allow us to share this amongst queues.
301 int pq_position = -1;
302 };
303
304 // Creates a BlossomGraph on the given number of nodes.
305 explicit BlossomGraph(int num_nodes);
306
307 // Same comment as MinCostPerfectMatching::AddEdgeWithCost() applies.
309
310 // Heuristic to start with a dual-feasible solution and some matched edges.
311 // To be called once all edges are added. Returns false if the problem is
312 // detected to be INFEASIBLE.
313 ABSL_MUST_USE_RESULT bool Initialize();
314
315 // Enters a loop that perform one of Grow()/Augment()/Shrink()/Expand() until
316 // a fixed point is reached.
317 void PrimalUpdates();
318
319 // Computes the maximum possible delta for UpdateAllTrees() that keeps the
320 // dual feasibility. Dual update approach (2) from the paper. This also fills
321 // primal_update_edge_queue_.
323
324 // Applies the same dual delta to all trees. Dual update approach (2) from the
325 // paper.
327
328 // Returns true iff this node is matched and is thus not a tree root.
329 // This cannot live in the Node class because we need to know the NodeIndex.
330 bool NodeIsMatched(NodeIndex n) const;
331
332 // Returns the node matched to the given one, or n if this node is not
333 // currently matched.
334 NodeIndex Match(NodeIndex n) const;
335
336 // Adds to the tree of tail the free matched pair(head, Match(head)).
337 // The edge is only used in DCHECKs. We duplicate tail/head because the
338 // order matter here.
339 void Grow(EdgeIndex e, NodeIndex tail, NodeIndex head);
340
341 // Merges two tree and augment the number of matched nodes by 1. This is
342 // the only functions that change the current matching.
343 void Augment(EdgeIndex e);
344
345 // Creates a Blossom using the given [+] -- [+] edge between two nodes of the
346 // same tree.
347 void Shrink(EdgeIndex e);
348
349 // Expands a Blossom into its component.
350 void Expand(NodeIndex to_expand);
351
352 // Returns the current number of matched nodes.
353 int NumMatched() const { return nodes_.size() - unmatched_nodes_.size(); }
354
355 // Returns the current dual objective which is always a valid lower-bound on
356 // the min-cost matching. Note that this is capped to kint64max in case of
357 // overflow. Because all of our cost are positive, this starts at zero.
358 CostValue DualObjective() const;
359
360 // This must be called at the end of the algorithm to recover the matching.
361 void ExpandAllBlossoms();
362
363 // Return the "slack" of the given edge.
364 CostValue Slack(const Edge& edge) const;
365
366 // Returns the dual value of the given node (which might be a pseudo-node).
367 CostValue Dual(const Node& node) const;
368
369 // Display to VLOG(1) some statistic about the solve.
370 void DisplayStats() const;
371
372 // Checks that there is no possible primal update in the current
373 // configuration.
375
376 // Tests that the dual values are currently feasible.
377 // This should ALWAYS be the case.
378 bool DebugDualsAreFeasible() const;
379
380 // In debug mode, we maintain the real slack of each edges and the real dual
381 // of each node via this function. Both Slack() and Dual() checks in debug
382 // mode that the value computed is the correct one.
384
385 // Returns true iff this is an external edge with a slack of zero.
386 // An external edge is an edge between two external nodes.
387 bool DebugEdgeIsTightAndExternal(const Edge& edge) const;
388
389 // Getters to access node/edges from outside the class.
390 // Only used in tests.
391 const Edge& GetEdge(int e) const { return edges_[EdgeIndex(e)]; }
392 const Node& GetNode(int n) const { return nodes_[NodeIndex(n)]; }
393
394 // Display information for debugging.
395 std::string NodeDebugString(NodeIndex n) const;
396 std::string EdgeDebugString(EdgeIndex e) const;
397 std::string DebugString() const;
398
399 private:
400 // Returns the index of a tight edge between the two given external nodes.
401 // Returns kNoEdgeIndex if none could be found.
402 //
403 // TODO(user): Store edges for match/parent/blossom instead and remove the
404 // need for this function that can take around 10% of the running time on
405 // some problems.
406 EdgeIndex FindTightExternalEdgeBetweenNodes(NodeIndex tail, NodeIndex head);
407
408 // Appends the path from n to the root of its tree. Used by Augment().
409 void AppendNodePathToRoot(NodeIndex n, std::vector<NodeIndex>* path) const;
410
411 // Returns the depth of a node in its tree. Used by Shrink().
412 int GetDepth(NodeIndex n) const;
413
414 // Adds positive delta to dual_objective_ and cap at kint64max on overflow.
415 void AddToDualObjective(CostValue delta);
416
417 // In the presence of blossoms, the original tail/head of an arc might not be
418 // up to date anymore. It is important to use these functions instead in all
419 // the places where this can happen. That is basically everywhere except in
420 // the initialization.
421 NodeIndex Tail(const Edge& edge) const {
422 return root_blossom_node_[edge.tail];
423 }
424 NodeIndex Head(const Edge& edge) const {
425 return root_blossom_node_[edge.head];
426 }
427
428 // Returns the Head() or Tail() that does not correspond to node. Node that
429 // node must be one of the original index in the given edge, this is DCHECKed
430 // by edge.OtherEnd().
431 NodeIndex OtherEnd(const Edge& edge, NodeIndex node) const {
432 return root_blossom_node_[edge.OtherEnd(node)];
433 }
434
435 // Same as OtherEnd() but the given node should either be Tail(edge) or
436 // Head(edge) and do not need to be one of the original node of this edge.
437 NodeIndex OtherEndFromExternalNode(const Edge& edge, NodeIndex node) const {
438 const NodeIndex head = Head(edge);
439 if (head != node) {
440 DCHECK_EQ(node, Tail(edge));
441 return head;
442 }
443 return Tail(edge);
444 }
445
446 // Returns the given node and if this node is a blossom, all its internal
447 // nodes (recursively). Note that any call to SubNodes() invalidate the
448 // previously returned reference.
449 const std::vector<NodeIndex>& SubNodes(NodeIndex n);
450
451 // Just used to check that initialized is called exactly once.
452 bool is_initialized_ = false;
453
454 // The set of all edges/nodes of the graph.
457
458 // Identity for a non-blossom node, and its top blossom node (in case of many
459 // nested blossom) for an internal node.
461
462 // The current graph incidence. Note that one EdgeIndex should appear in
463 // exactly two places (on its tail and head incidence list).
465
466 // Used by SubNodes().
467 std::vector<NodeIndex> subnodes_;
468
469 // The unmatched nodes are exactly the root of the trees. After
470 // initialization, this is only modified by Augment() which removes two nodes
471 // from this list each time. Note that during Shrink()/Expand() we never
472 // change the indexing of the root nodes.
473 std::vector<NodeIndex> unmatched_nodes_;
474
475 // List of tight_edges and possible shrink to check in PrimalUpdates().
476 std::vector<EdgeIndex> primal_update_edge_queue_;
477 std::vector<EdgeIndex> possible_shrink_;
478
479 // Priority queues of edges of a certain types.
482 std::vector<Edge*> tmp_all_tops_;
483
484 // The dual objective. Increase as the algorithm progress. This is a lower
485 // bound on the min-cost of a perfect matching.
486 CostValue dual_objective_ = CostValue(0);
487
488 // Statistics on the main operations.
489 int64_t num_grows_ = 0;
490 int64_t num_augments_ = 0;
491 int64_t num_shrinks_ = 0;
492 int64_t num_expands_ = 0;
493 int64_t num_dual_updates_ = 0;
494};
495
496} // namespace operations_research
497
498#endif // OR_TOOLS_GRAPH_PERFECT_MATCHING_H_
#define DCHECK(condition)
Definition: base/logging.h:885
#define DCHECK_EQ(val1, val2)
Definition: base/logging.h:886
DEFINE_INT_TYPE(CostValue, int64_t)
ABSL_MUST_USE_RESULT bool Initialize()
const Node & GetNode(int n) const
void Grow(EdgeIndex e, NodeIndex tail, NodeIndex head)
CostValue ComputeMaxCommonTreeDualDeltaAndResetPrimalEdgeQueue()
bool DebugEdgeIsTightAndExternal(const Edge &edge) const
static const CostValue kMaxCostValue
NodeIndex Match(NodeIndex n) const
void AddEdge(NodeIndex tail, NodeIndex head, CostValue cost)
const Edge & GetEdge(int e) const
bool NodeIsMatched(NodeIndex n) const
CostValue Slack(const Edge &edge) const
std::string NodeDebugString(NodeIndex n) const
std::string EdgeDebugString(EdgeIndex e) const
CostValue Dual(const Node &node) const
static const EdgeIndex kNoEdgeIndex
static const NodeIndex kNoNodeIndex
void Expand(NodeIndex to_expand)
void UpdateAllTrees(CostValue delta)
void DebugUpdateNodeDual(NodeIndex n, CostValue delta)
void AddEdgeWithCost(int tail, int head, int64_t cost)
const std::vector< int > & Matches() const
Collection of objects used to extend the Constraint Solver library.
int index
Definition: pack.cc:509
int64_t delta
Definition: resource.cc:1692
int64_t tail
int64_t cost
int64_t head
Edge(NodeIndex t, NodeIndex h, CostValue c)
bool operator>(const Edge &other) const
NodeIndex OtherEnd(NodeIndex n) const