COIN-OR::LEMON - Graph Library

source: lemon/lemon/howard.h @ 814:11c946fa8d13

Last change on this file since 814:11c946fa8d13 was 814:11c946fa8d13, checked in by Peter Kovacs <kpeter@…>, 15 years ago

Simplify comparisons in min mean cycle classes (#179)
using extreme INF values instead of bool flags.

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