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