lemon/min_mean_cycle.h
author deba
Wed, 27 Feb 2008 11:39:03 +0000
changeset 2580 fa71d9612c42
parent 2553 bfced05fa852
child 2583 7216b6a52ab9
permissions -rw-r--r--
Bug fixes
alpar@2409
     1
/* -*- C++ -*-
alpar@2409
     2
 *
alpar@2409
     3
 * This file is a part of LEMON, a generic C++ optimization library
alpar@2409
     4
 *
alpar@2553
     5
 * Copyright (C) 2003-2008
alpar@2409
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@2409
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@2409
     8
 *
alpar@2409
     9
 * Permission to use, modify and distribute this software is granted
alpar@2409
    10
 * provided that this copyright notice appears in all copies. For
alpar@2409
    11
 * precise terms see the accompanying LICENSE file.
alpar@2409
    12
 *
alpar@2409
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@2409
    14
 * express or implied, and with no claim as to its suitability for any
alpar@2409
    15
 * purpose.
alpar@2409
    16
 *
alpar@2409
    17
 */
alpar@2409
    18
alpar@2409
    19
#ifndef LEMON_MIN_MEAN_CYCLE_H
alpar@2409
    20
#define LEMON_MIN_MEAN_CYCLE_H
alpar@2409
    21
deba@2529
    22
/// \ingroup shortest_path
alpar@2409
    23
///
deba@2437
    24
/// \file
kpeter@2555
    25
/// \brief Howard's algorithm for finding a minimum mean directed cycle.
alpar@2409
    26
kpeter@2509
    27
#include <vector>
alpar@2409
    28
#include <lemon/graph_utils.h>
alpar@2409
    29
#include <lemon/topology.h>
alpar@2409
    30
#include <lemon/path.h>
kpeter@2555
    31
#include <lemon/tolerance.h>
alpar@2409
    32
alpar@2409
    33
namespace lemon {
alpar@2409
    34
deba@2529
    35
  /// \addtogroup shortest_path
alpar@2409
    36
  /// @{
alpar@2409
    37
kpeter@2555
    38
  /// \brief Implementation of Howard's algorithm for finding a minimum
kpeter@2555
    39
  /// mean directed cycle.
alpar@2409
    40
  ///
kpeter@2555
    41
  /// \ref MinMeanCycle implements Howard's algorithm for finding a
kpeter@2555
    42
  /// minimum mean directed cycle.
alpar@2409
    43
  ///
alpar@2409
    44
  /// \param Graph The directed graph type the algorithm runs on.
alpar@2409
    45
  /// \param LengthMap The type of the length (cost) map.
alpar@2409
    46
  ///
kpeter@2555
    47
  /// \warning \c LengthMap::Value must be convertible to \c double.
kpeter@2555
    48
  ///
alpar@2409
    49
  /// \author Peter Kovacs
alpar@2409
    50
kpeter@2555
    51
  template < typename Graph,
kpeter@2555
    52
             typename LengthMap = typename Graph::template EdgeMap<int> >
alpar@2409
    53
  class MinMeanCycle
alpar@2409
    54
  {
kpeter@2555
    55
    GRAPH_TYPEDEFS(typename Graph);
alpar@2409
    56
alpar@2409
    57
    typedef typename LengthMap::Value Length;
alpar@2409
    58
    typedef Path<Graph> Path;
alpar@2409
    59
alpar@2409
    60
  protected:
deba@2413
    61
kpeter@2555
    62
    typename Graph::template NodeMap<bool> _reached;
kpeter@2555
    63
    typename Graph::template NodeMap<double> _dist;
kpeter@2555
    64
    typename Graph::template NodeMap<Edge> _policy;
deba@2413
    65
kpeter@2555
    66
    /// The directed graph the algorithm runs on.
kpeter@2555
    67
    const Graph &_graph;
kpeter@2555
    68
    /// The length of the edges.
kpeter@2555
    69
    const LengthMap &_length;
deba@2413
    70
kpeter@2555
    71
    /// The total length of the found cycle.
kpeter@2555
    72
    Length _cycle_length;
kpeter@2555
    73
    /// The number of edges on the found cycle.
kpeter@2555
    74
    int _cycle_size;
kpeter@2555
    75
    /// The found cycle.
kpeter@2555
    76
    Path *_cycle_path;
deba@2413
    77
kpeter@2555
    78
    bool _local_path;
kpeter@2555
    79
    bool _cycle_found;
kpeter@2555
    80
    Node _cycle_node;
alpar@2409
    81
kpeter@2555
    82
    typename Graph::template NodeMap<int> _component;
kpeter@2555
    83
    int _component_num;
deba@2437
    84
kpeter@2555
    85
    std::vector<Node> _nodes;
kpeter@2555
    86
    std::vector<Edge> _edges;
kpeter@2555
    87
    Tolerance<double> _tolerance;
deba@2437
    88
kpeter@2555
    89
  public:
alpar@2409
    90
alpar@2409
    91
    /// \brief The constructor of the class.
alpar@2409
    92
    ///
alpar@2409
    93
    /// The constructor of the class.
alpar@2409
    94
    ///
kpeter@2555
    95
    /// \param graph The directed graph the algorithm runs on.
kpeter@2555
    96
    /// \param length The length (cost) of the edges.
kpeter@2555
    97
    MinMeanCycle( const Graph &graph,
kpeter@2555
    98
                  const LengthMap &length ) :
kpeter@2555
    99
      _graph(graph), _length(length), _dist(graph), _reached(graph),
kpeter@2555
   100
      _policy(graph), _component(graph), _cycle_length(0),
kpeter@2555
   101
      _cycle_size(-1), _cycle_path(NULL), _local_path(false)
alpar@2409
   102
    { }
alpar@2409
   103
kpeter@2555
   104
    /// The destructor of the class.
deba@2437
   105
    ~MinMeanCycle() {
kpeter@2555
   106
      if (_local_path) delete _cycle_path;
alpar@2409
   107
    }
alpar@2409
   108
alpar@2409
   109
  protected:
alpar@2409
   110
kpeter@2555
   111
    // Initializes the internal data structures for the current strongly
kpeter@2555
   112
    // connected component and creating the policy graph.
kpeter@2555
   113
    // The policy graph can be represented by the _policy map because
kpeter@2555
   114
    // the out degree of every node is 1.
kpeter@2555
   115
    bool initCurrentComponent(int comp) {
alpar@2409
   116
      // Finding the nodes of the current component
kpeter@2555
   117
      _nodes.clear();
kpeter@2555
   118
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@2555
   119
        if (_component[n] == comp) _nodes.push_back(n);
alpar@2409
   120
      }
kpeter@2555
   121
      if (_nodes.size() <= 1) return false;
kpeter@2555
   122
      // Finding the edges of the current component
kpeter@2555
   123
      _edges.clear();
kpeter@2555
   124
      for (EdgeIt e(_graph); e != INVALID; ++e) {
kpeter@2555
   125
        if ( _component[_graph.source(e)] == comp &&
kpeter@2555
   126
             _component[_graph.target(e)] == comp )
kpeter@2555
   127
          _edges.push_back(e);
kpeter@2555
   128
      }
kpeter@2555
   129
      // Initializing _reached, _dist, _policy maps
kpeter@2555
   130
      for (int i = 0; i < _nodes.size(); ++i) {
kpeter@2555
   131
        _reached[_nodes[i]] = false;
kpeter@2555
   132
        _policy[_nodes[i]] = INVALID;
kpeter@2555
   133
      }
kpeter@2555
   134
      Node u; Edge e;
kpeter@2555
   135
      for (int j = 0; j < _edges.size(); ++j) {
kpeter@2555
   136
        e = _edges[j];
kpeter@2555
   137
        u = _graph.source(e);
kpeter@2555
   138
        if (!_reached[u] || _length[e] < _dist[u]) {
kpeter@2555
   139
          _dist[u] = _length[e];
kpeter@2555
   140
          _policy[u] = e;
kpeter@2555
   141
          _reached[u] = true;
kpeter@2555
   142
        }
kpeter@2555
   143
      }
kpeter@2555
   144
      return true;
kpeter@2555
   145
    }
kpeter@2555
   146
kpeter@2555
   147
    // Finds all cycles in the policy graph.
kpeter@2555
   148
    // Sets _cycle_found to true if a cycle is found and sets
kpeter@2555
   149
    // _cycle_length, _cycle_size, _cycle_node to represent the minimum
kpeter@2555
   150
    // mean cycle in the policy graph.
kpeter@2555
   151
    bool findPolicyCycles(int comp) {
kpeter@2555
   152
      typename Graph::template NodeMap<int> level(_graph, -1);
kpeter@2555
   153
      _cycle_found = false;
kpeter@2555
   154
      Length clength;
kpeter@2555
   155
      int csize;
kpeter@2555
   156
      int path_cnt = 0;
kpeter@2555
   157
      Node u, v;
kpeter@2555
   158
      // Searching for cycles
kpeter@2555
   159
      for (int i = 0; i < _nodes.size(); ++i) {
kpeter@2555
   160
        if (level[_nodes[i]] < 0) {
kpeter@2555
   161
          u = _nodes[i];
kpeter@2555
   162
          level[u] = path_cnt;
kpeter@2555
   163
          while (level[u = _graph.target(_policy[u])] < 0)
kpeter@2555
   164
            level[u] = path_cnt;
kpeter@2555
   165
          if (level[u] == path_cnt) {
kpeter@2555
   166
            // A cycle is found
kpeter@2555
   167
            clength = _length[_policy[u]];
kpeter@2555
   168
            csize = 1;
kpeter@2555
   169
            for (v = u; (v = _graph.target(_policy[v])) != u; ) {
kpeter@2555
   170
              clength += _length[_policy[v]];
kpeter@2555
   171
              ++csize;
kpeter@2555
   172
            }
kpeter@2555
   173
            if ( !_cycle_found ||
kpeter@2555
   174
                 clength * _cycle_size < _cycle_length * csize ) {
kpeter@2555
   175
              _cycle_found = true;
kpeter@2555
   176
              _cycle_length = clength;
kpeter@2555
   177
              _cycle_size = csize;
kpeter@2555
   178
              _cycle_node = u;
kpeter@2555
   179
            }
kpeter@2555
   180
          }
kpeter@2555
   181
          ++path_cnt;
kpeter@2555
   182
        }
kpeter@2555
   183
      }
kpeter@2555
   184
      return _cycle_found;
kpeter@2555
   185
    }
kpeter@2555
   186
kpeter@2555
   187
    // Contracts the policy graph to be connected by cutting all cycles
kpeter@2555
   188
    // except for the main cycle (i.e. the minimum mean cycle).
kpeter@2555
   189
    void contractPolicyGraph(int comp) {
kpeter@2555
   190
      // Finding the component of the main cycle using
kpeter@2555
   191
      // reverse BFS search
kpeter@2555
   192
      typename Graph::template NodeMap<int> found(_graph, false);
kpeter@2555
   193
      std::deque<Node> queue;
kpeter@2555
   194
      queue.push_back(_cycle_node);
kpeter@2555
   195
      found[_cycle_node] = true;
kpeter@2555
   196
      Node u, v;
kpeter@2555
   197
      while (!queue.empty()) {
kpeter@2555
   198
        v = queue.front(); queue.pop_front();
kpeter@2555
   199
        for (InEdgeIt e(_graph, v); e != INVALID; ++e) {
kpeter@2555
   200
          u = _graph.source(e);
kpeter@2555
   201
          if (_component[u] == comp && !found[u] && _policy[u] == e) {
kpeter@2555
   202
            found[u] = true;
kpeter@2555
   203
            queue.push_back(u);
kpeter@2555
   204
          }
kpeter@2555
   205
        }
kpeter@2555
   206
      }
kpeter@2555
   207
      // Connecting all other nodes to this component using
kpeter@2555
   208
      // reverse BFS search
kpeter@2555
   209
      queue.clear();
kpeter@2555
   210
      for (int i = 0; i < _nodes.size(); ++i)
kpeter@2555
   211
        if (found[_nodes[i]]) queue.push_back(_nodes[i]);
kpeter@2555
   212
      int found_cnt = queue.size();
kpeter@2555
   213
      while (found_cnt < _nodes.size() && !queue.empty()) {
kpeter@2555
   214
        v = queue.front(); queue.pop_front();
kpeter@2555
   215
        for (InEdgeIt e(_graph, v); e != INVALID; ++e) {
kpeter@2555
   216
          u = _graph.source(e);
kpeter@2555
   217
          if (_component[u] == comp && !found[u]) {
kpeter@2555
   218
            found[u] = true;
kpeter@2555
   219
            ++found_cnt;
kpeter@2555
   220
            _policy[u] = e;
kpeter@2555
   221
            queue.push_back(u);
kpeter@2555
   222
          }
kpeter@2555
   223
        }
alpar@2409
   224
      }
alpar@2409
   225
    }
deba@2437
   226
kpeter@2555
   227
    // Computes node distances in the policy graph and updates the
kpeter@2555
   228
    // policy graph if the node distances can be improved.
kpeter@2555
   229
    bool computeNodeDistances(int comp) {
kpeter@2555
   230
      // Computing node distances using reverse BFS search
kpeter@2555
   231
      double cycle_mean = (double)_cycle_length / _cycle_size;
kpeter@2555
   232
      typename Graph::template NodeMap<int> found(_graph, false);
kpeter@2555
   233
      std::deque<Node> queue;
kpeter@2555
   234
      queue.push_back(_cycle_node);
kpeter@2555
   235
      found[_cycle_node] = true;
kpeter@2555
   236
      Node u, v;
kpeter@2555
   237
      while (!queue.empty()) {
kpeter@2555
   238
        v = queue.front(); queue.pop_front();
kpeter@2555
   239
        for (InEdgeIt e(_graph, v); e != INVALID; ++e) {
kpeter@2555
   240
          u = _graph.source(e);
kpeter@2555
   241
          if (_component[u] == comp && !found[u] && _policy[u] == e) {
kpeter@2555
   242
            found[u] = true;
kpeter@2555
   243
            _dist[u] = _dist[v] + _length[e] - cycle_mean;
kpeter@2555
   244
            queue.push_back(u);
kpeter@2555
   245
          }
kpeter@2555
   246
        }
alpar@2409
   247
      }
kpeter@2555
   248
      // Improving node distances
kpeter@2555
   249
      bool improved = false;
kpeter@2555
   250
      for (int j = 0; j < _edges.size(); ++j) {
kpeter@2555
   251
        Edge e = _edges[j];
kpeter@2555
   252
        u = _graph.source(e); v = _graph.target(e);
kpeter@2555
   253
        double delta = _dist[v] + _length[e] - cycle_mean;
kpeter@2555
   254
        if (_tolerance.less(delta, _dist[u])) {
kpeter@2555
   255
          improved = true;
kpeter@2555
   256
          _dist[u] = delta;
kpeter@2555
   257
          _policy[u] = e;
kpeter@2555
   258
        }
alpar@2409
   259
      }
kpeter@2555
   260
      return improved;
alpar@2409
   261
    }
deba@2437
   262
deba@2437
   263
  public:
deba@2437
   264
alpar@2409
   265
    /// \brief Runs the algorithm.
alpar@2409
   266
    ///
alpar@2409
   267
    /// Runs the algorithm.
alpar@2409
   268
    ///
kpeter@2555
   269
    /// \return Returns \c true if a directed cycle exists in the graph.
deba@2413
   270
    ///
kpeter@2555
   271
    /// \note Apart from the return value, <tt>mmc.run()</tt> is just a
kpeter@2517
   272
    /// shortcut of the following code.
deba@2413
   273
    /// \code
kpeter@2555
   274
    ///   mmc.init();
kpeter@2555
   275
    ///   mmc.findMinMean();
kpeter@2555
   276
    ///   mmc.findCycle();
deba@2413
   277
    /// \endcode
alpar@2409
   278
    bool run() {
alpar@2409
   279
      init();
kpeter@2555
   280
      return findMinMean() && findCycle();
deba@2413
   281
    }
deba@2437
   282
deba@2413
   283
    /// \brief Initializes the internal data structures.
kpeter@2517
   284
    ///
kpeter@2517
   285
    /// Initializes the internal data structures.
kpeter@2517
   286
    ///
kpeter@2517
   287
    /// \sa reset()
deba@2413
   288
    void init() {
kpeter@2555
   289
      _tolerance.epsilon(1e-8);
kpeter@2555
   290
      if (!_cycle_path) {
kpeter@2555
   291
        _local_path = true;
kpeter@2555
   292
        _cycle_path = new Path;
deba@2413
   293
      }
kpeter@2555
   294
      _cycle_found = false;
kpeter@2555
   295
      _component_num = stronglyConnectedComponents(_graph, _component);
deba@2413
   296
    }
deba@2413
   297
deba@2413
   298
    /// \brief Resets the internal data structures.
deba@2413
   299
    ///
deba@2437
   300
    /// Resets the internal data structures so that \ref findMinMean()
deba@2437
   301
    /// and \ref findCycle() can be called again (e.g. when the
deba@2413
   302
    /// underlaying graph has been modified).
kpeter@2517
   303
    ///
kpeter@2517
   304
    /// \sa init()
deba@2413
   305
    void reset() {
kpeter@2555
   306
      if (_cycle_path) _cycle_path->clear();
kpeter@2555
   307
      _cycle_found = false;
kpeter@2555
   308
      _component_num = stronglyConnectedComponents(_graph, _component);
kpeter@2555
   309
    }
kpeter@2555
   310
kpeter@2555
   311
    /// \brief Finds the minimum cycle mean length in the graph.
kpeter@2555
   312
    ///
kpeter@2555
   313
    /// Computes all the required data and finds the minimum cycle mean
kpeter@2555
   314
    /// length in the graph.
kpeter@2555
   315
    ///
kpeter@2555
   316
    /// \return Returns \c true if a directed cycle exists in the graph.
kpeter@2555
   317
    ///
kpeter@2555
   318
    /// \pre \ref init() must be called before using this function.
kpeter@2555
   319
    bool findMinMean() {
kpeter@2555
   320
      // Finding the minimum mean cycle in the components
kpeter@2555
   321
      for (int comp = 0; comp < _component_num; ++comp) {
kpeter@2555
   322
        if (!initCurrentComponent(comp)) continue;
kpeter@2555
   323
        while (true) {
kpeter@2555
   324
          if (!findPolicyCycles(comp)) return false;
kpeter@2555
   325
          contractPolicyGraph(comp);
kpeter@2555
   326
          if (!computeNodeDistances(comp)) return true;
kpeter@2555
   327
        }
kpeter@2555
   328
      }
kpeter@2555
   329
    }
kpeter@2555
   330
kpeter@2555
   331
    /// \brief Finds a critical (minimum mean) directed cycle.
kpeter@2555
   332
    ///
kpeter@2555
   333
    /// Finds a critical (minimum mean) directed cycle using the data
kpeter@2555
   334
    /// computed in the \ref findMinMean() function.
kpeter@2555
   335
    ///
kpeter@2555
   336
    /// \return Returns \c true if a directed cycle exists in the graph.
kpeter@2555
   337
    ///
kpeter@2555
   338
    /// \pre \ref init() and \ref findMinMean() must be called before
kpeter@2555
   339
    /// using this function.
kpeter@2555
   340
    bool findCycle() {
kpeter@2555
   341
      if (!_cycle_found) return false;
kpeter@2555
   342
      _cycle_path->addBack(_policy[_cycle_node]);
kpeter@2555
   343
      for ( Node v = _cycle_node;
kpeter@2555
   344
            (v = _graph.target(_policy[v])) != _cycle_node; ) {
kpeter@2555
   345
        _cycle_path->addBack(_policy[v]);
kpeter@2555
   346
      }
kpeter@2555
   347
      return true;
deba@2413
   348
    }
deba@2437
   349
deba@2413
   350
    /// \brief Returns the total length of the found cycle.
deba@2413
   351
    ///
deba@2413
   352
    /// Returns the total length of the found cycle.
alpar@2409
   353
    ///
kpeter@2555
   354
    /// \pre \ref run() or \ref findMinMean() must be called before
kpeter@2555
   355
    /// using this function.
deba@2437
   356
    Length cycleLength() const {
kpeter@2555
   357
      return _cycle_length;
alpar@2409
   358
    }
deba@2437
   359
kpeter@2555
   360
    /// \brief Returns the number of edges on the found cycle.
alpar@2409
   361
    ///
kpeter@2555
   362
    /// Returns the number of edges on the found cycle.
alpar@2409
   363
    ///
kpeter@2555
   364
    /// \pre \ref run() or \ref findMinMean() must be called before
kpeter@2555
   365
    /// using this function.
deba@2437
   366
    int cycleEdgeNum() const {
kpeter@2555
   367
      return _cycle_size;
alpar@2409
   368
    }
deba@2437
   369
deba@2413
   370
    /// \brief Returns the mean length of the found cycle.
alpar@2409
   371
    ///
deba@2413
   372
    /// Returns the mean length of the found cycle.
alpar@2409
   373
    ///
kpeter@2517
   374
    /// \pre \ref run() or \ref findMinMean() must be called before
kpeter@2517
   375
    /// using this function.
alpar@2409
   376
    ///
kpeter@2555
   377
    /// \note <tt>mmc.cycleMean()</tt> is just a shortcut of the
kpeter@2555
   378
    /// following code.
deba@2413
   379
    /// \code
kpeter@2555
   380
    ///   return double(mmc.cycleLength()) / mmc.cycleEdgeNum();
deba@2413
   381
    /// \endcode
kpeter@2555
   382
    double cycleMean() const {
kpeter@2555
   383
      return (double)_cycle_length / _cycle_size;
alpar@2409
   384
    }
alpar@2409
   385
kpeter@2555
   386
    /// \brief Returns a const reference to the \ref Path "path"
kpeter@2555
   387
    /// structure storing the found cycle.
alpar@2409
   388
    ///
kpeter@2555
   389
    /// Returns a const reference to the \ref Path "path"
kpeter@2555
   390
    /// structure storing the found cycle.
alpar@2409
   391
    ///
kpeter@2555
   392
    /// \pre \ref run() or \ref findCycle() must be called before using
kpeter@2555
   393
    /// this function.
alpar@2409
   394
    ///
kpeter@2555
   395
    /// \sa cyclePath()
deba@2437
   396
    const Path& cycle() const {
kpeter@2555
   397
      return *_cycle_path;
alpar@2409
   398
    }
deba@2437
   399
kpeter@2555
   400
    /// \brief Sets the \ref Path "path" structure for storing the found
kpeter@2555
   401
    /// cycle.
kpeter@2555
   402
    ///
kpeter@2555
   403
    /// Sets an external \ref Path "path" structure for storing the
alpar@2409
   404
    /// found cycle.
deba@2437
   405
    ///
kpeter@2555
   406
    /// If you don't call this function before calling \ref run() or
kpeter@2555
   407
    /// \ref init(), it will allocate a local \ref Path "path"
kpeter@2555
   408
    /// structure.
kpeter@2555
   409
    /// The destuctor deallocates this automatically allocated map,
kpeter@2555
   410
    /// of course.
alpar@2409
   411
    ///
kpeter@2555
   412
    /// \note The algorithm calls only the \ref lemon::Path::addBack()
kpeter@2555
   413
    /// "addBack()" function of the given \ref Path "path" structure.
deba@2437
   414
    ///
kpeter@2555
   415
    /// \return <tt>(*this)</tt>
kpeter@2555
   416
    ///
kpeter@2555
   417
    /// \sa cycle()
deba@2437
   418
    MinMeanCycle& cyclePath(Path &path) {
kpeter@2555
   419
      if (_local_path) {
kpeter@2555
   420
        delete _cycle_path;
kpeter@2555
   421
        _local_path = false;
alpar@2409
   422
      }
kpeter@2555
   423
      _cycle_path = &path;
alpar@2409
   424
      return *this;
alpar@2409
   425
    }
alpar@2409
   426
alpar@2409
   427
  }; //class MinMeanCycle
alpar@2409
   428
alpar@2409
   429
  ///@}
alpar@2409
   430
alpar@2409
   431
} //namespace lemon
alpar@2409
   432
alpar@2409
   433
#endif //LEMON_MIN_MEAN_CYCLE_H