COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/cost_scaling.h @ 921:140c953ad5d1

Last change on this file since 921:140c953ad5d1 was 921:140c953ad5d1, checked in by Peter Kovacs <kpeter@…>, 9 years ago

Minor doc improvements

File size: 42.3 KB
Line 
1/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library.
4 *
5 * Copyright (C) 2003-2010
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
12 *
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_COST_SCALING_H
20#define LEMON_COST_SCALING_H
21
22/// \ingroup min_cost_flow_algs
23/// \file
24/// \brief Cost scaling algorithm for finding a minimum cost flow.
25
26#include <vector>
27#include <deque>
28#include <limits>
29
30#include <lemon/core.h>
31#include <lemon/maps.h>
32#include <lemon/math.h>
33#include <lemon/static_graph.h>
34#include <lemon/circulation.h>
35#include <lemon/bellman_ford.h>
36
37namespace lemon {
38
39  /// \brief Default traits class of CostScaling algorithm.
40  ///
41  /// Default traits class of CostScaling algorithm.
42  /// \tparam GR Digraph type.
43  /// \tparam V The number type used for flow amounts, capacity bounds
44  /// and supply values. By default it is \c int.
45  /// \tparam C The number type used for costs and potentials.
46  /// By default it is the same as \c V.
47#ifdef DOXYGEN
48  template <typename GR, typename V = int, typename C = V>
49#else
50  template < typename GR, typename V = int, typename C = V,
51             bool integer = std::numeric_limits<C>::is_integer >
52#endif
53  struct CostScalingDefaultTraits
54  {
55    /// The type of the digraph
56    typedef GR Digraph;
57    /// The type of the flow amounts, capacity bounds and supply values
58    typedef V Value;
59    /// The type of the arc costs
60    typedef C Cost;
61
62    /// \brief The large cost type used for internal computations
63    ///
64    /// The large cost type used for internal computations.
65    /// It is \c long \c long if the \c Cost type is integer,
66    /// otherwise it is \c double.
67    /// \c Cost must be convertible to \c LargeCost.
68    typedef double LargeCost;
69  };
70
71  // Default traits class for integer cost types
72  template <typename GR, typename V, typename C>
73  struct CostScalingDefaultTraits<GR, V, C, true>
74  {
75    typedef GR Digraph;
76    typedef V Value;
77    typedef C Cost;
78#ifdef LEMON_HAVE_LONG_LONG
79    typedef long long LargeCost;
80#else
81    typedef long LargeCost;
82#endif
83  };
84
85
86  /// \addtogroup min_cost_flow_algs
87  /// @{
88
89  /// \brief Implementation of the Cost Scaling algorithm for
90  /// finding a \ref min_cost_flow "minimum cost flow".
91  ///
92  /// \ref CostScaling implements a cost scaling algorithm that performs
93  /// push/augment and relabel operations for finding a \ref min_cost_flow
94  /// "minimum cost flow" \ref amo93networkflows, \ref goldberg90approximation,
95  /// \ref goldberg97efficient, \ref bunnagel98efficient.
96  /// It is a highly efficient primal-dual solution method, which
97  /// can be viewed as the generalization of the \ref Preflow
98  /// "preflow push-relabel" algorithm for the maximum flow problem.
99  ///
100  /// Most of the parameters of the problem (except for the digraph)
101  /// can be given using separate functions, and the algorithm can be
102  /// executed using the \ref run() function. If some parameters are not
103  /// specified, then default values will be used.
104  ///
105  /// \tparam GR The digraph type the algorithm runs on.
106  /// \tparam V The number type used for flow amounts, capacity bounds
107  /// and supply values in the algorithm. By default, it is \c int.
108  /// \tparam C The number type used for costs and potentials in the
109  /// algorithm. By default, it is the same as \c V.
110  /// \tparam TR The traits class that defines various types used by the
111  /// algorithm. By default, it is \ref CostScalingDefaultTraits
112  /// "CostScalingDefaultTraits<GR, V, C>".
113  /// In most cases, this parameter should not be set directly,
114  /// consider to use the named template parameters instead.
115  ///
116  /// \warning Both \c V and \c C must be signed number types.
117  /// \warning All input data (capacities, supply values, and costs) must
118  /// be integer.
119  /// \warning This algorithm does not support negative costs for such
120  /// arcs that have infinite upper bound.
121  ///
122  /// \note %CostScaling provides three different internal methods,
123  /// from which the most efficient one is used by default.
124  /// For more information, see \ref Method.
125#ifdef DOXYGEN
126  template <typename GR, typename V, typename C, typename TR>
127#else
128  template < typename GR, typename V = int, typename C = V,
129             typename TR = CostScalingDefaultTraits<GR, V, C> >
130#endif
131  class CostScaling
132  {
133  public:
134
135    /// The type of the digraph
136    typedef typename TR::Digraph Digraph;
137    /// The type of the flow amounts, capacity bounds and supply values
138    typedef typename TR::Value Value;
139    /// The type of the arc costs
140    typedef typename TR::Cost Cost;
141
142    /// \brief The large cost type
143    ///
144    /// The large cost type used for internal computations.
145    /// By default, it is \c long \c long if the \c Cost type is integer,
146    /// otherwise it is \c double.
147    typedef typename TR::LargeCost LargeCost;
148
149    /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
150    typedef TR Traits;
151
152  public:
153
154    /// \brief Problem type constants for the \c run() function.
155    ///
156    /// Enum type containing the problem type constants that can be
157    /// returned by the \ref run() function of the algorithm.
158    enum ProblemType {
159      /// The problem has no feasible solution (flow).
160      INFEASIBLE,
161      /// The problem has optimal solution (i.e. it is feasible and
162      /// bounded), and the algorithm has found optimal flow and node
163      /// potentials (primal and dual solutions).
164      OPTIMAL,
165      /// The digraph contains an arc of negative cost and infinite
166      /// upper bound. It means that the objective function is unbounded
167      /// on that arc, however, note that it could actually be bounded
168      /// over the feasible flows, but this algroithm cannot handle
169      /// these cases.
170      UNBOUNDED
171    };
172
173    /// \brief Constants for selecting the internal method.
174    ///
175    /// Enum type containing constants for selecting the internal method
176    /// for the \ref run() function.
177    ///
178    /// \ref CostScaling provides three internal methods that differ mainly
179    /// in their base operations, which are used in conjunction with the
180    /// relabel operation.
181    /// By default, the so called \ref PARTIAL_AUGMENT
182    /// "Partial Augment-Relabel" method is used, which proved to be
183    /// the most efficient and the most robust on various test inputs.
184    /// However, the other methods can be selected using the \ref run()
185    /// function with the proper parameter.
186    enum Method {
187      /// Local push operations are used, i.e. flow is moved only on one
188      /// admissible arc at once.
189      PUSH,
190      /// Augment operations are used, i.e. flow is moved on admissible
191      /// paths from a node with excess to a node with deficit.
192      AUGMENT,
193      /// Partial augment operations are used, i.e. flow is moved on
194      /// admissible paths started from a node with excess, but the
195      /// lengths of these paths are limited. This method can be viewed
196      /// as a combined version of the previous two operations.
197      PARTIAL_AUGMENT
198    };
199
200  private:
201
202    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
203
204    typedef std::vector<int> IntVector;
205    typedef std::vector<Value> ValueVector;
206    typedef std::vector<Cost> CostVector;
207    typedef std::vector<LargeCost> LargeCostVector;
208    typedef std::vector<char> BoolVector;
209    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
210
211  private:
212
213    template <typename KT, typename VT>
214    class StaticVectorMap {
215    public:
216      typedef KT Key;
217      typedef VT Value;
218
219      StaticVectorMap(std::vector<Value>& v) : _v(v) {}
220
221      const Value& operator[](const Key& key) const {
222        return _v[StaticDigraph::id(key)];
223      }
224
225      Value& operator[](const Key& key) {
226        return _v[StaticDigraph::id(key)];
227      }
228
229      void set(const Key& key, const Value& val) {
230        _v[StaticDigraph::id(key)] = val;
231      }
232
233    private:
234      std::vector<Value>& _v;
235    };
236
237    typedef StaticVectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap;
238    typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
239
240  private:
241
242    // Data related to the underlying digraph
243    const GR &_graph;
244    int _node_num;
245    int _arc_num;
246    int _res_node_num;
247    int _res_arc_num;
248    int _root;
249
250    // Parameters of the problem
251    bool _have_lower;
252    Value _sum_supply;
253    int _sup_node_num;
254
255    // Data structures for storing the digraph
256    IntNodeMap _node_id;
257    IntArcMap _arc_idf;
258    IntArcMap _arc_idb;
259    IntVector _first_out;
260    BoolVector _forward;
261    IntVector _source;
262    IntVector _target;
263    IntVector _reverse;
264
265    // Node and arc data
266    ValueVector _lower;
267    ValueVector _upper;
268    CostVector _scost;
269    ValueVector _supply;
270
271    ValueVector _res_cap;
272    LargeCostVector _cost;
273    LargeCostVector _pi;
274    ValueVector _excess;
275    IntVector _next_out;
276    std::deque<int> _active_nodes;
277
278    // Data for scaling
279    LargeCost _epsilon;
280    int _alpha;
281
282    IntVector _buckets;
283    IntVector _bucket_next;
284    IntVector _bucket_prev;
285    IntVector _rank;
286    int _max_rank;
287
288    // Data for a StaticDigraph structure
289    typedef std::pair<int, int> IntPair;
290    StaticDigraph _sgr;
291    std::vector<IntPair> _arc_vec;
292    std::vector<LargeCost> _cost_vec;
293    LargeCostArcMap _cost_map;
294    LargeCostNodeMap _pi_map;
295
296  public:
297
298    /// \brief Constant for infinite upper bounds (capacities).
299    ///
300    /// Constant for infinite upper bounds (capacities).
301    /// It is \c std::numeric_limits<Value>::infinity() if available,
302    /// \c std::numeric_limits<Value>::max() otherwise.
303    const Value INF;
304
305  public:
306
307    /// \name Named Template Parameters
308    /// @{
309
310    template <typename T>
311    struct SetLargeCostTraits : public Traits {
312      typedef T LargeCost;
313    };
314
315    /// \brief \ref named-templ-param "Named parameter" for setting
316    /// \c LargeCost type.
317    ///
318    /// \ref named-templ-param "Named parameter" for setting \c LargeCost
319    /// type, which is used for internal computations in the algorithm.
320    /// \c Cost must be convertible to \c LargeCost.
321    template <typename T>
322    struct SetLargeCost
323      : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
324      typedef  CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
325    };
326
327    /// @}
328
329  protected:
330
331    CostScaling() {}
332
333  public:
334
335    /// \brief Constructor.
336    ///
337    /// The constructor of the class.
338    ///
339    /// \param graph The digraph the algorithm runs on.
340    CostScaling(const GR& graph) :
341      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
342      _cost_map(_cost_vec), _pi_map(_pi),
343      INF(std::numeric_limits<Value>::has_infinity ?
344          std::numeric_limits<Value>::infinity() :
345          std::numeric_limits<Value>::max())
346    {
347      // Check the number types
348      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
349        "The flow type of CostScaling must be signed");
350      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
351        "The cost type of CostScaling must be signed");
352
353      // Reset data structures
354      reset();
355    }
356
357    /// \name Parameters
358    /// The parameters of the algorithm can be specified using these
359    /// functions.
360
361    /// @{
362
363    /// \brief Set the lower bounds on the arcs.
364    ///
365    /// This function sets the lower bounds on the arcs.
366    /// If it is not used before calling \ref run(), the lower bounds
367    /// will be set to zero on all arcs.
368    ///
369    /// \param map An arc map storing the lower bounds.
370    /// Its \c Value type must be convertible to the \c Value type
371    /// of the algorithm.
372    ///
373    /// \return <tt>(*this)</tt>
374    template <typename LowerMap>
375    CostScaling& lowerMap(const LowerMap& map) {
376      _have_lower = true;
377      for (ArcIt a(_graph); a != INVALID; ++a) {
378        _lower[_arc_idf[a]] = map[a];
379        _lower[_arc_idb[a]] = map[a];
380      }
381      return *this;
382    }
383
384    /// \brief Set the upper bounds (capacities) on the arcs.
385    ///
386    /// This function sets the upper bounds (capacities) on the arcs.
387    /// If it is not used before calling \ref run(), the upper bounds
388    /// will be set to \ref INF on all arcs (i.e. the flow value will be
389    /// unbounded from above).
390    ///
391    /// \param map An arc map storing the upper bounds.
392    /// Its \c Value type must be convertible to the \c Value type
393    /// of the algorithm.
394    ///
395    /// \return <tt>(*this)</tt>
396    template<typename UpperMap>
397    CostScaling& upperMap(const UpperMap& map) {
398      for (ArcIt a(_graph); a != INVALID; ++a) {
399        _upper[_arc_idf[a]] = map[a];
400      }
401      return *this;
402    }
403
404    /// \brief Set the costs of the arcs.
405    ///
406    /// This function sets the costs of the arcs.
407    /// If it is not used before calling \ref run(), the costs
408    /// will be set to \c 1 on all arcs.
409    ///
410    /// \param map An arc map storing the costs.
411    /// Its \c Value type must be convertible to the \c Cost type
412    /// of the algorithm.
413    ///
414    /// \return <tt>(*this)</tt>
415    template<typename CostMap>
416    CostScaling& costMap(const CostMap& map) {
417      for (ArcIt a(_graph); a != INVALID; ++a) {
418        _scost[_arc_idf[a]] =  map[a];
419        _scost[_arc_idb[a]] = -map[a];
420      }
421      return *this;
422    }
423
424    /// \brief Set the supply values of the nodes.
425    ///
426    /// This function sets the supply values of the nodes.
427    /// If neither this function nor \ref stSupply() is used before
428    /// calling \ref run(), the supply of each node will be set to zero.
429    ///
430    /// \param map A node map storing the supply values.
431    /// Its \c Value type must be convertible to the \c Value type
432    /// of the algorithm.
433    ///
434    /// \return <tt>(*this)</tt>
435    template<typename SupplyMap>
436    CostScaling& supplyMap(const SupplyMap& map) {
437      for (NodeIt n(_graph); n != INVALID; ++n) {
438        _supply[_node_id[n]] = map[n];
439      }
440      return *this;
441    }
442
443    /// \brief Set single source and target nodes and a supply value.
444    ///
445    /// This function sets a single source node and a single target node
446    /// and the required flow value.
447    /// If neither this function nor \ref supplyMap() is used before
448    /// calling \ref run(), the supply of each node will be set to zero.
449    ///
450    /// Using this function has the same effect as using \ref supplyMap()
451    /// with such a map in which \c k is assigned to \c s, \c -k is
452    /// assigned to \c t and all other nodes have zero supply value.
453    ///
454    /// \param s The source node.
455    /// \param t The target node.
456    /// \param k The required amount of flow from node \c s to node \c t
457    /// (i.e. the supply of \c s and the demand of \c t).
458    ///
459    /// \return <tt>(*this)</tt>
460    CostScaling& stSupply(const Node& s, const Node& t, Value k) {
461      for (int i = 0; i != _res_node_num; ++i) {
462        _supply[i] = 0;
463      }
464      _supply[_node_id[s]] =  k;
465      _supply[_node_id[t]] = -k;
466      return *this;
467    }
468
469    /// @}
470
471    /// \name Execution control
472    /// The algorithm can be executed using \ref run().
473
474    /// @{
475
476    /// \brief Run the algorithm.
477    ///
478    /// This function runs the algorithm.
479    /// The paramters can be specified using functions \ref lowerMap(),
480    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
481    /// For example,
482    /// \code
483    ///   CostScaling<ListDigraph> cs(graph);
484    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
485    ///     .supplyMap(sup).run();
486    /// \endcode
487    ///
488    /// This function can be called more than once. All the given parameters
489    /// are kept for the next call, unless \ref resetParams() or \ref reset()
490    /// is used, thus only the modified parameters have to be set again.
491    /// If the underlying digraph was also modified after the construction
492    /// of the class (or the last \ref reset() call), then the \ref reset()
493    /// function must be called.
494    ///
495    /// \param method The internal method that will be used in the
496    /// algorithm. For more information, see \ref Method.
497    /// \param factor The cost scaling factor. It must be larger than one.
498    ///
499    /// \return \c INFEASIBLE if no feasible flow exists,
500    /// \n \c OPTIMAL if the problem has optimal solution
501    /// (i.e. it is feasible and bounded), and the algorithm has found
502    /// optimal flow and node potentials (primal and dual solutions),
503    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
504    /// and infinite upper bound. It means that the objective function
505    /// is unbounded on that arc, however, note that it could actually be
506    /// bounded over the feasible flows, but this algroithm cannot handle
507    /// these cases.
508    ///
509    /// \see ProblemType, Method
510    /// \see resetParams(), reset()
511    ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
512      _alpha = factor;
513      ProblemType pt = init();
514      if (pt != OPTIMAL) return pt;
515      start(method);
516      return OPTIMAL;
517    }
518
519    /// \brief Reset all the parameters that have been given before.
520    ///
521    /// This function resets all the paramaters that have been given
522    /// before using functions \ref lowerMap(), \ref upperMap(),
523    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
524    ///
525    /// It is useful for multiple \ref run() calls. Basically, all the given
526    /// parameters are kept for the next \ref run() call, unless
527    /// \ref resetParams() or \ref reset() is used.
528    /// If the underlying digraph was also modified after the construction
529    /// of the class or the last \ref reset() call, then the \ref reset()
530    /// function must be used, otherwise \ref resetParams() is sufficient.
531    ///
532    /// For example,
533    /// \code
534    ///   CostScaling<ListDigraph> cs(graph);
535    ///
536    ///   // First run
537    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
538    ///     .supplyMap(sup).run();
539    ///
540    ///   // Run again with modified cost map (resetParams() is not called,
541    ///   // so only the cost map have to be set again)
542    ///   cost[e] += 100;
543    ///   cs.costMap(cost).run();
544    ///
545    ///   // Run again from scratch using resetParams()
546    ///   // (the lower bounds will be set to zero on all arcs)
547    ///   cs.resetParams();
548    ///   cs.upperMap(capacity).costMap(cost)
549    ///     .supplyMap(sup).run();
550    /// \endcode
551    ///
552    /// \return <tt>(*this)</tt>
553    ///
554    /// \see reset(), run()
555    CostScaling& resetParams() {
556      for (int i = 0; i != _res_node_num; ++i) {
557        _supply[i] = 0;
558      }
559      int limit = _first_out[_root];
560      for (int j = 0; j != limit; ++j) {
561        _lower[j] = 0;
562        _upper[j] = INF;
563        _scost[j] = _forward[j] ? 1 : -1;
564      }
565      for (int j = limit; j != _res_arc_num; ++j) {
566        _lower[j] = 0;
567        _upper[j] = INF;
568        _scost[j] = 0;
569        _scost[_reverse[j]] = 0;
570      }
571      _have_lower = false;
572      return *this;
573    }
574
575    /// \brief Reset all the parameters that have been given before.
576    ///
577    /// This function resets all the paramaters that have been given
578    /// before using functions \ref lowerMap(), \ref upperMap(),
579    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
580    ///
581    /// It is useful for multiple run() calls. If this function is not
582    /// used, all the parameters given before are kept for the next
583    /// \ref run() call.
584    /// However, the underlying digraph must not be modified after this
585    /// class have been constructed, since it copies and extends the graph.
586    /// \return <tt>(*this)</tt>
587    CostScaling& reset() {
588      // Resize vectors
589      _node_num = countNodes(_graph);
590      _arc_num = countArcs(_graph);
591      _res_node_num = _node_num + 1;
592      _res_arc_num = 2 * (_arc_num + _node_num);
593      _root = _node_num;
594
595      _first_out.resize(_res_node_num + 1);
596      _forward.resize(_res_arc_num);
597      _source.resize(_res_arc_num);
598      _target.resize(_res_arc_num);
599      _reverse.resize(_res_arc_num);
600
601      _lower.resize(_res_arc_num);
602      _upper.resize(_res_arc_num);
603      _scost.resize(_res_arc_num);
604      _supply.resize(_res_node_num);
605
606      _res_cap.resize(_res_arc_num);
607      _cost.resize(_res_arc_num);
608      _pi.resize(_res_node_num);
609      _excess.resize(_res_node_num);
610      _next_out.resize(_res_node_num);
611
612      _arc_vec.reserve(_res_arc_num);
613      _cost_vec.reserve(_res_arc_num);
614
615      // Copy the graph
616      int i = 0, j = 0, k = 2 * _arc_num + _node_num;
617      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
618        _node_id[n] = i;
619      }
620      i = 0;
621      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
622        _first_out[i] = j;
623        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
624          _arc_idf[a] = j;
625          _forward[j] = true;
626          _source[j] = i;
627          _target[j] = _node_id[_graph.runningNode(a)];
628        }
629        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
630          _arc_idb[a] = j;
631          _forward[j] = false;
632          _source[j] = i;
633          _target[j] = _node_id[_graph.runningNode(a)];
634        }
635        _forward[j] = false;
636        _source[j] = i;
637        _target[j] = _root;
638        _reverse[j] = k;
639        _forward[k] = true;
640        _source[k] = _root;
641        _target[k] = i;
642        _reverse[k] = j;
643        ++j; ++k;
644      }
645      _first_out[i] = j;
646      _first_out[_res_node_num] = k;
647      for (ArcIt a(_graph); a != INVALID; ++a) {
648        int fi = _arc_idf[a];
649        int bi = _arc_idb[a];
650        _reverse[fi] = bi;
651        _reverse[bi] = fi;
652      }
653
654      // Reset parameters
655      resetParams();
656      return *this;
657    }
658
659    /// @}
660
661    /// \name Query Functions
662    /// The results of the algorithm can be obtained using these
663    /// functions.\n
664    /// The \ref run() function must be called before using them.
665
666    /// @{
667
668    /// \brief Return the total cost of the found flow.
669    ///
670    /// This function returns the total cost of the found flow.
671    /// Its complexity is O(e).
672    ///
673    /// \note The return type of the function can be specified as a
674    /// template parameter. For example,
675    /// \code
676    ///   cs.totalCost<double>();
677    /// \endcode
678    /// It is useful if the total cost cannot be stored in the \c Cost
679    /// type of the algorithm, which is the default return type of the
680    /// function.
681    ///
682    /// \pre \ref run() must be called before using this function.
683    template <typename Number>
684    Number totalCost() const {
685      Number c = 0;
686      for (ArcIt a(_graph); a != INVALID; ++a) {
687        int i = _arc_idb[a];
688        c += static_cast<Number>(_res_cap[i]) *
689             (-static_cast<Number>(_scost[i]));
690      }
691      return c;
692    }
693
694#ifndef DOXYGEN
695    Cost totalCost() const {
696      return totalCost<Cost>();
697    }
698#endif
699
700    /// \brief Return the flow on the given arc.
701    ///
702    /// This function returns the flow on the given arc.
703    ///
704    /// \pre \ref run() must be called before using this function.
705    Value flow(const Arc& a) const {
706      return _res_cap[_arc_idb[a]];
707    }
708
709    /// \brief Return the flow map (the primal solution).
710    ///
711    /// This function copies the flow value on each arc into the given
712    /// map. The \c Value type of the algorithm must be convertible to
713    /// the \c Value type of the map.
714    ///
715    /// \pre \ref run() must be called before using this function.
716    template <typename FlowMap>
717    void flowMap(FlowMap &map) const {
718      for (ArcIt a(_graph); a != INVALID; ++a) {
719        map.set(a, _res_cap[_arc_idb[a]]);
720      }
721    }
722
723    /// \brief Return the potential (dual value) of the given node.
724    ///
725    /// This function returns the potential (dual value) of the
726    /// given node.
727    ///
728    /// \pre \ref run() must be called before using this function.
729    Cost potential(const Node& n) const {
730      return static_cast<Cost>(_pi[_node_id[n]]);
731    }
732
733    /// \brief Return the potential map (the dual solution).
734    ///
735    /// This function copies the potential (dual value) of each node
736    /// into the given map.
737    /// The \c Cost type of the algorithm must be convertible to the
738    /// \c Value type of the map.
739    ///
740    /// \pre \ref run() must be called before using this function.
741    template <typename PotentialMap>
742    void potentialMap(PotentialMap &map) const {
743      for (NodeIt n(_graph); n != INVALID; ++n) {
744        map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
745      }
746    }
747
748    /// @}
749
750  private:
751
752    // Initialize the algorithm
753    ProblemType init() {
754      if (_res_node_num <= 1) return INFEASIBLE;
755
756      // Check the sum of supply values
757      _sum_supply = 0;
758      for (int i = 0; i != _root; ++i) {
759        _sum_supply += _supply[i];
760      }
761      if (_sum_supply > 0) return INFEASIBLE;
762
763
764      // Initialize vectors
765      for (int i = 0; i != _res_node_num; ++i) {
766        _pi[i] = 0;
767        _excess[i] = _supply[i];
768      }
769
770      // Remove infinite upper bounds and check negative arcs
771      const Value MAX = std::numeric_limits<Value>::max();
772      int last_out;
773      if (_have_lower) {
774        for (int i = 0; i != _root; ++i) {
775          last_out = _first_out[i+1];
776          for (int j = _first_out[i]; j != last_out; ++j) {
777            if (_forward[j]) {
778              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
779              if (c >= MAX) return UNBOUNDED;
780              _excess[i] -= c;
781              _excess[_target[j]] += c;
782            }
783          }
784        }
785      } else {
786        for (int i = 0; i != _root; ++i) {
787          last_out = _first_out[i+1];
788          for (int j = _first_out[i]; j != last_out; ++j) {
789            if (_forward[j] && _scost[j] < 0) {
790              Value c = _upper[j];
791              if (c >= MAX) return UNBOUNDED;
792              _excess[i] -= c;
793              _excess[_target[j]] += c;
794            }
795          }
796        }
797      }
798      Value ex, max_cap = 0;
799      for (int i = 0; i != _res_node_num; ++i) {
800        ex = _excess[i];
801        _excess[i] = 0;
802        if (ex < 0) max_cap -= ex;
803      }
804      for (int j = 0; j != _res_arc_num; ++j) {
805        if (_upper[j] >= MAX) _upper[j] = max_cap;
806      }
807
808      // Initialize the large cost vector and the epsilon parameter
809      _epsilon = 0;
810      LargeCost lc;
811      for (int i = 0; i != _root; ++i) {
812        last_out = _first_out[i+1];
813        for (int j = _first_out[i]; j != last_out; ++j) {
814          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
815          _cost[j] = lc;
816          if (lc > _epsilon) _epsilon = lc;
817        }
818      }
819      _epsilon /= _alpha;
820
821      // Initialize maps for Circulation and remove non-zero lower bounds
822      ConstMap<Arc, Value> low(0);
823      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
824      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
825      ValueArcMap cap(_graph), flow(_graph);
826      ValueNodeMap sup(_graph);
827      for (NodeIt n(_graph); n != INVALID; ++n) {
828        sup[n] = _supply[_node_id[n]];
829      }
830      if (_have_lower) {
831        for (ArcIt a(_graph); a != INVALID; ++a) {
832          int j = _arc_idf[a];
833          Value c = _lower[j];
834          cap[a] = _upper[j] - c;
835          sup[_graph.source(a)] -= c;
836          sup[_graph.target(a)] += c;
837        }
838      } else {
839        for (ArcIt a(_graph); a != INVALID; ++a) {
840          cap[a] = _upper[_arc_idf[a]];
841        }
842      }
843
844      _sup_node_num = 0;
845      for (NodeIt n(_graph); n != INVALID; ++n) {
846        if (sup[n] > 0) ++_sup_node_num;
847      }
848
849      // Find a feasible flow using Circulation
850      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
851        circ(_graph, low, cap, sup);
852      if (!circ.flowMap(flow).run()) return INFEASIBLE;
853
854      // Set residual capacities and handle GEQ supply type
855      if (_sum_supply < 0) {
856        for (ArcIt a(_graph); a != INVALID; ++a) {
857          Value fa = flow[a];
858          _res_cap[_arc_idf[a]] = cap[a] - fa;
859          _res_cap[_arc_idb[a]] = fa;
860          sup[_graph.source(a)] -= fa;
861          sup[_graph.target(a)] += fa;
862        }
863        for (NodeIt n(_graph); n != INVALID; ++n) {
864          _excess[_node_id[n]] = sup[n];
865        }
866        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
867          int u = _target[a];
868          int ra = _reverse[a];
869          _res_cap[a] = -_sum_supply + 1;
870          _res_cap[ra] = -_excess[u];
871          _cost[a] = 0;
872          _cost[ra] = 0;
873          _excess[u] = 0;
874        }
875      } else {
876        for (ArcIt a(_graph); a != INVALID; ++a) {
877          Value fa = flow[a];
878          _res_cap[_arc_idf[a]] = cap[a] - fa;
879          _res_cap[_arc_idb[a]] = fa;
880        }
881        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
882          int ra = _reverse[a];
883          _res_cap[a] = 0;
884          _res_cap[ra] = 0;
885          _cost[a] = 0;
886          _cost[ra] = 0;
887        }
888      }
889
890      return OPTIMAL;
891    }
892
893    // Execute the algorithm and transform the results
894    void start(Method method) {
895      // Maximum path length for partial augment
896      const int MAX_PATH_LENGTH = 4;
897
898      // Initialize data structures for buckets
899      _max_rank = _alpha * _res_node_num;
900      _buckets.resize(_max_rank);
901      _bucket_next.resize(_res_node_num + 1);
902      _bucket_prev.resize(_res_node_num + 1);
903      _rank.resize(_res_node_num + 1);
904
905      // Execute the algorithm
906      switch (method) {
907        case PUSH:
908          startPush();
909          break;
910        case AUGMENT:
911          startAugment();
912          break;
913        case PARTIAL_AUGMENT:
914          startAugment(MAX_PATH_LENGTH);
915          break;
916      }
917
918      // Compute node potentials for the original costs
919      _arc_vec.clear();
920      _cost_vec.clear();
921      for (int j = 0; j != _res_arc_num; ++j) {
922        if (_res_cap[j] > 0) {
923          _arc_vec.push_back(IntPair(_source[j], _target[j]));
924          _cost_vec.push_back(_scost[j]);
925        }
926      }
927      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
928
929      typename BellmanFord<StaticDigraph, LargeCostArcMap>
930        ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
931      bf.distMap(_pi_map);
932      bf.init(0);
933      bf.start();
934
935      // Handle non-zero lower bounds
936      if (_have_lower) {
937        int limit = _first_out[_root];
938        for (int j = 0; j != limit; ++j) {
939          if (!_forward[j]) _res_cap[j] += _lower[j];
940        }
941      }
942    }
943
944    // Initialize a cost scaling phase
945    void initPhase() {
946      // Saturate arcs not satisfying the optimality condition
947      for (int u = 0; u != _res_node_num; ++u) {
948        int last_out = _first_out[u+1];
949        LargeCost pi_u = _pi[u];
950        for (int a = _first_out[u]; a != last_out; ++a) {
951          int v = _target[a];
952          if (_res_cap[a] > 0 && _cost[a] + pi_u - _pi[v] < 0) {
953            Value delta = _res_cap[a];
954            _excess[u] -= delta;
955            _excess[v] += delta;
956            _res_cap[a] = 0;
957            _res_cap[_reverse[a]] += delta;
958          }
959        }
960      }
961
962      // Find active nodes (i.e. nodes with positive excess)
963      for (int u = 0; u != _res_node_num; ++u) {
964        if (_excess[u] > 0) _active_nodes.push_back(u);
965      }
966
967      // Initialize the next arcs
968      for (int u = 0; u != _res_node_num; ++u) {
969        _next_out[u] = _first_out[u];
970      }
971    }
972
973    // Early termination heuristic
974    bool earlyTermination() {
975      const double EARLY_TERM_FACTOR = 3.0;
976
977      // Build a static residual graph
978      _arc_vec.clear();
979      _cost_vec.clear();
980      for (int j = 0; j != _res_arc_num; ++j) {
981        if (_res_cap[j] > 0) {
982          _arc_vec.push_back(IntPair(_source[j], _target[j]));
983          _cost_vec.push_back(_cost[j] + 1);
984        }
985      }
986      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
987
988      // Run Bellman-Ford algorithm to check if the current flow is optimal
989      BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
990      bf.init(0);
991      bool done = false;
992      int K = int(EARLY_TERM_FACTOR * std::sqrt(double(_res_node_num)));
993      for (int i = 0; i < K && !done; ++i) {
994        done = bf.processNextWeakRound();
995      }
996      return done;
997    }
998
999    // Global potential update heuristic
1000    void globalUpdate() {
1001      int bucket_end = _root + 1;
1002
1003      // Initialize buckets
1004      for (int r = 0; r != _max_rank; ++r) {
1005        _buckets[r] = bucket_end;
1006      }
1007      Value total_excess = 0;
1008      for (int i = 0; i != _res_node_num; ++i) {
1009        if (_excess[i] < 0) {
1010          _rank[i] = 0;
1011          _bucket_next[i] = _buckets[0];
1012          _bucket_prev[_buckets[0]] = i;
1013          _buckets[0] = i;
1014        } else {
1015          total_excess += _excess[i];
1016          _rank[i] = _max_rank;
1017        }
1018      }
1019      if (total_excess == 0) return;
1020
1021      // Search the buckets
1022      int r = 0;
1023      for ( ; r != _max_rank; ++r) {
1024        while (_buckets[r] != bucket_end) {
1025          // Remove the first node from the current bucket
1026          int u = _buckets[r];
1027          _buckets[r] = _bucket_next[u];
1028
1029          // Search the incomming arcs of u
1030          LargeCost pi_u = _pi[u];
1031          int last_out = _first_out[u+1];
1032          for (int a = _first_out[u]; a != last_out; ++a) {
1033            int ra = _reverse[a];
1034            if (_res_cap[ra] > 0) {
1035              int v = _source[ra];
1036              int old_rank_v = _rank[v];
1037              if (r < old_rank_v) {
1038                // Compute the new rank of v
1039                LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1040                int new_rank_v = old_rank_v;
1041                if (nrc < LargeCost(_max_rank))
1042                  new_rank_v = r + 1 + int(nrc);
1043
1044                // Change the rank of v
1045                if (new_rank_v < old_rank_v) {
1046                  _rank[v] = new_rank_v;
1047                  _next_out[v] = _first_out[v];
1048
1049                  // Remove v from its old bucket
1050                  if (old_rank_v < _max_rank) {
1051                    if (_buckets[old_rank_v] == v) {
1052                      _buckets[old_rank_v] = _bucket_next[v];
1053                    } else {
1054                      _bucket_next[_bucket_prev[v]] = _bucket_next[v];
1055                      _bucket_prev[_bucket_next[v]] = _bucket_prev[v];
1056                    }
1057                  }
1058
1059                  // Insert v to its new bucket
1060                  _bucket_next[v] = _buckets[new_rank_v];
1061                  _bucket_prev[_buckets[new_rank_v]] = v;
1062                  _buckets[new_rank_v] = v;
1063                }
1064              }
1065            }
1066          }
1067
1068          // Finish search if there are no more active nodes
1069          if (_excess[u] > 0) {
1070            total_excess -= _excess[u];
1071            if (total_excess <= 0) break;
1072          }
1073        }
1074        if (total_excess <= 0) break;
1075      }
1076
1077      // Relabel nodes
1078      for (int u = 0; u != _res_node_num; ++u) {
1079        int k = std::min(_rank[u], r);
1080        if (k > 0) {
1081          _pi[u] -= _epsilon * k;
1082          _next_out[u] = _first_out[u];
1083        }
1084      }
1085    }
1086
1087    /// Execute the algorithm performing augment and relabel operations
1088    void startAugment(int max_length = std::numeric_limits<int>::max()) {
1089      // Paramters for heuristics
1090      const int EARLY_TERM_EPSILON_LIMIT = 1000;
1091      const double GLOBAL_UPDATE_FACTOR = 3.0;
1092
1093      const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1094        (_res_node_num + _sup_node_num * _sup_node_num));
1095      int next_update_limit = global_update_freq;
1096
1097      int relabel_cnt = 0;
1098
1099      // Perform cost scaling phases
1100      std::vector<int> path;
1101      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1102                                        1 : _epsilon / _alpha )
1103      {
1104        // Early termination heuristic
1105        if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1106          if (earlyTermination()) break;
1107        }
1108
1109        // Initialize current phase
1110        initPhase();
1111
1112        // Perform partial augment and relabel operations
1113        while (true) {
1114          // Select an active node (FIFO selection)
1115          while (_active_nodes.size() > 0 &&
1116                 _excess[_active_nodes.front()] <= 0) {
1117            _active_nodes.pop_front();
1118          }
1119          if (_active_nodes.size() == 0) break;
1120          int start = _active_nodes.front();
1121
1122          // Find an augmenting path from the start node
1123          path.clear();
1124          int tip = start;
1125          while (_excess[tip] >= 0 && int(path.size()) < max_length) {
1126            int u;
1127            LargeCost min_red_cost, rc, pi_tip = _pi[tip];
1128            int last_out = _first_out[tip+1];
1129            for (int a = _next_out[tip]; a != last_out; ++a) {
1130              u = _target[a];
1131              if (_res_cap[a] > 0 && _cost[a] + pi_tip - _pi[u] < 0) {
1132                path.push_back(a);
1133                _next_out[tip] = a;
1134                tip = u;
1135                goto next_step;
1136              }
1137            }
1138
1139            // Relabel tip node
1140            min_red_cost = std::numeric_limits<LargeCost>::max();
1141            if (tip != start) {
1142              int ra = _reverse[path.back()];
1143              min_red_cost = _cost[ra] + pi_tip - _pi[_target[ra]];
1144            }
1145            for (int a = _first_out[tip]; a != last_out; ++a) {
1146              rc = _cost[a] + pi_tip - _pi[_target[a]];
1147              if (_res_cap[a] > 0 && rc < min_red_cost) {
1148                min_red_cost = rc;
1149              }
1150            }
1151            _pi[tip] -= min_red_cost + _epsilon;
1152            _next_out[tip] = _first_out[tip];
1153            ++relabel_cnt;
1154
1155            // Step back
1156            if (tip != start) {
1157              tip = _source[path.back()];
1158              path.pop_back();
1159            }
1160
1161          next_step: ;
1162          }
1163
1164          // Augment along the found path (as much flow as possible)
1165          Value delta;
1166          int pa, u, v = start;
1167          for (int i = 0; i != int(path.size()); ++i) {
1168            pa = path[i];
1169            u = v;
1170            v = _target[pa];
1171            delta = std::min(_res_cap[pa], _excess[u]);
1172            _res_cap[pa] -= delta;
1173            _res_cap[_reverse[pa]] += delta;
1174            _excess[u] -= delta;
1175            _excess[v] += delta;
1176            if (_excess[v] > 0 && _excess[v] <= delta)
1177              _active_nodes.push_back(v);
1178          }
1179
1180          // Global update heuristic
1181          if (relabel_cnt >= next_update_limit) {
1182            globalUpdate();
1183            next_update_limit += global_update_freq;
1184          }
1185        }
1186      }
1187    }
1188
1189    /// Execute the algorithm performing push and relabel operations
1190    void startPush() {
1191      // Paramters for heuristics
1192      const int EARLY_TERM_EPSILON_LIMIT = 1000;
1193      const double GLOBAL_UPDATE_FACTOR = 2.0;
1194
1195      const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1196        (_res_node_num + _sup_node_num * _sup_node_num));
1197      int next_update_limit = global_update_freq;
1198
1199      int relabel_cnt = 0;
1200
1201      // Perform cost scaling phases
1202      BoolVector hyper(_res_node_num, false);
1203      LargeCostVector hyper_cost(_res_node_num);
1204      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1205                                        1 : _epsilon / _alpha )
1206      {
1207        // Early termination heuristic
1208        if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1209          if (earlyTermination()) break;
1210        }
1211
1212        // Initialize current phase
1213        initPhase();
1214
1215        // Perform push and relabel operations
1216        while (_active_nodes.size() > 0) {
1217          LargeCost min_red_cost, rc, pi_n;
1218          Value delta;
1219          int n, t, a, last_out = _res_arc_num;
1220
1221        next_node:
1222          // Select an active node (FIFO selection)
1223          n = _active_nodes.front();
1224          last_out = _first_out[n+1];
1225          pi_n = _pi[n];
1226
1227          // Perform push operations if there are admissible arcs
1228          if (_excess[n] > 0) {
1229            for (a = _next_out[n]; a != last_out; ++a) {
1230              if (_res_cap[a] > 0 &&
1231                  _cost[a] + pi_n - _pi[_target[a]] < 0) {
1232                delta = std::min(_res_cap[a], _excess[n]);
1233                t = _target[a];
1234
1235                // Push-look-ahead heuristic
1236                Value ahead = -_excess[t];
1237                int last_out_t = _first_out[t+1];
1238                LargeCost pi_t = _pi[t];
1239                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1240                  if (_res_cap[ta] > 0 &&
1241                      _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1242                    ahead += _res_cap[ta];
1243                  if (ahead >= delta) break;
1244                }
1245                if (ahead < 0) ahead = 0;
1246
1247                // Push flow along the arc
1248                if (ahead < delta && !hyper[t]) {
1249                  _res_cap[a] -= ahead;
1250                  _res_cap[_reverse[a]] += ahead;
1251                  _excess[n] -= ahead;
1252                  _excess[t] += ahead;
1253                  _active_nodes.push_front(t);
1254                  hyper[t] = true;
1255                  hyper_cost[t] = _cost[a] + pi_n - pi_t;
1256                  _next_out[n] = a;
1257                  goto next_node;
1258                } else {
1259                  _res_cap[a] -= delta;
1260                  _res_cap[_reverse[a]] += delta;
1261                  _excess[n] -= delta;
1262                  _excess[t] += delta;
1263                  if (_excess[t] > 0 && _excess[t] <= delta)
1264                    _active_nodes.push_back(t);
1265                }
1266
1267                if (_excess[n] == 0) {
1268                  _next_out[n] = a;
1269                  goto remove_nodes;
1270                }
1271              }
1272            }
1273            _next_out[n] = a;
1274          }
1275
1276          // Relabel the node if it is still active (or hyper)
1277          if (_excess[n] > 0 || hyper[n]) {
1278             min_red_cost = hyper[n] ? -hyper_cost[n] :
1279               std::numeric_limits<LargeCost>::max();
1280            for (int a = _first_out[n]; a != last_out; ++a) {
1281              rc = _cost[a] + pi_n - _pi[_target[a]];
1282              if (_res_cap[a] > 0 && rc < min_red_cost) {
1283                min_red_cost = rc;
1284              }
1285            }
1286            _pi[n] -= min_red_cost + _epsilon;
1287            _next_out[n] = _first_out[n];
1288            hyper[n] = false;
1289            ++relabel_cnt;
1290          }
1291
1292          // Remove nodes that are not active nor hyper
1293        remove_nodes:
1294          while ( _active_nodes.size() > 0 &&
1295                  _excess[_active_nodes.front()] <= 0 &&
1296                  !hyper[_active_nodes.front()] ) {
1297            _active_nodes.pop_front();
1298          }
1299
1300          // Global update heuristic
1301          if (relabel_cnt >= next_update_limit) {
1302            globalUpdate();
1303            for (int u = 0; u != _res_node_num; ++u)
1304              hyper[u] = false;
1305            next_update_limit += global_update_freq;
1306          }
1307        }
1308      }
1309    }
1310
1311  }; //class CostScaling
1312
1313  ///@}
1314
1315} //namespace lemon
1316
1317#endif //LEMON_COST_SCALING_H
Note: See TracBrowser for help on using the repository browser.