lemon/min_mean_cycle.h
changeset 805 b31e130db13d
child 806 d66ff32624e2
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/lemon/min_mean_cycle.h	Mon Aug 03 14:12:55 2009 +0200
     1.3 @@ -0,0 +1,462 @@
     1.4 +/* -*- C++ -*-
     1.5 + *
     1.6 + * This file is a part of LEMON, a generic C++ optimization library
     1.7 + *
     1.8 + * Copyright (C) 2003-2008
     1.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
    1.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
    1.11 + *
    1.12 + * Permission to use, modify and distribute this software is granted
    1.13 + * provided that this copyright notice appears in all copies. For
    1.14 + * precise terms see the accompanying LICENSE file.
    1.15 + *
    1.16 + * This software is provided "AS IS" with no warranty of any kind,
    1.17 + * express or implied, and with no claim as to its suitability for any
    1.18 + * purpose.
    1.19 + *
    1.20 + */
    1.21 +
    1.22 +#ifndef LEMON_MIN_MEAN_CYCLE_H
    1.23 +#define LEMON_MIN_MEAN_CYCLE_H
    1.24 +
    1.25 +/// \ingroup shortest_path
    1.26 +///
    1.27 +/// \file
    1.28 +/// \brief Howard's algorithm for finding a minimum mean cycle.
    1.29 +
    1.30 +#include <vector>
    1.31 +#include <lemon/core.h>
    1.32 +#include <lemon/path.h>
    1.33 +#include <lemon/tolerance.h>
    1.34 +#include <lemon/connectivity.h>
    1.35 +
    1.36 +namespace lemon {
    1.37 +
    1.38 +  /// \addtogroup shortest_path
    1.39 +  /// @{
    1.40 +
    1.41 +  /// \brief Implementation of Howard's algorithm for finding a minimum
    1.42 +  /// mean cycle.
    1.43 +  ///
    1.44 +  /// \ref MinMeanCycle implements Howard's algorithm for finding a
    1.45 +  /// directed cycle of minimum mean length (cost) in a digraph.
    1.46 +  ///
    1.47 +  /// \tparam GR The type of the digraph the algorithm runs on.
    1.48 +  /// \tparam LEN The type of the length map. The default
    1.49 +  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
    1.50 +  ///
    1.51 +  /// \warning \c LEN::Value must be convertible to \c double.
    1.52 +#ifdef DOXYGEN
    1.53 +  template <typename GR, typename LEN>
    1.54 +#else
    1.55 +  template < typename GR,
    1.56 +             typename LEN = typename GR::template ArcMap<int> >
    1.57 +#endif
    1.58 +  class MinMeanCycle
    1.59 +  {
    1.60 +  public:
    1.61 +  
    1.62 +    /// The type of the digraph the algorithm runs on
    1.63 +    typedef GR Digraph;
    1.64 +    /// The type of the length map
    1.65 +    typedef LEN LengthMap;
    1.66 +    /// The type of the arc lengths
    1.67 +    typedef typename LengthMap::Value Value;
    1.68 +    /// The type of the paths
    1.69 +    typedef lemon::Path<Digraph> Path;
    1.70 +
    1.71 +  private:
    1.72 +
    1.73 +    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
    1.74 +  
    1.75 +    // The digraph the algorithm runs on
    1.76 +    const Digraph &_gr;
    1.77 +    // The length of the arcs
    1.78 +    const LengthMap &_length;
    1.79 +
    1.80 +    // The total length of the found cycle
    1.81 +    Value _cycle_length;
    1.82 +    // The number of arcs on the found cycle
    1.83 +    int _cycle_size;
    1.84 +    // The found cycle
    1.85 +    Path *_cycle_path;
    1.86 +
    1.87 +    bool _local_path;
    1.88 +    bool _cycle_found;
    1.89 +    Node _cycle_node;
    1.90 +
    1.91 +    typename Digraph::template NodeMap<bool> _reached;
    1.92 +    typename Digraph::template NodeMap<double> _dist;
    1.93 +    typename Digraph::template NodeMap<Arc> _policy;
    1.94 +
    1.95 +    typename Digraph::template NodeMap<int> _comp;
    1.96 +    int _comp_num;
    1.97 +
    1.98 +    std::vector<Node> _nodes;
    1.99 +    std::vector<Arc> _arcs;
   1.100 +    Tolerance<double> _tol;
   1.101 +
   1.102 +  public:
   1.103 +
   1.104 +    /// \brief Constructor.
   1.105 +    ///
   1.106 +    /// The constructor of the class.
   1.107 +    ///
   1.108 +    /// \param digraph The digraph the algorithm runs on.
   1.109 +    /// \param length The lengths (costs) of the arcs.
   1.110 +    MinMeanCycle( const Digraph &digraph,
   1.111 +                  const LengthMap &length ) :
   1.112 +      _gr(digraph), _length(length), _cycle_length(0), _cycle_size(-1),
   1.113 +      _cycle_path(NULL), _local_path(false), _reached(digraph),
   1.114 +      _dist(digraph), _policy(digraph), _comp(digraph)
   1.115 +    {}
   1.116 +
   1.117 +    /// Destructor.
   1.118 +    ~MinMeanCycle() {
   1.119 +      if (_local_path) delete _cycle_path;
   1.120 +    }
   1.121 +
   1.122 +    /// \brief Set the path structure for storing the found cycle.
   1.123 +    ///
   1.124 +    /// This function sets an external path structure for storing the
   1.125 +    /// found cycle.
   1.126 +    ///
   1.127 +    /// If you don't call this function before calling \ref run() or
   1.128 +    /// \ref init(), it will allocate a local \ref Path "path"
   1.129 +    /// structure. The destuctor deallocates this automatically
   1.130 +    /// allocated object, of course.
   1.131 +    ///
   1.132 +    /// \note The algorithm calls only the \ref lemon::Path::addBack()
   1.133 +    /// "addBack()" function of the given path structure.
   1.134 +    ///
   1.135 +    /// \return <tt>(*this)</tt>
   1.136 +    ///
   1.137 +    /// \sa cycle()
   1.138 +    MinMeanCycle& cyclePath(Path &path) {
   1.139 +      if (_local_path) {
   1.140 +        delete _cycle_path;
   1.141 +        _local_path = false;
   1.142 +      }
   1.143 +      _cycle_path = &path;
   1.144 +      return *this;
   1.145 +    }
   1.146 +
   1.147 +    /// \name Execution control
   1.148 +    /// The simplest way to execute the algorithm is to call the \ref run()
   1.149 +    /// function.\n
   1.150 +    /// If you only need the minimum mean length, you may call \ref init()
   1.151 +    /// and \ref findMinMean().
   1.152 +    /// If you would like to run the algorithm again (e.g. the underlying
   1.153 +    /// digraph and/or the arc lengths has been modified), you may not
   1.154 +    /// create a new instance of the class, rather call \ref reset(),
   1.155 +    /// \ref findMinMean() and \ref findCycle() instead.
   1.156 +
   1.157 +    /// @{
   1.158 +
   1.159 +    /// \brief Run the algorithm.
   1.160 +    ///
   1.161 +    /// This function runs the algorithm.
   1.162 +    ///
   1.163 +    /// \return \c true if a directed cycle exists in the digraph.
   1.164 +    ///
   1.165 +    /// \note Apart from the return value, <tt>mmc.run()</tt> is just a
   1.166 +    /// shortcut of the following code.
   1.167 +    /// \code
   1.168 +    ///   mmc.init();
   1.169 +    ///   mmc.findMinMean();
   1.170 +    ///   mmc.findCycle();
   1.171 +    /// \endcode
   1.172 +    bool run() {
   1.173 +      init();
   1.174 +      return findMinMean() && findCycle();
   1.175 +    }
   1.176 +
   1.177 +    /// \brief Initialize the internal data structures.
   1.178 +    ///
   1.179 +    /// This function initializes the internal data structures.
   1.180 +    ///
   1.181 +    /// \sa reset()
   1.182 +    void init() {
   1.183 +      _tol.epsilon(1e-6);
   1.184 +      if (!_cycle_path) {
   1.185 +        _local_path = true;
   1.186 +        _cycle_path = new Path;
   1.187 +      }
   1.188 +      _cycle_found = false;
   1.189 +      _comp_num = stronglyConnectedComponents(_gr, _comp);
   1.190 +    }
   1.191 +
   1.192 +    /// \brief Reset the internal data structures.
   1.193 +    ///
   1.194 +    /// This function resets the internal data structures so that
   1.195 +    /// findMinMean() and findCycle() can be called again (e.g. when the
   1.196 +    /// underlying digraph and/or the arc lengths has been modified).
   1.197 +    ///
   1.198 +    /// \sa init()
   1.199 +    void reset() {
   1.200 +      if (_cycle_path) _cycle_path->clear();
   1.201 +      _cycle_found = false;
   1.202 +      _comp_num = stronglyConnectedComponents(_gr, _comp);
   1.203 +    }
   1.204 +
   1.205 +    /// \brief Find the minimum cycle mean.
   1.206 +    ///
   1.207 +    /// This function computes all the required data and finds the
   1.208 +    /// minimum mean length of the directed cycles in the digraph.
   1.209 +    ///
   1.210 +    /// \return \c true if a directed cycle exists in the digraph.
   1.211 +    ///
   1.212 +    /// \pre \ref init() must be called before using this function.
   1.213 +    bool findMinMean() {
   1.214 +      // Find the minimum cycle mean in the components
   1.215 +      for (int comp = 0; comp < _comp_num; ++comp) {
   1.216 +        if (!initCurrentComponent(comp)) continue;
   1.217 +        while (true) {
   1.218 +          if (!findPolicyCycles()) break;
   1.219 +          contractPolicyGraph(comp);
   1.220 +          if (!computeNodeDistances()) break;
   1.221 +        }
   1.222 +      }
   1.223 +      return _cycle_found;
   1.224 +    }
   1.225 +
   1.226 +    /// \brief Find a minimum mean directed cycle.
   1.227 +    ///
   1.228 +    /// This function finds a directed cycle of minimum mean length
   1.229 +    /// in the digraph using the data computed by findMinMean().
   1.230 +    ///
   1.231 +    /// \return \c true if a directed cycle exists in the digraph.
   1.232 +    ///
   1.233 +    /// \pre \ref init() and \ref findMinMean() must be called before
   1.234 +    /// using this function.
   1.235 +    bool findCycle() {
   1.236 +      if (!_cycle_found) return false;
   1.237 +      _cycle_path->addBack(_policy[_cycle_node]);
   1.238 +      for ( Node v = _cycle_node;
   1.239 +            (v = _gr.target(_policy[v])) != _cycle_node; ) {
   1.240 +        _cycle_path->addBack(_policy[v]);
   1.241 +      }
   1.242 +      return true;
   1.243 +    }
   1.244 +
   1.245 +    /// @}
   1.246 +
   1.247 +    /// \name Query Functions
   1.248 +    /// The result of the algorithm can be obtained using these
   1.249 +    /// functions.\n
   1.250 +    /// The algorithm should be executed before using them.
   1.251 +
   1.252 +    /// @{
   1.253 +
   1.254 +    /// \brief Return the total length of the found cycle.
   1.255 +    ///
   1.256 +    /// This function returns the total length of the found cycle.
   1.257 +    ///
   1.258 +    /// \pre \ref run() or \ref findCycle() must be called before
   1.259 +    /// using this function.
   1.260 +    Value cycleLength() const {
   1.261 +      return _cycle_length;
   1.262 +    }
   1.263 +
   1.264 +    /// \brief Return the number of arcs on the found cycle.
   1.265 +    ///
   1.266 +    /// This function returns the number of arcs on the found cycle.
   1.267 +    ///
   1.268 +    /// \pre \ref run() or \ref findCycle() must be called before
   1.269 +    /// using this function.
   1.270 +    int cycleArcNum() const {
   1.271 +      return _cycle_size;
   1.272 +    }
   1.273 +
   1.274 +    /// \brief Return the mean length of the found cycle.
   1.275 +    ///
   1.276 +    /// This function returns the mean length of the found cycle.
   1.277 +    ///
   1.278 +    /// \note <tt>mmc.cycleMean()</tt> is just a shortcut of the
   1.279 +    /// following code.
   1.280 +    /// \code
   1.281 +    ///   return double(mmc.cycleLength()) / mmc.cycleArcNum();
   1.282 +    /// \endcode
   1.283 +    ///
   1.284 +    /// \pre \ref run() or \ref findMinMean() must be called before
   1.285 +    /// using this function.
   1.286 +    double cycleMean() const {
   1.287 +      return double(_cycle_length) / _cycle_size;
   1.288 +    }
   1.289 +
   1.290 +    /// \brief Return the found cycle.
   1.291 +    ///
   1.292 +    /// This function returns a const reference to the path structure
   1.293 +    /// storing the found cycle.
   1.294 +    ///
   1.295 +    /// \pre \ref run() or \ref findCycle() must be called before using
   1.296 +    /// this function.
   1.297 +    ///
   1.298 +    /// \sa cyclePath()
   1.299 +    const Path& cycle() const {
   1.300 +      return *_cycle_path;
   1.301 +    }
   1.302 +
   1.303 +    ///@}
   1.304 +
   1.305 +  private:
   1.306 +
   1.307 +    // Initialize the internal data structures for the current strongly
   1.308 +    // connected component and create the policy graph.
   1.309 +    // The policy graph can be represented by the _policy map because
   1.310 +    // the out-degree of every node is 1.
   1.311 +    bool initCurrentComponent(int comp) {
   1.312 +      // Find the nodes of the current component
   1.313 +      _nodes.clear();
   1.314 +      for (NodeIt n(_gr); n != INVALID; ++n) {
   1.315 +        if (_comp[n] == comp) _nodes.push_back(n);
   1.316 +      }
   1.317 +      if (_nodes.size() <= 1) return false;
   1.318 +      // Find the arcs of the current component
   1.319 +      _arcs.clear();
   1.320 +      for (ArcIt e(_gr); e != INVALID; ++e) {
   1.321 +        if ( _comp[_gr.source(e)] == comp &&
   1.322 +             _comp[_gr.target(e)] == comp )
   1.323 +          _arcs.push_back(e);
   1.324 +      }
   1.325 +      // Initialize _reached, _dist, _policy maps
   1.326 +      for (int i = 0; i < int(_nodes.size()); ++i) {
   1.327 +        _reached[_nodes[i]] = false;
   1.328 +        _policy[_nodes[i]] = INVALID;
   1.329 +      }
   1.330 +      Node u; Arc e;
   1.331 +      for (int j = 0; j < int(_arcs.size()); ++j) {
   1.332 +        e = _arcs[j];
   1.333 +        u = _gr.source(e);
   1.334 +        if (!_reached[u] || _length[e] < _dist[u]) {
   1.335 +          _dist[u] = _length[e];
   1.336 +          _policy[u] = e;
   1.337 +          _reached[u] = true;
   1.338 +        }
   1.339 +      }
   1.340 +      return true;
   1.341 +    }
   1.342 +
   1.343 +    // Find all cycles in the policy graph.
   1.344 +    // Set _cycle_found to true if a cycle is found and set
   1.345 +    // _cycle_length, _cycle_size, _cycle_node to represent the minimum
   1.346 +    // mean cycle in the policy graph.
   1.347 +    bool findPolicyCycles() {
   1.348 +      typename Digraph::template NodeMap<int> level(_gr, -1);
   1.349 +      bool curr_cycle_found = false;
   1.350 +      Value clength;
   1.351 +      int csize;
   1.352 +      int path_cnt = 0;
   1.353 +      Node u, v;
   1.354 +      // Searching for cycles
   1.355 +      for (int i = 0; i < int(_nodes.size()); ++i) {
   1.356 +        if (level[_nodes[i]] < 0) {
   1.357 +          u = _nodes[i];
   1.358 +          level[u] = path_cnt;
   1.359 +          while (level[u = _gr.target(_policy[u])] < 0)
   1.360 +            level[u] = path_cnt;
   1.361 +          if (level[u] == path_cnt) {
   1.362 +            // A cycle is found
   1.363 +            curr_cycle_found = true;
   1.364 +            clength = _length[_policy[u]];
   1.365 +            csize = 1;
   1.366 +            for (v = u; (v = _gr.target(_policy[v])) != u; ) {
   1.367 +              clength += _length[_policy[v]];
   1.368 +              ++csize;
   1.369 +            }
   1.370 +            if ( !_cycle_found ||
   1.371 +                 clength * _cycle_size < _cycle_length * csize ) {
   1.372 +              _cycle_found = true;
   1.373 +              _cycle_length = clength;
   1.374 +              _cycle_size = csize;
   1.375 +              _cycle_node = u;
   1.376 +            }
   1.377 +          }
   1.378 +          ++path_cnt;
   1.379 +        }
   1.380 +      }
   1.381 +      return curr_cycle_found;
   1.382 +    }
   1.383 +
   1.384 +    // Contract the policy graph to be connected by cutting all cycles
   1.385 +    // except for the main cycle (i.e. the minimum mean cycle).
   1.386 +    void contractPolicyGraph(int comp) {
   1.387 +      // Find the component of the main cycle using reverse BFS search
   1.388 +      typename Digraph::template NodeMap<int> found(_gr, false);
   1.389 +      std::deque<Node> queue;
   1.390 +      queue.push_back(_cycle_node);
   1.391 +      found[_cycle_node] = true;
   1.392 +      Node u, v;
   1.393 +      while (!queue.empty()) {
   1.394 +        v = queue.front(); queue.pop_front();
   1.395 +        for (InArcIt e(_gr, v); e != INVALID; ++e) {
   1.396 +          u = _gr.source(e);
   1.397 +          if (_policy[u] == e && !found[u]) {
   1.398 +            found[u] = true;
   1.399 +            queue.push_back(u);
   1.400 +          }
   1.401 +        }
   1.402 +      }
   1.403 +      // Connect all other nodes to this component using reverse BFS search
   1.404 +      queue.clear();
   1.405 +      for (int i = 0; i < int(_nodes.size()); ++i)
   1.406 +        if (found[_nodes[i]]) queue.push_back(_nodes[i]);
   1.407 +      int found_cnt = queue.size();
   1.408 +      while (found_cnt < int(_nodes.size())) {
   1.409 +        v = queue.front(); queue.pop_front();
   1.410 +        for (InArcIt e(_gr, v); e != INVALID; ++e) {
   1.411 +          u = _gr.source(e);
   1.412 +          if (_comp[u] == comp && !found[u]) {
   1.413 +            found[u] = true;
   1.414 +            ++found_cnt;
   1.415 +            _policy[u] = e;
   1.416 +            queue.push_back(u);
   1.417 +          }
   1.418 +        }
   1.419 +      }
   1.420 +    }
   1.421 +
   1.422 +    // Compute node distances in the policy graph and update the
   1.423 +    // policy graph if the node distances can be improved.
   1.424 +    bool computeNodeDistances() {
   1.425 +      // Compute node distances using reverse BFS search
   1.426 +      double cycle_mean = double(_cycle_length) / _cycle_size;
   1.427 +      typename Digraph::template NodeMap<int> found(_gr, false);
   1.428 +      std::deque<Node> queue;
   1.429 +      queue.push_back(_cycle_node);
   1.430 +      found[_cycle_node] = true;
   1.431 +      _dist[_cycle_node] = 0;
   1.432 +      Node u, v;
   1.433 +      while (!queue.empty()) {
   1.434 +        v = queue.front(); queue.pop_front();
   1.435 +        for (InArcIt e(_gr, v); e != INVALID; ++e) {
   1.436 +          u = _gr.source(e);
   1.437 +          if (_policy[u] == e && !found[u]) {
   1.438 +            found[u] = true;
   1.439 +            _dist[u] = _dist[v] + _length[e] - cycle_mean;
   1.440 +            queue.push_back(u);
   1.441 +          }
   1.442 +        }
   1.443 +      }
   1.444 +      // Improving node distances
   1.445 +      bool improved = false;
   1.446 +      for (int j = 0; j < int(_arcs.size()); ++j) {
   1.447 +        Arc e = _arcs[j];
   1.448 +        u = _gr.source(e); v = _gr.target(e);
   1.449 +        double delta = _dist[v] + _length[e] - cycle_mean;
   1.450 +        if (_tol.less(delta, _dist[u])) {
   1.451 +          improved = true;
   1.452 +          _dist[u] = delta;
   1.453 +          _policy[u] = e;
   1.454 +        }
   1.455 +      }
   1.456 +      return improved;
   1.457 +    }
   1.458 +
   1.459 +  }; //class MinMeanCycle
   1.460 +
   1.461 +  ///@}
   1.462 +
   1.463 +} //namespace lemon
   1.464 +
   1.465 +#endif //LEMON_MIN_MEAN_CYCLE_H