OR-Tools  9.1
linear_assignment.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//
15// An implementation of a cost-scaling push-relabel algorithm for the
16// assignment problem (minimum-cost perfect bipartite matching), from
17// the paper of Goldberg and Kennedy (1995).
18//
19//
20// This implementation finds the minimum-cost perfect assignment in
21// the given graph with integral edge weights set through the
22// SetArcCost method.
23//
24// The running time is O(n*m*log(nC)) where n is the number of nodes,
25// m is the number of edges, and C is the largest magnitude of an edge cost.
26// In principle it can be worse than the Hungarian algorithm but we don't know
27// of any class of problems where that actually happens. An additional sqrt(n)
28// factor could be shaved off the running time bound using the technique
29// described in http://dx.doi.org/10.1137/S0895480194281185
30// (see also http://theory.stanford.edu/~robert/papers/glob_upd.ps).
31//
32//
33// Example usage:
34//
35// #include "ortools/graph/graph.h"
36// #include "ortools/graph/linear_assignment.h"
37//
38// // Choose a graph implementation (we recommend StaticGraph<>).
39// typedef util::StaticGraph<> Graph;
40//
41// // Define a num_nodes / 2 by num_nodes / 2 assignment problem:
42// const int num_nodes = ...
43// const int num_arcs = ...
44// const int num_left_nodes = num_nodes / 2;
45// Graph graph(num_nodes, num_arcs);
46// std::vector<operations_research::CostValue> arc_costs(num_arcs);
47// for (int arc = 0; arc < num_arcs; ++arc) {
48// const int arc_tail = ... // must be in [0, num_left_nodes)
49// const int arc_head = ... // must be in [num_left_nodes, num_nodes)
50// graph.AddArc(arc_tail, arc_head);
51// arc_costs[arc] = ...
52// }
53//
54// // Build the StaticGraph. You can skip this step by using a ListGraph<>
55// // instead, but then the ComputeAssignment() below will be slower. It is
56// // okay if your graph is small and performance is not critical though.
57// {
58// std::vector<Graph::ArcIndex> arc_permutation;
59// graph.Build(&arc_permutation);
60// util::Permute(arc_permutation, &arc_costs);
61// }
62//
63// // Construct the LinearSumAssignment.
64// ::operations_research::LinearSumAssignment<Graph> a(graph, num_left_nodes);
65// for (int arc = 0; arc < num_arcs; ++arc) {
66// // You can also replace 'arc_costs[arc]' by something like
67// // ComputeArcCost(permutation.empty() ? arc : permutation[arc])
68// // if you don't want to store the costs in arc_costs to save memory.
69// a.SetArcCost(arc, arc_costs[arc]);
70// }
71//
72// // Compute the optimum assignment.
73// bool success = a.ComputeAssignment();
74// // Retrieve the cost of the optimum assignment.
75// operations_research::CostValue optimum_cost = a.GetCost();
76// // Retrieve the node-node correspondence of the optimum assignment and the
77// // cost of each node pairing.
78// for (int left_node = 0; left_node < num_left_nodes; ++left_node) {
79// const int right_node = a.GetMate(left_node);
80// operations_research::CostValue node_pair_cost =
81// a.GetAssignmentCost(left_node);
82// ...
83// }
84//
85// In the following, we consider a bipartite graph
86// G = (V = X union Y, E subset XxY),
87// where V denotes the set of nodes (vertices) in the graph, E denotes
88// the set of arcs (edges), n = |V| denotes the number of nodes in the
89// graph, and m = |E| denotes the number of arcs in the graph.
90//
91// The set of nodes is divided into two parts, X and Y, and every arc
92// must go between a node of X and a node of Y. With each arc is
93// associated a cost c(v, w). A matching M is a subset of E with the
94// property that no two arcs in M have a head or tail node in common,
95// and a perfect matching is a matching that touches every node in the
96// graph. The cost of a matching M is the sum of the costs of all the
97// arcs in M.
98//
99// The assignment problem is to find a perfect matching of minimum
100// cost in the given bipartite graph. The present algorithm reduces
101// the assignment problem to an instance of the minimum-cost flow
102// problem and takes advantage of special properties of the resulting
103// minimum-cost flow problem to solve it efficiently using a
104// push-relabel method. For more information about minimum-cost flow
105// see ortools/graph/min_cost_flow.h
106//
107// The method used here is the cost-scaling approach for the
108// minimum-cost circulation problem as described in [Goldberg and
109// Tarjan] with some technical modifications:
110// 1. For efficiency, we solve a transportation problem instead of
111// minimum-cost circulation. We might revisit this decision if it
112// is important to handle problems in which no perfect matching
113// exists.
114// 2. We use a modified "asymmetric" notion of epsilon-optimality in
115// which left-to-right residual arcs are required to have reduced
116// cost bounded below by zero and right-to-left residual arcs are
117// required to have reduced cost bounded below by -epsilon. For
118// each residual arc direction, the reduced-cost threshold for
119// admissibility is epsilon/2 above the threshold for epsilon
120// optimality.
121// 3. We do not limit the applicability of the relabeling operation to
122// nodes with excess. Instead we use the double-push operation
123// (discussed in the Goldberg and Kennedy CSA paper and Kennedy's
124// thesis) which relabels right-side nodes just *after* they have
125// been discharged.
126// The above differences are explained in detail in [Kennedy's thesis]
127// and explained not quite as cleanly in [Goldberg and Kennedy's CSA
128// paper]. But note that the thesis explanation uses a value of
129// epsilon that's double what we use here.
130//
131// Some definitions:
132// Active: A node is called active when it has excess. It is
133// eligible to be pushed from. In this implementation, every active
134// node is on the left side of the graph where prices are determined
135// implicitly, so no left-side relabeling is necessary before
136// pushing from an active node. We do, however, need to compute
137// the implications for price changes on the affected right-side
138// nodes.
139// Admissible: A residual arc (one that can carry more flow) is
140// called admissible when its reduced cost is small enough. We can
141// push additional flow along such an arc without violating
142// epsilon-optimality. In the case of a left-to-right residual
143// arc, the reduced cost must be at most epsilon/2. In the case of
144// a right-to-left residual arc, the reduced cost must be at
145// most -epsilon/2. The careful reader will note that these thresholds
146// are not used explicitly anywhere in this implementation, and
147// the reason is the implicit pricing of left-side nodes.
148// Reduced cost: Essentially an arc's reduced cost is its
149// complementary slackness. In push-relabel algorithms this is
150// c_p(v, w) = p(v) + c(v, w) - p(w),
151// where p() is the node price function and c(v, w) is the cost of
152// the arc from v to w. See min_cost_flow.h for more details.
153// Partial reduced cost: We maintain prices implicitly for left-side
154// nodes in this implementation, so instead of reduced costs we
155// work with partial reduced costs, defined as
156// c'_p(v, w) = c(v, w) - p(w).
157//
158// We check at initialization time for the possibility of arithmetic
159// overflow and warn if the given costs are too large. In many cases
160// the bound we use to trigger the warning is pessimistic so the given
161// problem can often be solved even if we warn that overflow is
162// possible.
163//
164// We don't use the interface from
165// operations_research/algorithms/hungarian.h because we want to be
166// able to express sparse problems efficiently.
167//
168// When asked to solve the given assignment problem we return a
169// boolean to indicate whether the given problem was feasible.
170//
171// References:
172// [ Goldberg and Kennedy's CSA paper ] A. V. Goldberg and R. Kennedy,
173// "An Efficient Cost Scaling Algorithm for the Assignment Problem."
174// Mathematical Programming, Vol. 71, pages 153-178, December 1995.
175//
176// [ Goldberg and Tarjan ] A. V. Goldberg and R. E. Tarjan, "Finding
177// Minimum-Cost Circulations by Successive Approximation." Mathematics
178// of Operations Research, Vol. 15, No. 3, pages 430-466, August 1990.
179//
180// [ Kennedy's thesis ] J. R. Kennedy, Jr., "Solving Unweighted and
181// Weighted Bipartite Matching Problems in Theory and Practice."
182// Stanford University Doctoral Dissertation, Department of Computer
183// Science, 1995.
184//
185// [ Burkard et al. ] R. Burkard, M. Dell'Amico, S. Martello, "Assignment
186// Problems", SIAM, 2009, ISBN: 978-0898716634,
187// http://www.amazon.com/dp/0898716632/
188//
189// [ Ahuja et al. ] R. K. Ahuja, T. L. Magnanti, J. B. Orlin, "Network Flows:
190// Theory, Algorithms, and Applications," Prentice Hall, 1993,
191// ISBN: 978-0136175490, http://www.amazon.com/dp/013617549X.
192//
193// Keywords: linear sum assignment problem, Hungarian method, Goldberg, Kennedy.
194
195#ifndef OR_TOOLS_GRAPH_LINEAR_ASSIGNMENT_H_
196#define OR_TOOLS_GRAPH_LINEAR_ASSIGNMENT_H_
197
198#include <algorithm>
199#include <cstdint>
200#include <cstdlib>
201#include <deque>
202#include <limits>
203#include <memory>
204#include <string>
205#include <utility>
206#include <vector>
207
208#include "absl/strings/str_format.h"
211#include "ortools/base/logging.h"
212#include "ortools/base/macros.h"
215#include "ortools/util/zvector.h"
216
217#ifndef SWIG
218ABSL_DECLARE_FLAG(int64_t, assignment_alpha);
219ABSL_DECLARE_FLAG(int, assignment_progress_logging_period);
220ABSL_DECLARE_FLAG(bool, assignment_stack_order);
221#endif
222
223namespace operations_research {
224
225// This class does not take ownership of its underlying graph.
226template <typename GraphType>
228 public:
231
232 // Constructor for the case in which we will build the graph
233 // incrementally as we discover arc costs, as might be done with any
234 // of the dynamic graph representations such as StarGraph or ForwardStarGraph.
235 LinearSumAssignment(const GraphType& graph, NodeIndex num_left_nodes);
236
237 // Constructor for the case in which the underlying graph cannot be
238 // built until after all the arc costs are known, as is the case
239 // with ForwardStarStaticGraph. In this case, the graph is passed to
240 // us later via the SetGraph() method, below.
241 LinearSumAssignment(NodeIndex num_left_nodes, ArcIndex num_arcs);
242
244
245 // Sets the graph used by the LinearSumAssignment instance, for use
246 // when the graph layout can be determined only after arc costs are
247 // set. This happens, for example, when we use a ForwardStarStaticGraph.
248 void SetGraph(const GraphType* graph) {
249 DCHECK(graph_ == nullptr);
250 graph_ = graph;
251 }
252
253 // Sets the cost-scaling divisor, i.e., the amount by which we
254 // divide the scaling parameter on each iteration.
255 void SetCostScalingDivisor(CostValue factor) { alpha_ = factor; }
256
257 // Returns a permutation cycle handler that can be passed to the
258 // TransformToForwardStaticGraph method so that arc costs get
259 // permuted along with arcs themselves.
260 //
261 // Passes ownership of the cycle handler to the caller.
262 //
265
266 // Optimizes the layout of the graph for the access pattern our
267 // implementation will use.
268 //
269 // REQUIRES for LinearSumAssignment template instantiation if a call
270 // to the OptimizeGraphLayout() method is compiled: GraphType is a
271 // dynamic graph, i.e., one that implements the
272 // GroupForwardArcsByFunctor() member template method.
273 //
274 // If analogous optimization is needed for LinearSumAssignment
275 // instances based on static graphs, the graph layout should be
276 // constructed such that each node's outgoing arcs are sorted by
277 // head node index before the
278 // LinearSumAssignment<GraphType>::SetGraph() method is called.
279 void OptimizeGraphLayout(GraphType* graph);
280
281 // Allows tests, iterators, etc., to inspect our underlying graph.
282 inline const GraphType& Graph() const { return *graph_; }
283
284 // These handy member functions make the code more compact, and we
285 // expose them to clients so that client code that doesn't have
286 // direct access to the graph can learn about the optimum assignment
287 // once it is computed.
288 inline NodeIndex Head(ArcIndex arc) const { return graph_->Head(arc); }
289
290 // Returns the original arc cost for use by a client that's
291 // iterating over the optimum assignment.
293 DCHECK_EQ(0, scaled_arc_cost_[arc] % cost_scaling_factor_);
294 return scaled_arc_cost_[arc] / cost_scaling_factor_;
295 }
296
297 // Sets the cost of an arc already present in the given graph.
299
300 // Completes initialization after the problem is fully specified.
301 // Returns true if we successfully prove that arithmetic
302 // calculations are guaranteed not to overflow. ComputeAssignment()
303 // calls this method itself, so only clients that care about
304 // obtaining a warning about the possibility of arithmetic precision
305 // problems need to call this method explicitly.
306 //
307 // Separate from ComputeAssignment() for white-box testing and for
308 // clients that need to react to the possibility that arithmetic
309 // overflow is not ruled out.
310 //
311 // FinalizeSetup() is idempotent.
312 bool FinalizeSetup();
313
314 // Computes the optimum assignment. Returns true on success. Return
315 // value of false implies the given problem is infeasible.
316 bool ComputeAssignment();
317
318 // Returns the cost of the minimum-cost perfect matching.
319 // Precondition: success_ == true, signifying that we computed the
320 // optimum assignment for a feasible problem.
321 CostValue GetCost() const;
322
323 // Returns the total number of nodes in the given problem.
325 if (graph_ == nullptr) {
326 // Return a guess that must be true if ultimately we are given a
327 // feasible problem to solve.
328 return 2 * NumLeftNodes();
329 } else {
330 return graph_->num_nodes();
331 }
332 }
333
334 // Returns the number of nodes on the left side of the given
335 // problem.
336 NodeIndex NumLeftNodes() const { return num_left_nodes_; }
337
338 // Returns the arc through which the given node is matched.
339 inline ArcIndex GetAssignmentArc(NodeIndex left_node) const {
340 DCHECK_LT(left_node, num_left_nodes_);
341 return matched_arc_[left_node];
342 }
343
344 // Returns the cost of the assignment arc incident to the given
345 // node.
347 return ArcCost(GetAssignmentArc(node));
348 }
349
350 // Returns the node to which the given node is matched.
351 inline NodeIndex GetMate(NodeIndex left_node) const {
352 DCHECK_LT(left_node, num_left_nodes_);
353 ArcIndex matching_arc = GetAssignmentArc(left_node);
354 DCHECK_NE(GraphType::kNilArc, matching_arc);
355 return Head(matching_arc);
356 }
357
358 std::string StatsString() const { return total_stats_.StatsString(); }
359
361 public:
362 BipartiteLeftNodeIterator(const GraphType& graph, NodeIndex num_left_nodes)
363 : num_left_nodes_(num_left_nodes), node_iterator_(0) {}
364
366 : num_left_nodes_(assignment.NumLeftNodes()), node_iterator_(0) {}
367
368 NodeIndex Index() const { return node_iterator_; }
369
370 bool Ok() const { return node_iterator_ < num_left_nodes_; }
371
372 void Next() { ++node_iterator_; }
373
374 private:
375 const NodeIndex num_left_nodes_;
376 typename GraphType::NodeIndex node_iterator_;
377 };
378
379 private:
380 struct Stats {
381 Stats() : pushes_(0), double_pushes_(0), relabelings_(0), refinements_(0) {}
382 void Clear() {
383 pushes_ = 0;
384 double_pushes_ = 0;
385 relabelings_ = 0;
386 refinements_ = 0;
387 }
388 void Add(const Stats& that) {
389 pushes_ += that.pushes_;
390 double_pushes_ += that.double_pushes_;
391 relabelings_ += that.relabelings_;
392 refinements_ += that.refinements_;
393 }
394 std::string StatsString() const {
395 return absl::StrFormat(
396 "%d refinements; %d relabelings; "
397 "%d double pushes; %d pushes",
398 refinements_, relabelings_, double_pushes_, pushes_);
399 }
400 int64_t pushes_;
401 int64_t double_pushes_;
402 int64_t relabelings_;
403 int64_t refinements_;
404 };
405
406#ifndef SWIG
407 class ActiveNodeContainerInterface {
408 public:
409 virtual ~ActiveNodeContainerInterface() {}
410 virtual bool Empty() const = 0;
411 virtual void Add(NodeIndex node) = 0;
412 virtual NodeIndex Get() = 0;
413 };
414
415 class ActiveNodeStack : public ActiveNodeContainerInterface {
416 public:
417 ~ActiveNodeStack() override {}
418
419 bool Empty() const override { return v_.empty(); }
420
421 void Add(NodeIndex node) override { v_.push_back(node); }
422
423 NodeIndex Get() override {
424 DCHECK(!Empty());
425 NodeIndex result = v_.back();
426 v_.pop_back();
427 return result;
428 }
429
430 private:
431 std::vector<NodeIndex> v_;
432 };
433
434 class ActiveNodeQueue : public ActiveNodeContainerInterface {
435 public:
436 ~ActiveNodeQueue() override {}
437
438 bool Empty() const override { return q_.empty(); }
439
440 void Add(NodeIndex node) override { q_.push_front(node); }
441
442 NodeIndex Get() override {
443 DCHECK(!Empty());
444 NodeIndex result = q_.back();
445 q_.pop_back();
446 return result;
447 }
448
449 private:
450 std::deque<NodeIndex> q_;
451 };
452#endif
453
454 // Type definition for a pair
455 // (arc index, reduced cost gap)
456 // giving the arc along which we will push from a given left-side
457 // node and the gap between that arc's partial reduced cost and the
458 // reduced cost of the next-best (necessarily residual) arc out of
459 // the node. This information helps us efficiently relabel
460 // right-side nodes during DoublePush operations.
461 typedef std::pair<ArcIndex, CostValue> ImplicitPriceSummary;
462
463 // Returns true if and only if the current pseudoflow is
464 // epsilon-optimal. To be used in a DCHECK.
465 bool EpsilonOptimal() const;
466
467 // Checks that all nodes are matched.
468 // To be used in a DCHECK.
469 bool AllMatched() const;
470
471 // Calculates the implicit price of the given node.
472 // Only for debugging, for use in EpsilonOptimal().
473 inline CostValue ImplicitPrice(NodeIndex left_node) const;
474
475 // For use by DoublePush()
476 inline ImplicitPriceSummary BestArcAndGap(NodeIndex left_node) const;
477
478 // Accumulates stats between iterations and reports them if the
479 // verbosity level is high enough.
480 void ReportAndAccumulateStats();
481
482 // Utility function to compute the next error parameter value. This
483 // is used to ensure that the same sequence of error parameter
484 // values is used for computation of price bounds as is used for
485 // computing the optimum assignment.
486 CostValue NewEpsilon(CostValue current_epsilon) const;
487
488 // Advances internal state to prepare for the next scaling
489 // iteration. Returns false if infeasibility is detected, true
490 // otherwise.
491 bool UpdateEpsilon();
492
493 // Indicates whether the given left_node has positive excess. Called
494 // only for nodes on the left side.
495 inline bool IsActive(NodeIndex left_node) const;
496
497 // Indicates whether the given node has nonzero excess. The idea
498 // here is the same as the IsActive method above, but that method
499 // contains a safety DCHECK() that its argument is a left-side node,
500 // while this method is usable for any node.
501 // To be used in a DCHECK.
502 inline bool IsActiveForDebugging(NodeIndex node) const;
503
504 // Performs the push/relabel work for one scaling iteration.
505 bool Refine();
506
507 // Puts all left-side nodes in the active set in preparation for the
508 // first scaling iteration.
509 void InitializeActiveNodeContainer();
510
511 // Saturates all negative-reduced-cost arcs at the beginning of each
512 // scaling iteration. Note that according to the asymmetric
513 // definition of admissibility, this action is different from
514 // saturating all admissible arcs (which we never do). All negative
515 // arcs are admissible, but not all admissible arcs are negative. It
516 // is alwsys enough to saturate only the negative ones.
517 void SaturateNegativeArcs();
518
519 // Performs an optimized sequence of pushing a unit of excess out of
520 // the left-side node v and back to another left-side node if no
521 // deficit is cancelled with the first push.
522 bool DoublePush(NodeIndex source);
523
524 // Returns the partial reduced cost of the given arc.
525 inline CostValue PartialReducedCost(ArcIndex arc) const {
526 return scaled_arc_cost_[arc] - price_[Head(arc)];
527 }
528
529 // The graph underlying the problem definition we are given. Not
530 // owned by *this.
531 const GraphType* graph_;
532
533 // The number of nodes on the left side of the graph we are given.
534 NodeIndex num_left_nodes_;
535
536 // A flag indicating, after FinalizeSetup() has run, whether the
537 // arc-incidence precondition required by BestArcAndGap() is
538 // satisfied by every left-side node. If not, the problem is
539 // infeasible.
540 bool incidence_precondition_satisfied_;
541
542 // A flag indicating that an optimal perfect matching has been computed.
543 bool success_;
544
545 // The value by which we multiply all the arc costs we are given in
546 // order to be able to use integer arithmetic in all our
547 // computations. In order to establish optimality of the final
548 // matching we compute, we need that
549 // (cost_scaling_factor_ / kMinEpsilon) > graph_->num_nodes().
550 const CostValue cost_scaling_factor_;
551
552 // Scaling divisor.
553 CostValue alpha_;
554
555 // Minimum value of epsilon. When a flow is epsilon-optimal for
556 // epsilon == kMinEpsilon, the flow is optimal.
557 static const CostValue kMinEpsilon;
558
559 // Current value of epsilon, the cost scaling parameter.
560 CostValue epsilon_;
561
562 // The following two data members, price_lower_bound_ and
563 // slack_relabeling_price_, have to do with bounds on the amount by
564 // which node prices can change during execution of the algorithm.
565 // We need some detailed discussion of this topic because we violate
566 // several simplifying assumptions typically made in the theoretical
567 // literature. In particular, we use integer arithmetic, we use a
568 // reduction to the transportation problem rather than min-cost
569 // circulation, we provide detection of infeasible problems rather
570 // than assume feasibility, we detect when our computations might
571 // exceed the range of representable cost values, and we use the
572 // double-push heuristic which relabels nodes that do not have
573 // excess.
574 //
575 // In the following discussion, we prove the following propositions:
576 // Proposition 1. [Fidelity of arithmetic precision guarantee] If
577 // FinalizeSetup() returns true, no arithmetic
578 // overflow occurs during ComputeAssignment().
579 // Proposition 2. [Fidelity of feasibility detection] If no
580 // arithmetic overflow occurs during
581 // ComputeAssignment(), the return value of
582 // ComputeAssignment() faithfully indicates whether
583 // the given problem is feasible.
584 //
585 // We begin with some general discussion.
586 //
587 // The ideas used to prove our two propositions are essentially
588 // those that appear in [Goldberg and Tarjan], but several details
589 // are different: [Goldberg and Tarjan] assumes a feasible problem,
590 // uses a symmetric notion of epsilon-optimality, considers only
591 // nodes with excess eligible for relabeling, and does not treat the
592 // question of arithmetic overflow. This implementation, on the
593 // other hand, detects and reports infeasible problems, uses
594 // asymmetric epsilon-optimality, relabels nodes with no excess in
595 // the course of the double-push operation, and gives a reasonably
596 // tight guarantee of arithmetic precision. No fundamentally new
597 // ideas are involved, but the details are a bit tricky so they are
598 // explained here.
599 //
600 // We have two intertwined needs that lead us to compute bounds on
601 // the prices nodes can have during the assignment computation, on
602 // the assumption that the given problem is feasible:
603 // 1. Infeasibility detection: Infeasibility is detected by
604 // observing that some node's price has been reduced too much by
605 // relabeling operations (see [Goldberg and Tarjan] for the
606 // argument -- duplicated in modified form below -- bounding the
607 // running time of the push/relabel min-cost flow algorithm for
608 // feasible problems); and
609 // 2. Aggressively relabeling nodes and arcs whose matching is
610 // forced: When a left-side node is incident to only one arc a,
611 // any feasible solution must include a, and reducing the price
612 // of Head(a) by any nonnegative amount preserves epsilon-
613 // optimality. Because of this freedom, we'll call this sort of
614 // relabeling (i.e., a relabeling of a right-side node that is
615 // the only neighbor of the left-side node to which it has been
616 // matched in the present double-push operation) a "slack"
617 // relabeling. Relabelings that are not slack relabelings are
618 // called "confined" relabelings. By relabeling Head(a) to have
619 // p(Head(a))=-infinity, we could guarantee that a never becomes
620 // unmatched during the current iteration, and this would prevent
621 // our wasting time repeatedly unmatching and rematching a. But
622 // there are some details we need to handle:
623 // a. The CostValue type cannot represent -infinity;
624 // b. Low node prices are precisely the signal we use to detect
625 // infeasibility (see (1)), so we must be careful not to
626 // falsely conclude that the problem is infeasible as a result
627 // of the low price we gave Head(a); and
628 // c. We need to indicate accurately to the client when our best
629 // understanding indicates that we can't rule out arithmetic
630 // overflow in our calculations. Most importantly, if we don't
631 // warn the client, we must be certain to avoid overflow. This
632 // means our slack relabelings must not be so aggressive as to
633 // create the possibility of unforeseen overflow. Although we
634 // will not achieve this in practice, slack relabelings would
635 // ideally not introduce overflow unless overflow was
636 // inevitable were even the smallest reasonable price change
637 // (== epsilon) used for slack relabelings.
638 // Using the analysis below, we choose a finite amount of price
639 // change for slack relabelings aggressive enough that we don't
640 // waste time doing repeated slack relabelings in a single
641 // iteration, yet modest enough that we keep a good handle on
642 // arithmetic precision and our ability to detect infeasible
643 // problems.
644 //
645 // To provide faithful detection of infeasibility, a dependable
646 // guarantee of arithmetic precision whenever possible, and good
647 // performance by aggressively relabeling nodes whose matching is
648 // forced, we exploit these facts:
649 // 1. Beyond the first iteration, infeasibility detection isn't needed
650 // because a problem is feasible in some iteration if and only if
651 // it's feasible in all others. Therefore we are free to use an
652 // infeasibility detection mechanism that might work in just one
653 // iteration and switch it off in all other iterations.
654 // 2. When we do a slack relabeling, we must choose the amount of
655 // price reduction to use. We choose an amount large enough to
656 // guarantee putting the node's matching to rest, yet (although
657 // we don't bother to prove this explicitly) small enough that
658 // the node's price obeys the overall lower bound that holds if
659 // the slack relabeling amount is small.
660 //
661 // We will establish Propositions (1) and (2) above according to the
662 // following steps:
663 // First, we prove Lemma 1, which is a modified form of lemma 5.8 of
664 // [Goldberg and Tarjan] giving a bound on the difference in price
665 // between the end nodes of certain paths in the residual graph.
666 // Second, we prove Lemma 2, which is technical lemma to establish
667 // reachability of certain "anchor" nodes in the residual graph from
668 // any node where a relabeling takes place.
669 // Third, we apply the first two lemmas to prove Lemma 3 and Lemma
670 // 4, which give two similar bounds that hold whenever the given
671 // problem is feasible: (for feasibility detection) a bound on the
672 // price of any node we relabel during any iteration (and the first
673 // iteration in particular), and (for arithmetic precision) a bound
674 // on the price of any node we relabel during the entire algorithm.
675 //
676 // Finally, we note that if the whole-algorithm price bound can be
677 // represented precisely by the CostValue type, arithmetic overflow
678 // cannot occur (establishing Proposition 1), and assuming no
679 // overflow occurs during the first iteration, any violation of the
680 // first-iteration price bound establishes infeasibility
681 // (Proposition 2).
682 //
683 // The statement of Lemma 1 is perhaps easier to understand when the
684 // reader knows how it will be used. To wit: In this lemma, f' and
685 // e_0 are the flow and error parameter (epsilon) at the beginning
686 // of the current iteration, while f and e_1 are the current
687 // pseudoflow and error parameter when a relabeling of interest
688 // occurs. Without loss of generality, c is the reduced cost
689 // function at the beginning of the current iteration and p is the
690 // change in prices that has taken place in the current iteration.
691 //
692 // Lemma 1 (a variant of lemma 5.8 from [Goldberg and Tarjan]): Let
693 // f be a pseudoflow and let f' be a flow. Suppose P is a simple
694 // path from right-side node v to right-side node w such that P is
695 // residual with respect to f and reverse(P) is residual with
696 // respect to f'. Further, suppose c is an arc cost function with
697 // respect to which f' is e_0-optimal with the zero price function
698 // and p is a price function with respect to which f is e_1-optimal
699 // with respect to p. Then
700 // p(v) - p(w) >= -(e_0 + e_1) * (n-2)/2. (***)
701 //
702 // Proof: We have c_p(P) = p(v) + c(P) - p(w) and hence
703 // p(v) - p(w) = c_p(P) - c(P).
704 // So we seek a bound on c_p(P) - c(P).
705 // p(v) = c_p(P) - c(P).
706 // Let arc a lie on P, which implies that a is residual with respect
707 // to f and reverse(a) is residual with respect to f'.
708 // Case 1: a is a forward arc. Then by e_1-optimality of f with
709 // respect to p, c_p(a) >= 0 and reverse(a) is residual with
710 // respect to f'. By e_0-optimality of f', c(a) <= e_0. So
711 // c_p(a) - c(a) >= -e_0.
712 // Case 2: a is a reverse arc. Then by e_1-optimality of f with
713 // respect to p, c_p(a) >= -e_1 and reverse(a) is residual
714 // with respect to f'. By e_0-optimality of f', c(a) <= 0.
715 // So
716 // c_p(a) - c(a) >= -e_1.
717 // We assumed v and w are both right-side nodes, so there are at
718 // most n - 2 arcs on the path P, of which at most (n-2)/2 are
719 // forward arcs and at most (n-2)/2 are reverse arcs, so
720 // p(v) - p(w) = c_p(P) - c(P)
721 // >= -(e_0 + e_1) * (n-2)/2. (***)
722 //
723 // Some of the rest of our argument is given as a sketch, omitting
724 // several details. Also elided here are some minor technical issues
725 // related to the first iteration, inasmuch as our arguments assume
726 // on the surface a "previous iteration" that doesn't exist in that
727 // case. The issues are not substantial, just a bit messy.
728 //
729 // Lemma 2 is analogous to lemma 5.7 of [Goldberg and Tarjan], where
730 // they have only relabelings that take place at nodes with excess
731 // while we have only relabelings that take place as part of the
732 // double-push operation at nodes without excess.
733 //
734 // Lemma 2: If the problem is feasible, for any node v with excess,
735 // there exists a path P from v to a node w with deficit such that P
736 // is residual with respect to the current pseudoflow, and
737 // reverse(P) is residual with respect to the flow at the beginning
738 // of the current iteration. (Note that such a path exactly
739 // satisfies the conditions of Lemma 1.)
740 //
741 // Let the bound from Lemma 1 with p(w) = 0 be called B(e_0, e_1),
742 // and let us say that when a slack relabeling of a node v occurs,
743 // we will change the price of v by B(e_0, e_1) such that v tightly
744 // satisfies the bound of Lemma 1. Explicitly, we define
745 // B(e_0, e_1) = -(e_0 + e_1) * (n-2)/2.
746 //
747 // Lemma 1 and Lemma 2 combine to bound the price change during an
748 // iteration for any node with excess. Viewed a different way, Lemma
749 // 1 and Lemma 2 tell us that if epsilon-optimality can be preserved
750 // by changing the price of a node by B(e_0, e_1), that node will
751 // never have excess again during the current iteration unless the
752 // problem is infeasible. This insight gives us an approach to
753 // detect infeasibility (by observing prices on nodes with excess
754 // that violate this bound) and to relabel nodes aggressively enough
755 // to avoid unnecessary future work while we also avoid falsely
756 // concluding the problem is infeasible.
757 //
758 // From Lemma 1 and Lemma 2, and taking into account our knowledge
759 // of the slack relabeling amount, we have Lemma 3.
760 //
761 // Lemma 3: During any iteration, if the given problem is feasible
762 // the price of any node is reduced by less than
763 // -2 * B(e_0, e_1) = (e_0 + e_1) * (n-2).
764 //
765 // Proof: Straightforward, omitted for expedience.
766 //
767 // In the case where e_0 = e_1 * alpha, we can express the bound
768 // just in terms of e_1, the current iteration's value of epsilon_:
769 // B(e_1) = B(e_1 * alpha, e_1) = -(1 + alpha) * e_1 * (n-2)/2,
770 // so we have that p(v) is reduced by less than 2 * B(e_1).
771 //
772 // Because we use truncating division to compute each iteration's error
773 // parameter from that of the previous iteration, it isn't exactly
774 // the case that e_0 = e_1 * alpha as we just assumed. To patch this
775 // up, we can use the observation that
776 // e_1 = floor(e_0 / alpha),
777 // which implies
778 // -e_0 > -(e_1 + 1) * alpha
779 // to rewrite from (***):
780 // p(v) > 2 * B(e_0, e_1) > 2 * B((e_1 + 1) * alpha, e_1)
781 // = 2 * -((e_1 + 1) * alpha + e_1) * (n-2)/2
782 // = 2 * -(1 + alpha) * e_1 * (n-2)/2 - alpha * (n-2)
783 // = 2 * B(e_1) - alpha * (n-2)
784 // = -((1 + alpha) * e_1 + alpha) * (n-2).
785 //
786 // We sum up the bounds for all the iterations to get Lemma 4:
787 //
788 // Lemma 4: If the given problem is feasible, after k iterations the
789 // price of any node is always greater than
790 // -((1 + alpha) * C + (k * alpha)) * (n-2)
791 //
792 // Proof: Suppose the price decrease of every node in the iteration
793 // with epsilon_ == x is bounded by B(x) which is proportional to x
794 // (not surprisingly, this will be the same function B() as
795 // above). Assume for simplicity that C, the largest cost magnitude,
796 // is a power of alpha. Then the price of each node, tallied across
797 // all iterations is bounded
798 // p(v) > 2 * B(C/alpha) + 2 * B(C/alpha^2) + ... + 2 * B(kMinEpsilon)
799 // == 2 * B(C/alpha) * alpha / (alpha - 1)
800 // == 2 * B(C) / (alpha - 1).
801 // As above, this needs some patching up to handle the fact that we
802 // use truncating arithmetic. We saw that each iteration effectively
803 // reduces the price bound by alpha * (n-2), hence if there are k
804 // iterations, the bound is
805 // p(v) > 2 * B(C) / (alpha - 1) - k * alpha * (n-2)
806 // = -(1 + alpha) * C * (n-2) / (alpha - 1) - k * alpha * (n-2)
807 // = (n-2) * (C * (1 + alpha) / (1 - alpha) - k * alpha).
808 //
809 // The bound of lemma 4 can be used to warn for possible overflow of
810 // arithmetic precision. But because it involves the number of
811 // iterations, k, we might as well count through the iterations
812 // simply adding up the bounds given by Lemma 3 to get a tighter
813 // result. This is what the implementation does.
814
815 // A lower bound on the price of any node at any time throughout the
816 // computation. A price below this level proves infeasibility; this
817 // value is used for feasibility detection. We use this value also
818 // to rule out the possibility of arithmetic overflow or warn the
819 // client that we have not been able to rule out that possibility.
820 //
821 // We can use the value implied by Lemma 4 here, but note that that
822 // value includes k, the number of iterations. It's plenty fast if
823 // we count through the iterations to compute that value, but if
824 // we're going to count through the iterations, we might as well use
825 // the two-parameter bound from Lemma 3, summing up as we go. This
826 // gives us a tighter bound and more comprehensible code.
827 //
828 // While computing this bound, if we find the value justified by the
829 // theory lies outside the representable range of CostValue, we
830 // conclude that the given arc costs have magnitudes so large that
831 // we cannot guarantee our calculations don't overflow. If the value
832 // justified by the theory lies inside the representable range of
833 // CostValue, we commit that our calculation will not overflow. This
834 // commitment means we need to be careful with the amount by which
835 // we relabel right-side nodes that are incident to any node with
836 // only one neighbor.
837 CostValue price_lower_bound_;
838
839 // A bound on the amount by which a node's price can be reduced
840 // during the current iteration, used only for slack
841 // relabelings. Where epsilon is the first iteration's error
842 // parameter and C is the largest magnitude of an arc cost, we set
843 // slack_relabeling_price_ = -B(C, epsilon)
844 // = (C + epsilon) * (n-2)/2.
845 //
846 // We could use slack_relabeling_price_ for feasibility detection
847 // but the feasibility threshold is double the slack relabeling
848 // amount and we judge it not to be worth having to multiply by two
849 // gratuitously to check feasibility in each double push
850 // operation. Instead we settle for feasibility detection using
851 // price_lower_bound_ instead, which is somewhat slower in the
852 // infeasible case because more relabelings will be required for
853 // some node price to attain the looser bound.
854 CostValue slack_relabeling_price_;
855
856 // Computes the value of the bound on price reduction for an
857 // iteration, given the old and new values of epsilon_. Because the
858 // expression computed here is used in at least one place where we
859 // want an additional factor in the denominator, we take that factor
860 // as an argument. If extra_divisor == 1, this function computes of
861 // the function B() discussed above.
862 //
863 // Avoids overflow in computing the bound, and sets *in_range =
864 // false if the value of the bound doesn't fit in CostValue.
865 inline CostValue PriceChangeBound(CostValue old_epsilon,
866 CostValue new_epsilon,
867 bool* in_range) const {
868 const CostValue n = graph_->num_nodes();
869 // We work in double-precision floating point to determine whether
870 // we'll overflow the integral CostValue type's range of
871 // representation. Switching between integer and double is a
872 // rather expensive operation, but we do this only twice per
873 // scaling iteration, so we can afford it rather than resort to
874 // complex and subtle tricks within the bounds of integer
875 // arithmetic.
876 //
877 // You will want to read the comments above about
878 // price_lower_bound_ and slack_relabeling_price_, and have a
879 // pencil handy. :-)
880 const double result =
881 static_cast<double>(std::max<CostValue>(1, n / 2 - 1)) *
882 (static_cast<double>(old_epsilon) + static_cast<double>(new_epsilon));
883 const double limit =
884 static_cast<double>(std::numeric_limits<CostValue>::max());
885 if (result > limit) {
886 // Our integer computations could overflow.
887 if (in_range != nullptr) *in_range = false;
889 } else {
890 // Don't touch *in_range; other computations could already have
891 // set it to false and we don't want to overwrite that result.
892 return static_cast<CostValue>(result);
893 }
894 }
895
896 // A scaled record of the largest arc-cost magnitude we've been
897 // given during problem setup. This is used to set the initial value
898 // of epsilon_, which in turn is used not only as the error
899 // parameter but also to determine whether we risk arithmetic
900 // overflow during the algorithm.
901 //
902 // Note: Our treatment of arithmetic overflow assumes the following
903 // property of CostValue:
904 // -std::numeric_limits<CostValue>::max() is a representable
905 // CostValue.
906 // That property is satisfied if CostValue uses a two's-complement
907 // representation.
908 CostValue largest_scaled_cost_magnitude_;
909
910 // The total excess in the graph. Given our asymmetric definition of
911 // epsilon-optimality and our use of the double-push operation, this
912 // equals the number of unmatched left-side nodes.
913 NodeIndex total_excess_;
914
915 // Indexed by node index, the price_ values are maintained only for
916 // right-side nodes.
917 //
918 // Note: We use a ZVector to only allocate a vector of size num_left_nodes_
919 // instead of 2*num_left_nodes_ since the right-side node indices start at
920 // num_left_nodes_.
921 ZVector<CostValue> price_;
922
923 // Indexed by left-side node index, the matched_arc_ array gives the
924 // arc index of the arc matching any given left-side node, or
925 // GraphType::kNilArc if the node is unmatched.
926 std::vector<ArcIndex> matched_arc_;
927
928 // Indexed by right-side node index, the matched_node_ array gives
929 // the node index of the left-side node matching any given
930 // right-side node, or GraphType::kNilNode if the right-side node is
931 // unmatched.
932 //
933 // Note: We use a ZVector for the same reason as for price_.
934 ZVector<NodeIndex> matched_node_;
935
936 // The array of arc costs as given in the problem definition, except
937 // that they are scaled up by the number of nodes in the graph so we
938 // can use integer arithmetic throughout.
939 std::vector<CostValue> scaled_arc_cost_;
940
941 // The container of active nodes (i.e., unmatched nodes). This can
942 // be switched easily between ActiveNodeStack and ActiveNodeQueue
943 // for experimentation.
944 std::unique_ptr<ActiveNodeContainerInterface> active_nodes_;
945
946 // Statistics giving the overall numbers of various operations the
947 // algorithm performs.
948 Stats total_stats_;
949
950 // Statistics giving the numbers of various operations the algorithm
951 // has performed in the current iteration.
952 Stats iteration_stats_;
953
954 DISALLOW_COPY_AND_ASSIGN(LinearSumAssignment);
955};
956
957// Implementation of out-of-line LinearSumAssignment template member
958// functions.
959
960template <typename GraphType>
961const CostValue LinearSumAssignment<GraphType>::kMinEpsilon = 1;
962
963template <typename GraphType>
965 const GraphType& graph, const NodeIndex num_left_nodes)
966 : graph_(&graph),
967 num_left_nodes_(num_left_nodes),
968 success_(false),
969 cost_scaling_factor_(1 + num_left_nodes),
970 alpha_(absl::GetFlag(FLAGS_assignment_alpha)),
971 epsilon_(0),
972 price_lower_bound_(0),
973 slack_relabeling_price_(0),
974 largest_scaled_cost_magnitude_(0),
975 total_excess_(0),
976 price_(num_left_nodes, 2 * num_left_nodes - 1),
977 matched_arc_(num_left_nodes, 0),
978 matched_node_(num_left_nodes, 2 * num_left_nodes - 1),
979 scaled_arc_cost_(graph.max_end_arc_index(), 0),
980 active_nodes_(absl::GetFlag(FLAGS_assignment_stack_order)
981 ? static_cast<ActiveNodeContainerInterface*>(
982 new ActiveNodeStack())
983 : static_cast<ActiveNodeContainerInterface*>(
984 new ActiveNodeQueue())) {}
985
986template <typename GraphType>
988 const NodeIndex num_left_nodes, const ArcIndex num_arcs)
989 : graph_(nullptr),
990 num_left_nodes_(num_left_nodes),
991 success_(false),
992 cost_scaling_factor_(1 + num_left_nodes),
993 alpha_(absl::GetFlag(FLAGS_assignment_alpha)),
994 epsilon_(0),
995 price_lower_bound_(0),
996 slack_relabeling_price_(0),
997 largest_scaled_cost_magnitude_(0),
998 total_excess_(0),
999 price_(num_left_nodes, 2 * num_left_nodes - 1),
1000 matched_arc_(num_left_nodes, 0),
1001 matched_node_(num_left_nodes, 2 * num_left_nodes - 1),
1002 scaled_arc_cost_(num_arcs, 0),
1003 active_nodes_(absl::GetFlag(FLAGS_assignment_stack_order)
1004 ? static_cast<ActiveNodeContainerInterface*>(
1005 new ActiveNodeStack())
1006 : static_cast<ActiveNodeContainerInterface*>(
1007 new ActiveNodeQueue())) {}
1008
1009template <typename GraphType>
1011 if (graph_ != nullptr) {
1012 DCHECK_GE(arc, 0);
1013 DCHECK_LT(arc, graph_->num_arcs());
1014 NodeIndex head = Head(arc);
1015 DCHECK_LE(num_left_nodes_, head);
1016 }
1017 cost *= cost_scaling_factor_;
1018 const CostValue cost_magnitude = std::abs(cost);
1019 largest_scaled_cost_magnitude_ =
1020 std::max(largest_scaled_cost_magnitude_, cost_magnitude);
1021 scaled_arc_cost_[arc] = cost;
1022}
1023
1024template <typename ArcIndexType>
1026 public:
1027 explicit CostValueCycleHandler(std::vector<CostValue>* cost)
1028 : temp_(0), cost_(cost) {}
1029
1030 void SetTempFromIndex(ArcIndexType source) override {
1031 temp_ = (*cost_)[source];
1032 }
1033
1034 void SetIndexFromIndex(ArcIndexType source,
1035 ArcIndexType destination) const override {
1036 (*cost_)[destination] = (*cost_)[source];
1037 }
1038
1039 void SetIndexFromTemp(ArcIndexType destination) const override {
1040 (*cost_)[destination] = temp_;
1041 }
1042
1044
1045 private:
1046 CostValue temp_;
1047 std::vector<CostValue>* const cost_;
1048
1049 DISALLOW_COPY_AND_ASSIGN(CostValueCycleHandler);
1050};
1051
1052// Logically this class should be defined inside OptimizeGraphLayout,
1053// but compilation fails if we do that because C++98 doesn't allow
1054// instantiation of member templates with function-scoped types as
1055// template parameters, which in turn is because those function-scoped
1056// types lack linkage.
1057template <typename GraphType>
1059 public:
1060 explicit ArcIndexOrderingByTailNode(const GraphType& graph) : graph_(graph) {}
1061
1062 // Says ArcIndex a is less than ArcIndex b if arc a's tail is less
1063 // than arc b's tail. If their tails are equal, orders according to
1064 // heads.
1066 typename GraphType::ArcIndex b) const {
1067 return ((graph_.Tail(a) < graph_.Tail(b)) ||
1068 ((graph_.Tail(a) == graph_.Tail(b)) &&
1069 (graph_.Head(a) < graph_.Head(b))));
1070 }
1071
1072 private:
1073 const GraphType& graph_;
1074
1075 // Copy and assign are allowed; they have to be for STL to work
1076 // with this functor, although it seems like a bug for STL to be
1077 // written that way.
1078};
1079
1080// Passes ownership of the cycle handler to the caller.
1081template <typename GraphType>
1082PermutationCycleHandler<typename GraphType::ArcIndex>*
1085 &scaled_arc_cost_);
1086}
1087
1088template <typename GraphType>
1090 // The graph argument is only to give us a non-const-qualified
1091 // handle on the graph we already have. Any different graph is
1092 // nonsense.
1093 DCHECK_EQ(graph_, graph);
1094 const ArcIndexOrderingByTailNode<GraphType> compare(*graph_);
1096 &scaled_arc_cost_);
1097 TailArrayManager<GraphType> tail_array_manager(graph);
1099 graph->GroupForwardArcsByFunctor(compare, &cycle_handler);
1100 tail_array_manager.ReleaseTailArrayIfForwardGraph();
1101}
1102
1103template <typename GraphType>
1105 const CostValue current_epsilon) const {
1106 return std::max(current_epsilon / alpha_, kMinEpsilon);
1107}
1108
1109template <typename GraphType>
1110bool LinearSumAssignment<GraphType>::UpdateEpsilon() {
1111 CostValue new_epsilon = NewEpsilon(epsilon_);
1112 slack_relabeling_price_ = PriceChangeBound(epsilon_, new_epsilon, nullptr);
1113 epsilon_ = new_epsilon;
1114 VLOG(3) << "Updated: epsilon_ == " << epsilon_;
1115 VLOG(4) << "slack_relabeling_price_ == " << slack_relabeling_price_;
1116 DCHECK_GT(slack_relabeling_price_, 0);
1117 // For today we always return true; in the future updating epsilon
1118 // in sophisticated ways could conceivably detect infeasibility
1119 // before the first iteration of Refine().
1120 return true;
1121}
1122
1123// For production code that checks whether a left-side node is active.
1124template <typename GraphType>
1125inline bool LinearSumAssignment<GraphType>::IsActive(
1126 NodeIndex left_node) const {
1127 DCHECK_LT(left_node, num_left_nodes_);
1128 return matched_arc_[left_node] == GraphType::kNilArc;
1129}
1130
1131// Only for debugging. Separate from the production IsActive() method
1132// so that method can assert that its argument is a left-side node,
1133// while for debugging we need to be able to test any node.
1134template <typename GraphType>
1135inline bool LinearSumAssignment<GraphType>::IsActiveForDebugging(
1136 NodeIndex node) const {
1137 if (node < num_left_nodes_) {
1138 return IsActive(node);
1139 } else {
1140 return matched_node_[node] == GraphType::kNilNode;
1141 }
1142}
1143
1144template <typename GraphType>
1145void LinearSumAssignment<GraphType>::InitializeActiveNodeContainer() {
1146 DCHECK(active_nodes_->Empty());
1147 for (BipartiteLeftNodeIterator node_it(*graph_, num_left_nodes_);
1148 node_it.Ok(); node_it.Next()) {
1149 const NodeIndex node = node_it.Index();
1150 if (IsActive(node)) {
1151 active_nodes_->Add(node);
1152 }
1153 }
1154}
1155
1156// There exists a price function such that the admissible arcs at the
1157// beginning of an iteration are exactly the reverse arcs of all
1158// matching arcs. Saturating all admissible arcs with respect to that
1159// price function therefore means simply unmatching every matched
1160// node.
1161//
1162// In the future we will price out arcs, which will reduce the set of
1163// nodes we unmatch here. If a matching arc is priced out, we will not
1164// unmatch its endpoints since that element of the matching is
1165// guaranteed not to change.
1166template <typename GraphType>
1167void LinearSumAssignment<GraphType>::SaturateNegativeArcs() {
1168 total_excess_ = 0;
1169 for (BipartiteLeftNodeIterator node_it(*graph_, num_left_nodes_);
1170 node_it.Ok(); node_it.Next()) {
1171 const NodeIndex node = node_it.Index();
1172 if (IsActive(node)) {
1173 // This can happen in the first iteration when nothing is
1174 // matched yet.
1175 total_excess_ += 1;
1176 } else {
1177 // We're about to create a unit of excess by unmatching these nodes.
1178 total_excess_ += 1;
1179 const NodeIndex mate = GetMate(node);
1180 matched_arc_[node] = GraphType::kNilArc;
1181 matched_node_[mate] = GraphType::kNilNode;
1182 }
1183 }
1184}
1185
1186// Returns true for success, false for infeasible.
1187template <typename GraphType>
1188bool LinearSumAssignment<GraphType>::DoublePush(NodeIndex source) {
1189 DCHECK_GT(num_left_nodes_, source);
1190 DCHECK(IsActive(source)) << "Node " << source
1191 << "must be active (unmatched)!";
1192 ImplicitPriceSummary summary = BestArcAndGap(source);
1193 const ArcIndex best_arc = summary.first;
1194 const CostValue gap = summary.second;
1195 // Now we have the best arc incident to source, i.e., the one with
1196 // minimum reduced cost. Match that arc, unmatching its head if
1197 // necessary.
1198 if (best_arc == GraphType::kNilArc) {
1199 return false;
1200 }
1201 const NodeIndex new_mate = Head(best_arc);
1202 const NodeIndex to_unmatch = matched_node_[new_mate];
1203 if (to_unmatch != GraphType::kNilNode) {
1204 // Unmatch new_mate from its current mate, pushing the unit of
1205 // flow back to a node on the left side as a unit of excess.
1206 matched_arc_[to_unmatch] = GraphType::kNilArc;
1207 active_nodes_->Add(to_unmatch);
1208 // This counts as a double push.
1209 iteration_stats_.double_pushes_ += 1;
1210 } else {
1211 // We are about to increase the cardinality of the matching.
1212 total_excess_ -= 1;
1213 // This counts as a single push.
1214 iteration_stats_.pushes_ += 1;
1215 }
1216 matched_arc_[source] = best_arc;
1217 matched_node_[new_mate] = source;
1218 // Finally, relabel new_mate.
1219 iteration_stats_.relabelings_ += 1;
1220 const CostValue new_price = price_[new_mate] - gap - epsilon_;
1221 price_[new_mate] = new_price;
1222 return new_price >= price_lower_bound_;
1223}
1224
1225template <typename GraphType>
1226bool LinearSumAssignment<GraphType>::Refine() {
1227 SaturateNegativeArcs();
1228 InitializeActiveNodeContainer();
1229 while (total_excess_ > 0) {
1230 // Get an active node (i.e., one with excess == 1) and discharge
1231 // it using DoublePush.
1232 const NodeIndex node = active_nodes_->Get();
1233 if (!DoublePush(node)) {
1234 // Infeasibility detected.
1235 //
1236 // If infeasibility is detected after the first iteration, we
1237 // have a bug. We don't crash production code in this case but
1238 // we know we're returning a wrong answer so we we leave a
1239 // message in the logs to increase our hope of chasing down the
1240 // problem.
1241 LOG_IF(DFATAL, total_stats_.refinements_ > 0)
1242 << "Infeasibility detection triggered after first iteration found "
1243 << "a feasible assignment!";
1244 return false;
1245 }
1246 }
1247 DCHECK(active_nodes_->Empty());
1248 iteration_stats_.refinements_ += 1;
1249 return true;
1250}
1251
1252// Computes best_arc, the minimum reduced-cost arc incident to
1253// left_node and admissibility_gap, the amount by which the reduced
1254// cost of best_arc must be increased to make it equal in reduced cost
1255// to another residual arc incident to left_node.
1256//
1257// Precondition: left_node is unmatched and has at least one incident
1258// arc. This allows us to simplify the code. The debug-only
1259// counterpart to this routine is LinearSumAssignment::ImplicitPrice()
1260// and it assumes there is an incident arc but does not assume the
1261// node is unmatched. The condition that each left node has at least
1262// one incident arc is explicitly computed during FinalizeSetup().
1263//
1264// This function is large enough that our suggestion that the compiler
1265// inline it might be pointless.
1266template <typename GraphType>
1267inline typename LinearSumAssignment<GraphType>::ImplicitPriceSummary
1268LinearSumAssignment<GraphType>::BestArcAndGap(NodeIndex left_node) const {
1269 DCHECK(IsActive(left_node))
1270 << "Node " << left_node << " must be active (unmatched)!";
1271 DCHECK_GT(epsilon_, 0);
1272 typename GraphType::OutgoingArcIterator arc_it(*graph_, left_node);
1273 ArcIndex best_arc = arc_it.Index();
1274 CostValue min_partial_reduced_cost = PartialReducedCost(best_arc);
1275 // We choose second_min_partial_reduced_cost so that in the case of
1276 // the largest possible gap (which results from a left-side node
1277 // with only a single incident residual arc), the corresponding
1278 // right-side node will be relabeled by an amount that exactly
1279 // matches slack_relabeling_price_.
1280 const CostValue max_gap = slack_relabeling_price_ - epsilon_;
1281 CostValue second_min_partial_reduced_cost =
1282 min_partial_reduced_cost + max_gap;
1283 for (arc_it.Next(); arc_it.Ok(); arc_it.Next()) {
1284 const ArcIndex arc = arc_it.Index();
1285 const CostValue partial_reduced_cost = PartialReducedCost(arc);
1286 if (partial_reduced_cost < second_min_partial_reduced_cost) {
1287 if (partial_reduced_cost < min_partial_reduced_cost) {
1288 best_arc = arc;
1289 second_min_partial_reduced_cost = min_partial_reduced_cost;
1290 min_partial_reduced_cost = partial_reduced_cost;
1291 } else {
1292 second_min_partial_reduced_cost = partial_reduced_cost;
1293 }
1294 }
1295 }
1296 const CostValue gap = std::min<CostValue>(
1297 second_min_partial_reduced_cost - min_partial_reduced_cost, max_gap);
1298 DCHECK_GE(gap, 0);
1299 return std::make_pair(best_arc, gap);
1300}
1301
1302// Only for debugging.
1303//
1304// Requires the precondition, explicitly computed in FinalizeSetup(),
1305// that every left-side node has at least one incident arc.
1306template <typename GraphType>
1307inline CostValue LinearSumAssignment<GraphType>::ImplicitPrice(
1308 NodeIndex left_node) const {
1309 DCHECK_GT(num_left_nodes_, left_node);
1310 DCHECK_GT(epsilon_, 0);
1311 typename GraphType::OutgoingArcIterator arc_it(*graph_, left_node);
1312 // We must not execute this method if left_node has no incident arc.
1313 DCHECK(arc_it.Ok());
1314 ArcIndex best_arc = arc_it.Index();
1315 if (best_arc == matched_arc_[left_node]) {
1316 arc_it.Next();
1317 if (arc_it.Ok()) {
1318 best_arc = arc_it.Index();
1319 }
1320 }
1321 CostValue min_partial_reduced_cost = PartialReducedCost(best_arc);
1322 if (!arc_it.Ok()) {
1323 // Only one arc is incident to left_node, and the node is
1324 // currently matched along that arc, which must be the case in any
1325 // feasible solution. Therefore we implicitly price this node so
1326 // low that we will never consider unmatching it.
1327 return -(min_partial_reduced_cost + slack_relabeling_price_);
1328 }
1329 for (arc_it.Next(); arc_it.Ok(); arc_it.Next()) {
1330 const ArcIndex arc = arc_it.Index();
1331 if (arc != matched_arc_[left_node]) {
1332 const CostValue partial_reduced_cost = PartialReducedCost(arc);
1333 if (partial_reduced_cost < min_partial_reduced_cost) {
1334 min_partial_reduced_cost = partial_reduced_cost;
1335 }
1336 }
1337 }
1338 return -min_partial_reduced_cost;
1339}
1340
1341// Only for debugging.
1342template <typename GraphType>
1343bool LinearSumAssignment<GraphType>::AllMatched() const {
1344 for (NodeIndex node = 0; node < graph_->num_nodes(); ++node) {
1345 if (IsActiveForDebugging(node)) {
1346 return false;
1347 }
1348 }
1349 return true;
1350}
1351
1352// Only for debugging.
1353template <typename GraphType>
1354bool LinearSumAssignment<GraphType>::EpsilonOptimal() const {
1355 for (BipartiteLeftNodeIterator node_it(*graph_, num_left_nodes_);
1356 node_it.Ok(); node_it.Next()) {
1357 const NodeIndex left_node = node_it.Index();
1358 // Get the implicit price of left_node and make sure the reduced
1359 // costs of left_node's incident arcs are in bounds.
1360 CostValue left_node_price = ImplicitPrice(left_node);
1361 for (typename GraphType::OutgoingArcIterator arc_it(*graph_, left_node);
1362 arc_it.Ok(); arc_it.Next()) {
1363 const ArcIndex arc = arc_it.Index();
1364 const CostValue reduced_cost = left_node_price + PartialReducedCost(arc);
1365 // Note the asymmetric definition of epsilon-optimality that we
1366 // use because it means we can saturate all admissible arcs in
1367 // the beginning of Refine() just by unmatching all matched
1368 // nodes.
1369 if (matched_arc_[left_node] == arc) {
1370 // The reverse arc is residual. Epsilon-optimality requires
1371 // that the reduced cost of the forward arc be at most
1372 // epsilon_.
1373 if (reduced_cost > epsilon_) {
1374 return false;
1375 }
1376 } else {
1377 // The forward arc is residual. Epsilon-optimality requires
1378 // that the reduced cost of the forward arc be at least zero.
1379 if (reduced_cost < 0) {
1380 return false;
1381 }
1382 }
1383 }
1384 }
1385 return true;
1386}
1387
1388template <typename GraphType>
1390 incidence_precondition_satisfied_ = true;
1391 // epsilon_ must be greater than kMinEpsilon so that in the case
1392 // where the largest arc cost is zero, we still do a Refine()
1393 // iteration.
1394 epsilon_ = std::max(largest_scaled_cost_magnitude_, kMinEpsilon + 1);
1395 VLOG(2) << "Largest given cost magnitude: "
1396 << largest_scaled_cost_magnitude_ / cost_scaling_factor_;
1397 // Initialize left-side node-indexed arrays and check incidence
1398 // precondition.
1399 for (NodeIndex node = 0; node < num_left_nodes_; ++node) {
1400 matched_arc_[node] = GraphType::kNilArc;
1401 typename GraphType::OutgoingArcIterator arc_it(*graph_, node);
1402 if (!arc_it.Ok()) {
1403 incidence_precondition_satisfied_ = false;
1404 }
1405 }
1406 // Initialize right-side node-indexed arrays. Example: prices are
1407 // stored only for right-side nodes.
1408 for (NodeIndex node = num_left_nodes_; node < graph_->num_nodes(); ++node) {
1409 price_[node] = 0;
1410 matched_node_[node] = GraphType::kNilNode;
1411 }
1412 bool in_range = true;
1413 double double_price_lower_bound = 0.0;
1414 CostValue new_error_parameter;
1415 CostValue old_error_parameter = epsilon_;
1416 do {
1417 new_error_parameter = NewEpsilon(old_error_parameter);
1418 double_price_lower_bound -=
1419 2.0 * static_cast<double>(PriceChangeBound(
1420 old_error_parameter, new_error_parameter, &in_range));
1421 old_error_parameter = new_error_parameter;
1422 } while (new_error_parameter != kMinEpsilon);
1423 const double limit =
1424 -static_cast<double>(std::numeric_limits<CostValue>::max());
1425 if (double_price_lower_bound < limit) {
1426 in_range = false;
1427 price_lower_bound_ = -std::numeric_limits<CostValue>::max();
1428 } else {
1429 price_lower_bound_ = static_cast<CostValue>(double_price_lower_bound);
1430 }
1431 VLOG(4) << "price_lower_bound_ == " << price_lower_bound_;
1432 DCHECK_LE(price_lower_bound_, 0);
1433 if (!in_range) {
1434 LOG(WARNING) << "Price change bound exceeds range of representable "
1435 << "costs; arithmetic overflow is not ruled out and "
1436 << "infeasibility might go undetected.";
1437 }
1438 return in_range;
1439}
1440
1441template <typename GraphType>
1443 total_stats_.Add(iteration_stats_);
1444 VLOG(3) << "Iteration stats: " << iteration_stats_.StatsString();
1445 iteration_stats_.Clear();
1446}
1447
1448template <typename GraphType>
1450 CHECK(graph_ != nullptr);
1451 bool ok = graph_->num_nodes() == 2 * num_left_nodes_;
1452 if (!ok) return false;
1453 // Note: FinalizeSetup() might have been called already by white-box
1454 // test code or by a client that wants to react to the possibility
1455 // of overflow before solving the given problem, but FinalizeSetup()
1456 // is idempotent and reasonably fast, so we call it unconditionally
1457 // here.
1458 FinalizeSetup();
1459 ok = ok && incidence_precondition_satisfied_;
1460 DCHECK(!ok || EpsilonOptimal());
1461 while (ok && epsilon_ > kMinEpsilon) {
1462 ok = ok && UpdateEpsilon();
1463 ok = ok && Refine();
1464 ReportAndAccumulateStats();
1465 DCHECK(!ok || EpsilonOptimal());
1466 DCHECK(!ok || AllMatched());
1467 }
1468 success_ = ok;
1469 VLOG(1) << "Overall stats: " << total_stats_.StatsString();
1470 return ok;
1471}
1472
1473template <typename GraphType>
1475 // It is illegal to call this method unless we successfully computed
1476 // an optimum assignment.
1477 DCHECK(success_);
1478 CostValue cost = 0;
1479 for (BipartiteLeftNodeIterator node_it(*this); node_it.Ok(); node_it.Next()) {
1480 cost += GetAssignmentCost(node_it.Index());
1481 }
1482 return cost;
1483}
1484
1485} // namespace operations_research
1486
1487#endif // OR_TOOLS_GRAPH_LINEAR_ASSIGNMENT_H_
int64_t max
Definition: alldiff_cst.cc:140
#define LOG_IF(severity, condition)
Definition: base/logging.h:475
#define CHECK(condition)
Definition: base/logging.h:491
#define DCHECK_LE(val1, val2)
Definition: base/logging.h:888
#define DCHECK_NE(val1, val2)
Definition: base/logging.h:887
#define DCHECK_GE(val1, val2)
Definition: base/logging.h:890
#define DCHECK_GT(val1, val2)
Definition: base/logging.h:891
#define DCHECK_LT(val1, val2)
Definition: base/logging.h:889
#define LOG(severity)
Definition: base/logging.h:416
#define DCHECK(condition)
Definition: base/logging.h:885
#define DCHECK_EQ(val1, val2)
Definition: base/logging.h:886
#define VLOG(verboselevel)
Definition: base/logging.h:979
bool operator()(typename GraphType::ArcIndex a, typename GraphType::ArcIndex b) const
void SetIndexFromIndex(ArcIndexType source, ArcIndexType destination) const override
CostValueCycleHandler(std::vector< CostValue > *cost)
void SetTempFromIndex(ArcIndexType source) override
void SetIndexFromTemp(ArcIndexType destination) const override
BipartiteLeftNodeIterator(const GraphType &graph, NodeIndex num_left_nodes)
ArcIndex GetAssignmentArc(NodeIndex left_node) const
void SetArcCost(ArcIndex arc, CostValue cost)
NodeIndex Head(ArcIndex arc) const
CostValue ArcCost(ArcIndex arc) const
CostValue GetAssignmentCost(NodeIndex node) const
operations_research::PermutationCycleHandler< typename GraphType::ArcIndex > * ArcAnnotationCycleHandler()
NodeIndex GetMate(NodeIndex left_node) const
void SetGraph(const GraphType *graph)
LinearSumAssignment(const GraphType &graph, NodeIndex num_left_nodes)
bool BuildTailArrayFromAdjacencyListsIfForwardGraph() const
Definition: ebert_graph.h:1921
int64_t b
int64_t a
ABSL_DECLARE_FLAG(int64_t, assignment_alpha)
const int WARNING
Definition: log_severity.h:31
Definition: cleanup.h:22
Collection of objects used to extend the Constraint Solver library.
int64_t cost
int64_t head