COIN-OR::LEMON - Graph Library

source: lemon-1.2/lemon/min_mean_cycle.h @ 760:83ce7ce39f21

Last change on this file since 760:83ce7ce39f21 was 760:83ce7ce39f21, checked in by Peter Kovacs <kpeter@…>, 10 years ago

Rework and fix the implementation of MinMeanCycle? (#179)

  • Fix the handling of the cycle means.
  • Many implementation improvements:
    • More efficient data storage for the strongly connected components.
    • Better handling of BFS queues.
    • Merge consecutive BFS searches (perform two BFS searches instead of three).

This version is about two times faster on average and an order of
magnitude faster if there are a lot of strongly connected components.

File size: 13.3 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  /// \addtogroup shortest_path
36  /// @{
37
38  /// \brief Implementation of Howard's algorithm for finding a minimum
39  /// mean cycle.
40  ///
41  /// \ref MinMeanCycle implements Howard's algorithm for finding a
42  /// directed cycle of minimum mean length (cost) in a digraph.
43  ///
44  /// \tparam GR The type of the digraph the algorithm runs on.
45  /// \tparam LEN The type of the length map. The default
46  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
47  ///
48  /// \warning \c LEN::Value must be convertible to \c double.
49#ifdef DOXYGEN
50  template <typename GR, typename LEN>
51#else
52  template < typename GR,
53             typename LEN = typename GR::template ArcMap<int> >
54#endif
55  class MinMeanCycle
56  {
57  public:
58 
59    /// The type of the digraph the algorithm runs on
60    typedef GR Digraph;
61    /// The type of the length map
62    typedef LEN LengthMap;
63    /// The type of the arc lengths
64    typedef typename LengthMap::Value Value;
65    /// The type of the paths
66    typedef lemon::Path<Digraph> Path;
67
68  private:
69
70    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
71 
72    // The digraph the algorithm runs on
73    const Digraph &_gr;
74    // The length of the arcs
75    const LengthMap &_length;
76
77    // Data for the found cycles
78    bool _curr_found, _best_found;
79    Value _curr_length, _best_length;
80    int _curr_size, _best_size;
81    Node _curr_node, _best_node;
82
83    Path *_cycle_path;
84    bool _local_path;
85
86    // Internal data used by the algorithm
87    typename Digraph::template NodeMap<Arc> _policy;
88    typename Digraph::template NodeMap<bool> _reached;
89    typename Digraph::template NodeMap<int> _level;
90    typename Digraph::template NodeMap<double> _dist;
91
92    // Data for storing the strongly connected components
93    int _comp_num;
94    typename Digraph::template NodeMap<int> _comp;
95    std::vector<std::vector<Node> > _comp_nodes;
96    std::vector<Node>* _nodes;
97    typename Digraph::template NodeMap<std::vector<Arc> > _in_arcs;
98   
99    // Queue used for BFS search
100    std::vector<Node> _queue;
101    int _qfront, _qback;
102   
103    Tolerance<double> _tol;
104
105  public:
106
107    /// \brief Constructor.
108    ///
109    /// The constructor of the class.
110    ///
111    /// \param digraph The digraph the algorithm runs on.
112    /// \param length The lengths (costs) of the arcs.
113    MinMeanCycle( const Digraph &digraph,
114                  const LengthMap &length ) :
115      _gr(digraph), _length(length), _cycle_path(NULL), _local_path(false),
116      _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
117      _comp(digraph), _in_arcs(digraph)
118    {}
119
120    /// Destructor.
121    ~MinMeanCycle() {
122      if (_local_path) delete _cycle_path;
123    }
124
125    /// \brief Set the path structure for storing the found cycle.
126    ///
127    /// This function sets an external path structure for storing the
128    /// found cycle.
129    ///
130    /// If you don't call this function before calling \ref run() or
131    /// \ref findMinMean(), it will allocate a local \ref Path "path"
132    /// structure. The destuctor deallocates this automatically
133    /// allocated object, of course.
134    ///
135    /// \note The algorithm calls only the \ref lemon::Path::addBack()
136    /// "addBack()" function of the given path structure.
137    ///
138    /// \return <tt>(*this)</tt>
139    ///
140    /// \sa cycle()
141    MinMeanCycle& cyclePath(Path &path) {
142      if (_local_path) {
143        delete _cycle_path;
144        _local_path = false;
145      }
146      _cycle_path = &path;
147      return *this;
148    }
149
150    /// \name Execution control
151    /// The simplest way to execute the algorithm is to call the \ref run()
152    /// function.\n
153    /// If you only need the minimum mean length, you may call
154    /// \ref findMinMean().
155
156    /// @{
157
158    /// \brief Run the algorithm.
159    ///
160    /// This function runs the algorithm.
161    /// It can be called more than once (e.g. if the underlying digraph
162    /// and/or the arc lengths have been modified).
163    ///
164    /// \return \c true if a directed cycle exists in the digraph.
165    ///
166    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
167    /// \code
168    ///   return mmc.findMinMean() && mmc.findCycle();
169    /// \endcode
170    bool run() {
171      return findMinMean() && findCycle();
172    }
173
174    /// \brief Find the minimum cycle mean.
175    ///
176    /// This function finds the minimum mean length of the directed
177    /// cycles in the digraph.
178    ///
179    /// \return \c true if a directed cycle exists in the digraph.
180    bool findMinMean() {
181      // Initialize and find strongly connected components
182      init();
183      findComponents();
184     
185      // Find the minimum cycle mean in the components
186      for (int comp = 0; comp < _comp_num; ++comp) {
187        // Find the minimum mean cycle in the current component
188        if (!buildPolicyGraph(comp)) continue;
189        while (true) {
190          findPolicyCycle();
191          if (!computeNodeDistances()) break;
192        }
193        // Update the best cycle (global minimum mean cycle)
194        if ( !_best_found || (_curr_found &&
195             _curr_length * _best_size < _best_length * _curr_size) ) {
196          _best_found = true;
197          _best_length = _curr_length;
198          _best_size = _curr_size;
199          _best_node = _curr_node;
200        }
201      }
202      return _best_found;
203    }
204
205    /// \brief Find a minimum mean directed cycle.
206    ///
207    /// This function finds a directed cycle of minimum mean length
208    /// in the digraph using the data computed by findMinMean().
209    ///
210    /// \return \c true if a directed cycle exists in the digraph.
211    ///
212    /// \pre \ref findMinMean() must be called before using this function.
213    bool findCycle() {
214      if (!_best_found) return false;
215      _cycle_path->addBack(_policy[_best_node]);
216      for ( Node v = _best_node;
217            (v = _gr.target(_policy[v])) != _best_node; ) {
218        _cycle_path->addBack(_policy[v]);
219      }
220      return true;
221    }
222
223    /// @}
224
225    /// \name Query Functions
226    /// The results of the algorithm can be obtained using these
227    /// functions.\n
228    /// The algorithm should be executed before using them.
229
230    /// @{
231
232    /// \brief Return the total length of the found cycle.
233    ///
234    /// This function returns the total length of the found cycle.
235    ///
236    /// \pre \ref run() or \ref findMinMean() must be called before
237    /// using this function.
238    Value cycleLength() const {
239      return _best_length;
240    }
241
242    /// \brief Return the number of arcs on the found cycle.
243    ///
244    /// This function returns the number of arcs on the found cycle.
245    ///
246    /// \pre \ref run() or \ref findMinMean() must be called before
247    /// using this function.
248    int cycleArcNum() const {
249      return _best_size;
250    }
251
252    /// \brief Return the mean length of the found cycle.
253    ///
254    /// This function returns the mean length of the found cycle.
255    ///
256    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
257    /// following code.
258    /// \code
259    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
260    /// \endcode
261    ///
262    /// \pre \ref run() or \ref findMinMean() must be called before
263    /// using this function.
264    double cycleMean() const {
265      return static_cast<double>(_best_length) / _best_size;
266    }
267
268    /// \brief Return the found cycle.
269    ///
270    /// This function returns a const reference to the path structure
271    /// storing the found cycle.
272    ///
273    /// \pre \ref run() or \ref findCycle() must be called before using
274    /// this function.
275    ///
276    /// \sa cyclePath()
277    const Path& cycle() const {
278      return *_cycle_path;
279    }
280
281    ///@}
282
283  private:
284
285    // Initialize
286    void init() {
287      _tol.epsilon(1e-6);
288      if (!_cycle_path) {
289        _local_path = true;
290        _cycle_path = new Path;
291      }
292      _queue.resize(countNodes(_gr));
293      _best_found = false;
294      _best_length = 0;
295      _best_size = 1;
296      _cycle_path->clear();
297    }
298   
299    // Find strongly connected components and initialize _comp_nodes
300    // and _in_arcs
301    void findComponents() {
302      _comp_num = stronglyConnectedComponents(_gr, _comp);
303      _comp_nodes.resize(_comp_num);
304      if (_comp_num == 1) {
305        _comp_nodes[0].clear();
306        for (NodeIt n(_gr); n != INVALID; ++n) {
307          _comp_nodes[0].push_back(n);
308          _in_arcs[n].clear();
309          for (InArcIt a(_gr, n); a != INVALID; ++a) {
310            _in_arcs[n].push_back(a);
311          }
312        }
313      } else {
314        for (int i = 0; i < _comp_num; ++i)
315          _comp_nodes[i].clear();
316        for (NodeIt n(_gr); n != INVALID; ++n) {
317          int k = _comp[n];
318          _comp_nodes[k].push_back(n);
319          _in_arcs[n].clear();
320          for (InArcIt a(_gr, n); a != INVALID; ++a) {
321            if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
322          }
323        }
324      }
325    }
326
327    // Build the policy graph in the given strongly connected component
328    // (the out-degree of every node is 1)
329    bool buildPolicyGraph(int comp) {
330      _nodes = &(_comp_nodes[comp]);
331      if (_nodes->size() < 1 ||
332          (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
333        return false;
334      }
335      for (int i = 0; i < int(_nodes->size()); ++i) {
336        _dist[(*_nodes)[i]] = std::numeric_limits<double>::max();
337      }
338      Node u, v;
339      Arc e;
340      for (int i = 0; i < int(_nodes->size()); ++i) {
341        v = (*_nodes)[i];
342        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
343          e = _in_arcs[v][j];
344          u = _gr.source(e);
345          if (_length[e] < _dist[u]) {
346            _dist[u] = _length[e];
347            _policy[u] = e;
348          }
349        }
350      }
351      return true;
352    }
353
354    // Find the minimum mean cycle in the policy graph
355    void findPolicyCycle() {
356      for (int i = 0; i < int(_nodes->size()); ++i) {
357        _level[(*_nodes)[i]] = -1;
358      }
359      Value clength;
360      int csize;
361      Node u, v;
362      _curr_found = false;
363      for (int i = 0; i < int(_nodes->size()); ++i) {
364        u = (*_nodes)[i];
365        if (_level[u] >= 0) continue;
366        for (; _level[u] < 0; u = _gr.target(_policy[u])) {
367          _level[u] = i;
368        }
369        if (_level[u] == i) {
370          // A cycle is found
371          clength = _length[_policy[u]];
372          csize = 1;
373          for (v = u; (v = _gr.target(_policy[v])) != u; ) {
374            clength += _length[_policy[v]];
375            ++csize;
376          }
377          if ( !_curr_found ||
378               (clength * _curr_size < _curr_length * csize) ) {
379            _curr_found = true;
380            _curr_length = clength;
381            _curr_size = csize;
382            _curr_node = u;
383          }
384        }
385      }
386    }
387
388    // Contract the policy graph and compute node distances
389    bool computeNodeDistances() {
390      // Find the component of the main cycle and compute node distances
391      // using reverse BFS
392      for (int i = 0; i < int(_nodes->size()); ++i) {
393        _reached[(*_nodes)[i]] = false;
394      }
395      double curr_mean = double(_curr_length) / _curr_size;
396      _qfront = _qback = 0;
397      _queue[0] = _curr_node;
398      _reached[_curr_node] = true;
399      _dist[_curr_node] = 0;
400      Node u, v;
401      Arc e;
402      while (_qfront <= _qback) {
403        v = _queue[_qfront++];
404        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
405          e = _in_arcs[v][j];
406          u = _gr.source(e);
407          if (_policy[u] == e && !_reached[u]) {
408            _reached[u] = true;
409            _dist[u] = _dist[v] + _length[e] - curr_mean;
410            _queue[++_qback] = u;
411          }
412        }
413      }
414
415      // Connect all other nodes to this component and compute node
416      // distances using reverse BFS
417      _qfront = 0;
418      while (_qback < int(_nodes->size())-1) {
419        v = _queue[_qfront++];
420        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
421          e = _in_arcs[v][j];
422          u = _gr.source(e);
423          if (!_reached[u]) {
424            _reached[u] = true;
425            _policy[u] = e;
426            _dist[u] = _dist[v] + _length[e] - curr_mean;
427            _queue[++_qback] = u;
428          }
429        }
430      }
431
432      // Improve node distances
433      bool improved = false;
434      for (int i = 0; i < int(_nodes->size()); ++i) {
435        v = (*_nodes)[i];
436        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
437          e = _in_arcs[v][j];
438          u = _gr.source(e);
439          double delta = _dist[v] + _length[e] - curr_mean;
440          if (_tol.less(delta, _dist[u])) {
441            _dist[u] = delta;
442            _policy[u] = e;
443            improved = true;
444          }
445        }
446      }
447      return improved;
448    }
449
450  }; //class MinMeanCycle
451
452  ///@}
453
454} //namespace lemon
455
456#endif //LEMON_MIN_MEAN_CYCLE_H
Note: See TracBrowser for help on using the repository browser.