lemon/hartmann_orlin.h
author Balazs Dezso <deba@inf.elte.hu>
Sun, 14 Feb 2010 23:14:09 +0100
changeset 833 d2bc45e8f6f2
parent 795 921d5bf41ac2
child 841 aa8c9008b3de
permissions -rw-r--r--
Merge bugfix #337
     1 /* -*- C++ -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library
     4  *
     5  * Copyright (C) 2003-2008
     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_HARTMANN_ORLIN_H
    20 #define LEMON_HARTMANN_ORLIN_H
    21 
    22 /// \ingroup min_mean_cycle
    23 ///
    24 /// \file
    25 /// \brief Hartmann-Orlin's algorithm for finding a minimum mean cycle.
    26 
    27 #include <vector>
    28 #include <limits>
    29 #include <lemon/core.h>
    30 #include <lemon/path.h>
    31 #include <lemon/tolerance.h>
    32 #include <lemon/connectivity.h>
    33 
    34 namespace lemon {
    35 
    36   /// \brief Default traits class of HartmannOrlin algorithm.
    37   ///
    38   /// Default traits class of HartmannOrlin algorithm.
    39   /// \tparam GR The type of the digraph.
    40   /// \tparam LEN The type of the length map.
    41   /// It must conform to the \ref concepts::Rea_data "Rea_data" concept.
    42 #ifdef DOXYGEN
    43   template <typename GR, typename LEN>
    44 #else
    45   template <typename GR, typename LEN,
    46     bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
    47 #endif
    48   struct HartmannOrlinDefaultTraits
    49   {
    50     /// The type of the digraph
    51     typedef GR Digraph;
    52     /// The type of the length map
    53     typedef LEN LengthMap;
    54     /// The type of the arc lengths
    55     typedef typename LengthMap::Value Value;
    56 
    57     /// \brief The large value type used for internal computations
    58     ///
    59     /// The large value type used for internal computations.
    60     /// It is \c long \c long if the \c Value type is integer,
    61     /// otherwise it is \c double.
    62     /// \c Value must be convertible to \c LargeValue.
    63     typedef double LargeValue;
    64 
    65     /// The tolerance type used for internal computations
    66     typedef lemon::Tolerance<LargeValue> Tolerance;
    67 
    68     /// \brief The path type of the found cycles
    69     ///
    70     /// The path type of the found cycles.
    71     /// It must conform to the \ref lemon::concepts::Path "Path" concept
    72     /// and it must have an \c addFront() function.
    73     typedef lemon::Path<Digraph> Path;
    74   };
    75 
    76   // Default traits class for integer value types
    77   template <typename GR, typename LEN>
    78   struct HartmannOrlinDefaultTraits<GR, LEN, true>
    79   {
    80     typedef GR Digraph;
    81     typedef LEN LengthMap;
    82     typedef typename LengthMap::Value Value;
    83 #ifdef LEMON_HAVE_LONG_LONG
    84     typedef long long LargeValue;
    85 #else
    86     typedef long LargeValue;
    87 #endif
    88     typedef lemon::Tolerance<LargeValue> Tolerance;
    89     typedef lemon::Path<Digraph> Path;
    90   };
    91 
    92 
    93   /// \addtogroup min_mean_cycle
    94   /// @{
    95 
    96   /// \brief Implementation of the Hartmann-Orlin algorithm for finding
    97   /// a minimum mean cycle.
    98   ///
    99   /// This class implements the Hartmann-Orlin algorithm for finding
   100   /// a directed cycle of minimum mean length (cost) in a digraph
   101   /// \ref amo93networkflows, \ref dasdan98minmeancycle.
   102   /// It is an improved version of \ref Karp "Karp"'s original algorithm,
   103   /// it applies an efficient early termination scheme.
   104   /// It runs in time O(ne) and uses space O(n<sup>2</sup>+e).
   105   ///
   106   /// \tparam GR The type of the digraph the algorithm runs on.
   107   /// \tparam LEN The type of the length map. The default
   108   /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
   109   /// \tparam TR The traits class that defines various types used by the
   110   /// algorithm. By default, it is \ref HartmannOrlinDefaultTraits
   111   /// "HartmannOrlinDefaultTraits<GR, LEN>".
   112   /// In most cases, this parameter should not be set directly,
   113   /// consider to use the named template parameters instead.
   114 #ifdef DOXYGEN
   115   template <typename GR, typename LEN, typename TR>
   116 #else
   117   template < typename GR,
   118              typename LEN = typename GR::template ArcMap<int>,
   119              typename TR = HartmannOrlinDefaultTraits<GR, LEN> >
   120 #endif
   121   class HartmannOrlin
   122   {
   123   public:
   124 
   125     /// The type of the digraph
   126     typedef typename TR::Digraph Digraph;
   127     /// The type of the length map
   128     typedef typename TR::LengthMap LengthMap;
   129     /// The type of the arc lengths
   130     typedef typename TR::Value Value;
   131 
   132     /// \brief The large value type
   133     ///
   134     /// The large value type used for internal computations.
   135     /// By default, it is \c long \c long if the \c Value type is integer,
   136     /// otherwise it is \c double.
   137     typedef typename TR::LargeValue LargeValue;
   138 
   139     /// The tolerance type
   140     typedef typename TR::Tolerance Tolerance;
   141 
   142     /// \brief The path type of the found cycles
   143     ///
   144     /// The path type of the found cycles.
   145     /// Using the \ref HartmannOrlinDefaultTraits "default traits class",
   146     /// it is \ref lemon::Path "Path<Digraph>".
   147     typedef typename TR::Path Path;
   148 
   149     /// The \ref HartmannOrlinDefaultTraits "traits class" of the algorithm
   150     typedef TR Traits;
   151 
   152   private:
   153 
   154     TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
   155 
   156     // Data sturcture for path data
   157     struct PathData
   158     {
   159       LargeValue dist;
   160       Arc pred;
   161       PathData(LargeValue d, Arc p = INVALID) :
   162         dist(d), pred(p) {}
   163     };
   164 
   165     typedef typename Digraph::template NodeMap<std::vector<PathData> >
   166       PathDataNodeMap;
   167 
   168   private:
   169 
   170     // The digraph the algorithm runs on
   171     const Digraph &_gr;
   172     // The length of the arcs
   173     const LengthMap &_length;
   174 
   175     // Data for storing the strongly connected components
   176     int _comp_num;
   177     typename Digraph::template NodeMap<int> _comp;
   178     std::vector<std::vector<Node> > _comp_nodes;
   179     std::vector<Node>* _nodes;
   180     typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
   181 
   182     // Data for the found cycles
   183     bool _curr_found, _best_found;
   184     LargeValue _curr_length, _best_length;
   185     int _curr_size, _best_size;
   186     Node _curr_node, _best_node;
   187     int _curr_level, _best_level;
   188 
   189     Path *_cycle_path;
   190     bool _local_path;
   191 
   192     // Node map for storing path data
   193     PathDataNodeMap _data;
   194     // The processed nodes in the last round
   195     std::vector<Node> _process;
   196 
   197     Tolerance _tolerance;
   198 
   199     // Infinite constant
   200     const LargeValue INF;
   201 
   202   public:
   203 
   204     /// \name Named Template Parameters
   205     /// @{
   206 
   207     template <typename T>
   208     struct SetLargeValueTraits : public Traits {
   209       typedef T LargeValue;
   210       typedef lemon::Tolerance<T> Tolerance;
   211     };
   212 
   213     /// \brief \ref named-templ-param "Named parameter" for setting
   214     /// \c LargeValue type.
   215     ///
   216     /// \ref named-templ-param "Named parameter" for setting \c LargeValue
   217     /// type. It is used for internal computations in the algorithm.
   218     template <typename T>
   219     struct SetLargeValue
   220       : public HartmannOrlin<GR, LEN, SetLargeValueTraits<T> > {
   221       typedef HartmannOrlin<GR, LEN, SetLargeValueTraits<T> > Create;
   222     };
   223 
   224     template <typename T>
   225     struct SetPathTraits : public Traits {
   226       typedef T Path;
   227     };
   228 
   229     /// \brief \ref named-templ-param "Named parameter" for setting
   230     /// \c %Path type.
   231     ///
   232     /// \ref named-templ-param "Named parameter" for setting the \c %Path
   233     /// type of the found cycles.
   234     /// It must conform to the \ref lemon::concepts::Path "Path" concept
   235     /// and it must have an \c addFront() function.
   236     template <typename T>
   237     struct SetPath
   238       : public HartmannOrlin<GR, LEN, SetPathTraits<T> > {
   239       typedef HartmannOrlin<GR, LEN, SetPathTraits<T> > Create;
   240     };
   241 
   242     /// @}
   243 
   244   public:
   245 
   246     /// \brief Constructor.
   247     ///
   248     /// The constructor of the class.
   249     ///
   250     /// \param digraph The digraph the algorithm runs on.
   251     /// \param length The lengths (costs) of the arcs.
   252     HartmannOrlin( const Digraph &digraph,
   253                    const LengthMap &length ) :
   254       _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
   255       _best_found(false), _best_length(0), _best_size(1),
   256       _cycle_path(NULL), _local_path(false), _data(digraph),
   257       INF(std::numeric_limits<LargeValue>::has_infinity ?
   258           std::numeric_limits<LargeValue>::infinity() :
   259           std::numeric_limits<LargeValue>::max())
   260     {}
   261 
   262     /// Destructor.
   263     ~HartmannOrlin() {
   264       if (_local_path) delete _cycle_path;
   265     }
   266 
   267     /// \brief Set the path structure for storing the found cycle.
   268     ///
   269     /// This function sets an external path structure for storing the
   270     /// found cycle.
   271     ///
   272     /// If you don't call this function before calling \ref run() or
   273     /// \ref findMinMean(), it will allocate a local \ref Path "path"
   274     /// structure. The destuctor deallocates this automatically
   275     /// allocated object, of course.
   276     ///
   277     /// \note The algorithm calls only the \ref lemon::Path::addFront()
   278     /// "addFront()" function of the given path structure.
   279     ///
   280     /// \return <tt>(*this)</tt>
   281     HartmannOrlin& cycle(Path &path) {
   282       if (_local_path) {
   283         delete _cycle_path;
   284         _local_path = false;
   285       }
   286       _cycle_path = &path;
   287       return *this;
   288     }
   289 
   290     /// \brief Set the tolerance used by the algorithm.
   291     ///
   292     /// This function sets the tolerance object used by the algorithm.
   293     ///
   294     /// \return <tt>(*this)</tt>
   295     HartmannOrlin& tolerance(const Tolerance& tolerance) {
   296       _tolerance = tolerance;
   297       return *this;
   298     }
   299 
   300     /// \brief Return a const reference to the tolerance.
   301     ///
   302     /// This function returns a const reference to the tolerance object
   303     /// used by the algorithm.
   304     const Tolerance& tolerance() const {
   305       return _tolerance;
   306     }
   307 
   308     /// \name Execution control
   309     /// The simplest way to execute the algorithm is to call the \ref run()
   310     /// function.\n
   311     /// If you only need the minimum mean length, you may call
   312     /// \ref findMinMean().
   313 
   314     /// @{
   315 
   316     /// \brief Run the algorithm.
   317     ///
   318     /// This function runs the algorithm.
   319     /// It can be called more than once (e.g. if the underlying digraph
   320     /// and/or the arc lengths have been modified).
   321     ///
   322     /// \return \c true if a directed cycle exists in the digraph.
   323     ///
   324     /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
   325     /// \code
   326     ///   return mmc.findMinMean() && mmc.findCycle();
   327     /// \endcode
   328     bool run() {
   329       return findMinMean() && findCycle();
   330     }
   331 
   332     /// \brief Find the minimum cycle mean.
   333     ///
   334     /// This function finds the minimum mean length of the directed
   335     /// cycles in the digraph.
   336     ///
   337     /// \return \c true if a directed cycle exists in the digraph.
   338     bool findMinMean() {
   339       // Initialization and find strongly connected components
   340       init();
   341       findComponents();
   342       
   343       // Find the minimum cycle mean in the components
   344       for (int comp = 0; comp < _comp_num; ++comp) {
   345         if (!initComponent(comp)) continue;
   346         processRounds();
   347         
   348         // Update the best cycle (global minimum mean cycle)
   349         if ( _curr_found && (!_best_found || 
   350              _curr_length * _best_size < _best_length * _curr_size) ) {
   351           _best_found = true;
   352           _best_length = _curr_length;
   353           _best_size = _curr_size;
   354           _best_node = _curr_node;
   355           _best_level = _curr_level;
   356         }
   357       }
   358       return _best_found;
   359     }
   360 
   361     /// \brief Find a minimum mean directed cycle.
   362     ///
   363     /// This function finds a directed cycle of minimum mean length
   364     /// in the digraph using the data computed by findMinMean().
   365     ///
   366     /// \return \c true if a directed cycle exists in the digraph.
   367     ///
   368     /// \pre \ref findMinMean() must be called before using this function.
   369     bool findCycle() {
   370       if (!_best_found) return false;
   371       IntNodeMap reached(_gr, -1);
   372       int r = _best_level + 1;
   373       Node u = _best_node;
   374       while (reached[u] < 0) {
   375         reached[u] = --r;
   376         u = _gr.source(_data[u][r].pred);
   377       }
   378       r = reached[u];
   379       Arc e = _data[u][r].pred;
   380       _cycle_path->addFront(e);
   381       _best_length = _length[e];
   382       _best_size = 1;
   383       Node v;
   384       while ((v = _gr.source(e)) != u) {
   385         e = _data[v][--r].pred;
   386         _cycle_path->addFront(e);
   387         _best_length += _length[e];
   388         ++_best_size;
   389       }
   390       return true;
   391     }
   392 
   393     /// @}
   394 
   395     /// \name Query Functions
   396     /// The results of the algorithm can be obtained using these
   397     /// functions.\n
   398     /// The algorithm should be executed before using them.
   399 
   400     /// @{
   401 
   402     /// \brief Return the total length of the found cycle.
   403     ///
   404     /// This function returns the total length of the found cycle.
   405     ///
   406     /// \pre \ref run() or \ref findMinMean() must be called before
   407     /// using this function.
   408     LargeValue cycleLength() const {
   409       return _best_length;
   410     }
   411 
   412     /// \brief Return the number of arcs on the found cycle.
   413     ///
   414     /// This function returns the number of arcs on the found cycle.
   415     ///
   416     /// \pre \ref run() or \ref findMinMean() must be called before
   417     /// using this function.
   418     int cycleArcNum() const {
   419       return _best_size;
   420     }
   421 
   422     /// \brief Return the mean length of the found cycle.
   423     ///
   424     /// This function returns the mean length of the found cycle.
   425     ///
   426     /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
   427     /// following code.
   428     /// \code
   429     ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
   430     /// \endcode
   431     ///
   432     /// \pre \ref run() or \ref findMinMean() must be called before
   433     /// using this function.
   434     double cycleMean() const {
   435       return static_cast<double>(_best_length) / _best_size;
   436     }
   437 
   438     /// \brief Return the found cycle.
   439     ///
   440     /// This function returns a const reference to the path structure
   441     /// storing the found cycle.
   442     ///
   443     /// \pre \ref run() or \ref findCycle() must be called before using
   444     /// this function.
   445     const Path& cycle() const {
   446       return *_cycle_path;
   447     }
   448 
   449     ///@}
   450 
   451   private:
   452 
   453     // Initialization
   454     void init() {
   455       if (!_cycle_path) {
   456         _local_path = true;
   457         _cycle_path = new Path;
   458       }
   459       _cycle_path->clear();
   460       _best_found = false;
   461       _best_length = 0;
   462       _best_size = 1;
   463       _cycle_path->clear();
   464       for (NodeIt u(_gr); u != INVALID; ++u)
   465         _data[u].clear();
   466     }
   467 
   468     // Find strongly connected components and initialize _comp_nodes
   469     // and _out_arcs
   470     void findComponents() {
   471       _comp_num = stronglyConnectedComponents(_gr, _comp);
   472       _comp_nodes.resize(_comp_num);
   473       if (_comp_num == 1) {
   474         _comp_nodes[0].clear();
   475         for (NodeIt n(_gr); n != INVALID; ++n) {
   476           _comp_nodes[0].push_back(n);
   477           _out_arcs[n].clear();
   478           for (OutArcIt a(_gr, n); a != INVALID; ++a) {
   479             _out_arcs[n].push_back(a);
   480           }
   481         }
   482       } else {
   483         for (int i = 0; i < _comp_num; ++i)
   484           _comp_nodes[i].clear();
   485         for (NodeIt n(_gr); n != INVALID; ++n) {
   486           int k = _comp[n];
   487           _comp_nodes[k].push_back(n);
   488           _out_arcs[n].clear();
   489           for (OutArcIt a(_gr, n); a != INVALID; ++a) {
   490             if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
   491           }
   492         }
   493       }
   494     }
   495 
   496     // Initialize path data for the current component
   497     bool initComponent(int comp) {
   498       _nodes = &(_comp_nodes[comp]);
   499       int n = _nodes->size();
   500       if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
   501         return false;
   502       }      
   503       for (int i = 0; i < n; ++i) {
   504         _data[(*_nodes)[i]].resize(n + 1, PathData(INF));
   505       }
   506       return true;
   507     }
   508 
   509     // Process all rounds of computing path data for the current component.
   510     // _data[v][k] is the length of a shortest directed walk from the root
   511     // node to node v containing exactly k arcs.
   512     void processRounds() {
   513       Node start = (*_nodes)[0];
   514       _data[start][0] = PathData(0);
   515       _process.clear();
   516       _process.push_back(start);
   517 
   518       int k, n = _nodes->size();
   519       int next_check = 4;
   520       bool terminate = false;
   521       for (k = 1; k <= n && int(_process.size()) < n && !terminate; ++k) {
   522         processNextBuildRound(k);
   523         if (k == next_check || k == n) {
   524           terminate = checkTermination(k);
   525           next_check = next_check * 3 / 2;
   526         }
   527       }
   528       for ( ; k <= n && !terminate; ++k) {
   529         processNextFullRound(k);
   530         if (k == next_check || k == n) {
   531           terminate = checkTermination(k);
   532           next_check = next_check * 3 / 2;
   533         }
   534       }
   535     }
   536 
   537     // Process one round and rebuild _process
   538     void processNextBuildRound(int k) {
   539       std::vector<Node> next;
   540       Node u, v;
   541       Arc e;
   542       LargeValue d;
   543       for (int i = 0; i < int(_process.size()); ++i) {
   544         u = _process[i];
   545         for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
   546           e = _out_arcs[u][j];
   547           v = _gr.target(e);
   548           d = _data[u][k-1].dist + _length[e];
   549           if (_tolerance.less(d, _data[v][k].dist)) {
   550             if (_data[v][k].dist == INF) next.push_back(v);
   551             _data[v][k] = PathData(d, e);
   552           }
   553         }
   554       }
   555       _process.swap(next);
   556     }
   557 
   558     // Process one round using _nodes instead of _process
   559     void processNextFullRound(int k) {
   560       Node u, v;
   561       Arc e;
   562       LargeValue d;
   563       for (int i = 0; i < int(_nodes->size()); ++i) {
   564         u = (*_nodes)[i];
   565         for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
   566           e = _out_arcs[u][j];
   567           v = _gr.target(e);
   568           d = _data[u][k-1].dist + _length[e];
   569           if (_tolerance.less(d, _data[v][k].dist)) {
   570             _data[v][k] = PathData(d, e);
   571           }
   572         }
   573       }
   574     }
   575     
   576     // Check early termination
   577     bool checkTermination(int k) {
   578       typedef std::pair<int, int> Pair;
   579       typename GR::template NodeMap<Pair> level(_gr, Pair(-1, 0));
   580       typename GR::template NodeMap<LargeValue> pi(_gr);
   581       int n = _nodes->size();
   582       LargeValue length;
   583       int size;
   584       Node u;
   585       
   586       // Search for cycles that are already found
   587       _curr_found = false;
   588       for (int i = 0; i < n; ++i) {
   589         u = (*_nodes)[i];
   590         if (_data[u][k].dist == INF) continue;
   591         for (int j = k; j >= 0; --j) {
   592           if (level[u].first == i && level[u].second > 0) {
   593             // A cycle is found
   594             length = _data[u][level[u].second].dist - _data[u][j].dist;
   595             size = level[u].second - j;
   596             if (!_curr_found || length * _curr_size < _curr_length * size) {
   597               _curr_length = length;
   598               _curr_size = size;
   599               _curr_node = u;
   600               _curr_level = level[u].second;
   601               _curr_found = true;
   602             }
   603           }
   604           level[u] = Pair(i, j);
   605           if (j != 0) {
   606 	    u = _gr.source(_data[u][j].pred);
   607 	  }
   608         }
   609       }
   610 
   611       // If at least one cycle is found, check the optimality condition
   612       LargeValue d;
   613       if (_curr_found && k < n) {
   614         // Find node potentials
   615         for (int i = 0; i < n; ++i) {
   616           u = (*_nodes)[i];
   617           pi[u] = INF;
   618           for (int j = 0; j <= k; ++j) {
   619             if (_data[u][j].dist < INF) {
   620               d = _data[u][j].dist * _curr_size - j * _curr_length;
   621               if (_tolerance.less(d, pi[u])) pi[u] = d;
   622             }
   623           }
   624         }
   625 
   626         // Check the optimality condition for all arcs
   627         bool done = true;
   628         for (ArcIt a(_gr); a != INVALID; ++a) {
   629           if (_tolerance.less(_length[a] * _curr_size - _curr_length,
   630                               pi[_gr.target(a)] - pi[_gr.source(a)]) ) {
   631             done = false;
   632             break;
   633           }
   634         }
   635         return done;
   636       }
   637       return (k == n);
   638     }
   639 
   640   }; //class HartmannOrlin
   641 
   642   ///@}
   643 
   644 } //namespace lemon
   645 
   646 #endif //LEMON_HARTMANN_ORLIN_H