COIN-OR::LEMON - Graph Library

source: lemon/lemon/min_mean_cycle.h @ 808:5795860737f5

Last change on this file since 808:5795860737f5 was 808:5795860737f5, checked in by Peter Kovacs <kpeter@…>, 15 years ago

Traits class + named parameters for MinMeanCycle? (#179)

  • Add a Traits class defining LargeValue?, Tolerance, Path types. LargeValue? is used for internal computations, it is 'long long' if the length type is integer, otherwise it is 'double'.
  • Add named template parameters for LargeValue? and Path types.
  • Improve numerical stability: remove divisions from the internal computations. If the arc lengths are integers, then all used values are integers (except for the cycleMean() query function, of course).
File size: 17.0 KB
Line 
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_MIN_MEAN_CYCLE_H
20#define LEMON_MIN_MEAN_CYCLE_H
21
22/// \ingroup shortest_path
23///
24/// \file
25/// \brief Howard's algorithm for finding a minimum mean cycle.
26
27#include <vector>
28#include <lemon/core.h>
29#include <lemon/path.h>
30#include <lemon/tolerance.h>
31#include <lemon/connectivity.h>
32
33namespace lemon {
34
35  /// \brief Default traits class of MinMeanCycle class.
36  ///
37  /// Default traits class of MinMeanCycle class.
38  /// \tparam GR The type of the digraph.
39  /// \tparam LEN The type of the length map.
40  /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
41#ifdef DOXYGEN
42  template <typename GR, typename LEN>
43#else
44  template <typename GR, typename LEN,
45    bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
46#endif
47  struct MinMeanCycleDefaultTraits
48  {
49    /// The type of the digraph
50    typedef GR Digraph;
51    /// The type of the length map
52    typedef LEN LengthMap;
53    /// The type of the arc lengths
54    typedef typename LengthMap::Value Value;
55
56    /// \brief The large value type used for internal computations
57    ///
58    /// The large value type used for internal computations.
59    /// It is \c long \c long if the \c Value type is integer,
60    /// otherwise it is \c double.
61    /// \c Value must be convertible to \c LargeValue.
62    typedef double LargeValue;
63
64    /// The tolerance type used for internal computations
65    typedef lemon::Tolerance<LargeValue> Tolerance;
66
67    /// \brief The path type of the found cycles
68    ///
69    /// The path type of the found cycles.
70    /// It must conform to the \ref lemon::concepts::Path "Path" concept
71    /// and it must have an \c addBack() function.
72    typedef lemon::Path<Digraph> Path;
73  };
74
75  // Default traits class for integer value types
76  template <typename GR, typename LEN>
77  struct MinMeanCycleDefaultTraits<GR, LEN, true>
78  {
79    typedef GR Digraph;
80    typedef LEN LengthMap;
81    typedef typename LengthMap::Value Value;
82#ifdef LEMON_HAVE_LONG_LONG
83    typedef long long LargeValue;
84#else
85    typedef long LargeValue;
86#endif
87    typedef lemon::Tolerance<LargeValue> Tolerance;
88    typedef lemon::Path<Digraph> Path;
89  };
90
91
92  /// \addtogroup shortest_path
93  /// @{
94
95  /// \brief Implementation of Howard's algorithm for finding a minimum
96  /// mean cycle.
97  ///
98  /// \ref MinMeanCycle implements Howard's algorithm for finding a
99  /// directed cycle of minimum mean length (cost) in a digraph.
100  ///
101  /// \tparam GR The type of the digraph the algorithm runs on.
102  /// \tparam LEN The type of the length map. The default
103  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
104#ifdef DOXYGEN
105  template <typename GR, typename LEN, typename TR>
106#else
107  template < typename GR,
108             typename LEN = typename GR::template ArcMap<int>,
109             typename TR = MinMeanCycleDefaultTraits<GR, LEN> >
110#endif
111  class MinMeanCycle
112  {
113  public:
114 
115    /// The type of the digraph
116    typedef typename TR::Digraph Digraph;
117    /// The type of the length map
118    typedef typename TR::LengthMap LengthMap;
119    /// The type of the arc lengths
120    typedef typename TR::Value Value;
121
122    /// \brief The large value type
123    ///
124    /// The large value type used for internal computations.
125    /// Using the \ref MinMeanCycleDefaultTraits "default traits class",
126    /// it is \c long \c long if the \c Value type is integer,
127    /// otherwise it is \c double.
128    typedef typename TR::LargeValue LargeValue;
129
130    /// The tolerance type
131    typedef typename TR::Tolerance Tolerance;
132
133    /// \brief The path type of the found cycles
134    ///
135    /// The path type of the found cycles.
136    /// Using the \ref MinMeanCycleDefaultTraits "default traits class",
137    /// it is \ref lemon::Path "Path<Digraph>".
138    typedef typename TR::Path Path;
139
140    /// The \ref MinMeanCycleDefaultTraits "traits class" of the algorithm
141    typedef TR Traits;
142
143  private:
144
145    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
146 
147    // The digraph the algorithm runs on
148    const Digraph &_gr;
149    // The length of the arcs
150    const LengthMap &_length;
151
152    // Data for the found cycles
153    bool _curr_found, _best_found;
154    LargeValue _curr_length, _best_length;
155    int _curr_size, _best_size;
156    Node _curr_node, _best_node;
157
158    Path *_cycle_path;
159    bool _local_path;
160
161    // Internal data used by the algorithm
162    typename Digraph::template NodeMap<Arc> _policy;
163    typename Digraph::template NodeMap<bool> _reached;
164    typename Digraph::template NodeMap<int> _level;
165    typename Digraph::template NodeMap<LargeValue> _dist;
166
167    // Data for storing the strongly connected components
168    int _comp_num;
169    typename Digraph::template NodeMap<int> _comp;
170    std::vector<std::vector<Node> > _comp_nodes;
171    std::vector<Node>* _nodes;
172    typename Digraph::template NodeMap<std::vector<Arc> > _in_arcs;
173   
174    // Queue used for BFS search
175    std::vector<Node> _queue;
176    int _qfront, _qback;
177
178    Tolerance _tolerance;
179 
180  public:
181 
182    /// \name Named Template Parameters
183    /// @{
184
185    template <typename T>
186    struct SetLargeValueTraits : public Traits {
187      typedef T LargeValue;
188      typedef lemon::Tolerance<T> Tolerance;
189    };
190
191    /// \brief \ref named-templ-param "Named parameter" for setting
192    /// \c LargeValue type.
193    ///
194    /// \ref named-templ-param "Named parameter" for setting \c LargeValue
195    /// type. It is used for internal computations in the algorithm.
196    template <typename T>
197    struct SetLargeValue
198      : public MinMeanCycle<GR, LEN, SetLargeValueTraits<T> > {
199      typedef MinMeanCycle<GR, LEN, SetLargeValueTraits<T> > Create;
200    };
201
202    template <typename T>
203    struct SetPathTraits : public Traits {
204      typedef T Path;
205    };
206
207    /// \brief \ref named-templ-param "Named parameter" for setting
208    /// \c %Path type.
209    ///
210    /// \ref named-templ-param "Named parameter" for setting the \c %Path
211    /// type of the found cycles.
212    /// It must conform to the \ref lemon::concepts::Path "Path" concept
213    /// and it must have an \c addBack() function.
214    template <typename T>
215    struct SetPath
216      : public MinMeanCycle<GR, LEN, SetPathTraits<T> > {
217      typedef MinMeanCycle<GR, LEN, SetPathTraits<T> > Create;
218    };
219   
220    /// @}
221
222  public:
223
224    /// \brief Constructor.
225    ///
226    /// The constructor of the class.
227    ///
228    /// \param digraph The digraph the algorithm runs on.
229    /// \param length The lengths (costs) of the arcs.
230    MinMeanCycle( const Digraph &digraph,
231                  const LengthMap &length ) :
232      _gr(digraph), _length(length), _cycle_path(NULL), _local_path(false),
233      _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
234      _comp(digraph), _in_arcs(digraph)
235    {}
236
237    /// Destructor.
238    ~MinMeanCycle() {
239      if (_local_path) delete _cycle_path;
240    }
241
242    /// \brief Set the path structure for storing the found cycle.
243    ///
244    /// This function sets an external path structure for storing the
245    /// found cycle.
246    ///
247    /// If you don't call this function before calling \ref run() or
248    /// \ref findMinMean(), it will allocate a local \ref Path "path"
249    /// structure. The destuctor deallocates this automatically
250    /// allocated object, of course.
251    ///
252    /// \note The algorithm calls only the \ref lemon::Path::addBack()
253    /// "addBack()" function of the given path structure.
254    ///
255    /// \return <tt>(*this)</tt>
256    ///
257    /// \sa cycle()
258    MinMeanCycle& cyclePath(Path &path) {
259      if (_local_path) {
260        delete _cycle_path;
261        _local_path = false;
262      }
263      _cycle_path = &path;
264      return *this;
265    }
266
267    /// \name Execution control
268    /// The simplest way to execute the algorithm is to call the \ref run()
269    /// function.\n
270    /// If you only need the minimum mean length, you may call
271    /// \ref findMinMean().
272
273    /// @{
274
275    /// \brief Run the algorithm.
276    ///
277    /// This function runs the algorithm.
278    /// It can be called more than once (e.g. if the underlying digraph
279    /// and/or the arc lengths have been modified).
280    ///
281    /// \return \c true if a directed cycle exists in the digraph.
282    ///
283    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
284    /// \code
285    ///   return mmc.findMinMean() && mmc.findCycle();
286    /// \endcode
287    bool run() {
288      return findMinMean() && findCycle();
289    }
290
291    /// \brief Find the minimum cycle mean.
292    ///
293    /// This function finds the minimum mean length of the directed
294    /// cycles in the digraph.
295    ///
296    /// \return \c true if a directed cycle exists in the digraph.
297    bool findMinMean() {
298      // Initialize and find strongly connected components
299      init();
300      findComponents();
301     
302      // Find the minimum cycle mean in the components
303      for (int comp = 0; comp < _comp_num; ++comp) {
304        // Find the minimum mean cycle in the current component
305        if (!buildPolicyGraph(comp)) continue;
306        while (true) {
307          findPolicyCycle();
308          if (!computeNodeDistances()) break;
309        }
310        // Update the best cycle (global minimum mean cycle)
311        if ( !_best_found || (_curr_found &&
312             _curr_length * _best_size < _best_length * _curr_size) ) {
313          _best_found = true;
314          _best_length = _curr_length;
315          _best_size = _curr_size;
316          _best_node = _curr_node;
317        }
318      }
319      return _best_found;
320    }
321
322    /// \brief Find a minimum mean directed cycle.
323    ///
324    /// This function finds a directed cycle of minimum mean length
325    /// in the digraph using the data computed by findMinMean().
326    ///
327    /// \return \c true if a directed cycle exists in the digraph.
328    ///
329    /// \pre \ref findMinMean() must be called before using this function.
330    bool findCycle() {
331      if (!_best_found) return false;
332      _cycle_path->addBack(_policy[_best_node]);
333      for ( Node v = _best_node;
334            (v = _gr.target(_policy[v])) != _best_node; ) {
335        _cycle_path->addBack(_policy[v]);
336      }
337      return true;
338    }
339
340    /// @}
341
342    /// \name Query Functions
343    /// The results of the algorithm can be obtained using these
344    /// functions.\n
345    /// The algorithm should be executed before using them.
346
347    /// @{
348
349    /// \brief Return the total length of the found cycle.
350    ///
351    /// This function returns the total length of the found cycle.
352    ///
353    /// \pre \ref run() or \ref findMinMean() must be called before
354    /// using this function.
355    LargeValue cycleLength() const {
356      return _best_length;
357    }
358
359    /// \brief Return the number of arcs on the found cycle.
360    ///
361    /// This function returns the number of arcs on the found cycle.
362    ///
363    /// \pre \ref run() or \ref findMinMean() must be called before
364    /// using this function.
365    int cycleArcNum() const {
366      return _best_size;
367    }
368
369    /// \brief Return the mean length of the found cycle.
370    ///
371    /// This function returns the mean length of the found cycle.
372    ///
373    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
374    /// following code.
375    /// \code
376    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
377    /// \endcode
378    ///
379    /// \pre \ref run() or \ref findMinMean() must be called before
380    /// using this function.
381    double cycleMean() const {
382      return static_cast<double>(_best_length) / _best_size;
383    }
384
385    /// \brief Return the found cycle.
386    ///
387    /// This function returns a const reference to the path structure
388    /// storing the found cycle.
389    ///
390    /// \pre \ref run() or \ref findCycle() must be called before using
391    /// this function.
392    ///
393    /// \sa cyclePath()
394    const Path& cycle() const {
395      return *_cycle_path;
396    }
397
398    ///@}
399
400  private:
401
402    // Initialize
403    void init() {
404      if (!_cycle_path) {
405        _local_path = true;
406        _cycle_path = new Path;
407      }
408      _queue.resize(countNodes(_gr));
409      _best_found = false;
410      _best_length = 0;
411      _best_size = 1;
412      _cycle_path->clear();
413    }
414   
415    // Find strongly connected components and initialize _comp_nodes
416    // and _in_arcs
417    void findComponents() {
418      _comp_num = stronglyConnectedComponents(_gr, _comp);
419      _comp_nodes.resize(_comp_num);
420      if (_comp_num == 1) {
421        _comp_nodes[0].clear();
422        for (NodeIt n(_gr); n != INVALID; ++n) {
423          _comp_nodes[0].push_back(n);
424          _in_arcs[n].clear();
425          for (InArcIt a(_gr, n); a != INVALID; ++a) {
426            _in_arcs[n].push_back(a);
427          }
428        }
429      } else {
430        for (int i = 0; i < _comp_num; ++i)
431          _comp_nodes[i].clear();
432        for (NodeIt n(_gr); n != INVALID; ++n) {
433          int k = _comp[n];
434          _comp_nodes[k].push_back(n);
435          _in_arcs[n].clear();
436          for (InArcIt a(_gr, n); a != INVALID; ++a) {
437            if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
438          }
439        }
440      }
441    }
442
443    // Build the policy graph in the given strongly connected component
444    // (the out-degree of every node is 1)
445    bool buildPolicyGraph(int comp) {
446      _nodes = &(_comp_nodes[comp]);
447      if (_nodes->size() < 1 ||
448          (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
449        return false;
450      }
451      for (int i = 0; i < int(_nodes->size()); ++i) {
452        _dist[(*_nodes)[i]] = std::numeric_limits<LargeValue>::max();
453      }
454      Node u, v;
455      Arc e;
456      for (int i = 0; i < int(_nodes->size()); ++i) {
457        v = (*_nodes)[i];
458        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
459          e = _in_arcs[v][j];
460          u = _gr.source(e);
461          if (_length[e] < _dist[u]) {
462            _dist[u] = _length[e];
463            _policy[u] = e;
464          }
465        }
466      }
467      return true;
468    }
469
470    // Find the minimum mean cycle in the policy graph
471    void findPolicyCycle() {
472      for (int i = 0; i < int(_nodes->size()); ++i) {
473        _level[(*_nodes)[i]] = -1;
474      }
475      LargeValue clength;
476      int csize;
477      Node u, v;
478      _curr_found = false;
479      for (int i = 0; i < int(_nodes->size()); ++i) {
480        u = (*_nodes)[i];
481        if (_level[u] >= 0) continue;
482        for (; _level[u] < 0; u = _gr.target(_policy[u])) {
483          _level[u] = i;
484        }
485        if (_level[u] == i) {
486          // A cycle is found
487          clength = _length[_policy[u]];
488          csize = 1;
489          for (v = u; (v = _gr.target(_policy[v])) != u; ) {
490            clength += _length[_policy[v]];
491            ++csize;
492          }
493          if ( !_curr_found ||
494               (clength * _curr_size < _curr_length * csize) ) {
495            _curr_found = true;
496            _curr_length = clength;
497            _curr_size = csize;
498            _curr_node = u;
499          }
500        }
501      }
502    }
503
504    // Contract the policy graph and compute node distances
505    bool computeNodeDistances() {
506      // Find the component of the main cycle and compute node distances
507      // using reverse BFS
508      for (int i = 0; i < int(_nodes->size()); ++i) {
509        _reached[(*_nodes)[i]] = false;
510      }
511      _qfront = _qback = 0;
512      _queue[0] = _curr_node;
513      _reached[_curr_node] = true;
514      _dist[_curr_node] = 0;
515      Node u, v;
516      Arc e;
517      while (_qfront <= _qback) {
518        v = _queue[_qfront++];
519        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
520          e = _in_arcs[v][j];
521          u = _gr.source(e);
522          if (_policy[u] == e && !_reached[u]) {
523            _reached[u] = true;
524            _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
525            _queue[++_qback] = u;
526          }
527        }
528      }
529
530      // Connect all other nodes to this component and compute node
531      // distances using reverse BFS
532      _qfront = 0;
533      while (_qback < int(_nodes->size())-1) {
534        v = _queue[_qfront++];
535        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
536          e = _in_arcs[v][j];
537          u = _gr.source(e);
538          if (!_reached[u]) {
539            _reached[u] = true;
540            _policy[u] = e;
541            _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
542            _queue[++_qback] = u;
543          }
544        }
545      }
546
547      // Improve node distances
548      bool improved = false;
549      for (int i = 0; i < int(_nodes->size()); ++i) {
550        v = (*_nodes)[i];
551        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
552          e = _in_arcs[v][j];
553          u = _gr.source(e);
554          LargeValue delta = _dist[v] + _length[e] * _curr_size - _curr_length;
555          if (_tolerance.less(delta, _dist[u])) {
556            _dist[u] = delta;
557            _policy[u] = e;
558            improved = true;
559          }
560        }
561      }
562      return improved;
563    }
564
565  }; //class MinMeanCycle
566
567  ///@}
568
569} //namespace lemon
570
571#endif //LEMON_MIN_MEAN_CYCLE_H
Note: See TracBrowser for help on using the repository browser.