COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/cost_scaling.h @ 919:e0cef67fe565

Last change on this file since 919:e0cef67fe565 was 919:e0cef67fe565, checked in by Peter Kovacs <kpeter@…>, 13 years ago

Various doc improvements (#406)

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