1.1 --- a/lemon/Makefile.am Thu Jun 11 23:13:24 2009 +0200
1.2 +++ b/lemon/Makefile.am Mon Aug 03 14:12:55 2009 +0200
1.3 @@ -97,6 +97,7 @@
1.4 lemon/matching.h \
1.5 lemon/math.h \
1.6 lemon/min_cost_arborescence.h \
1.7 + lemon/min_mean_cycle.h \
1.8 lemon/nauty_reader.h \
1.9 lemon/network_simplex.h \
1.10 lemon/path.h \
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/lemon/min_mean_cycle.h Mon Aug 03 14:12:55 2009 +0200
2.3 @@ -0,0 +1,462 @@
2.4 +/* -*- C++ -*-
2.5 + *
2.6 + * This file is a part of LEMON, a generic C++ optimization library
2.7 + *
2.8 + * Copyright (C) 2003-2008
2.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
2.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
2.11 + *
2.12 + * Permission to use, modify and distribute this software is granted
2.13 + * provided that this copyright notice appears in all copies. For
2.14 + * precise terms see the accompanying LICENSE file.
2.15 + *
2.16 + * This software is provided "AS IS" with no warranty of any kind,
2.17 + * express or implied, and with no claim as to its suitability for any
2.18 + * purpose.
2.19 + *
2.20 + */
2.21 +
2.22 +#ifndef LEMON_MIN_MEAN_CYCLE_H
2.23 +#define LEMON_MIN_MEAN_CYCLE_H
2.24 +
2.25 +/// \ingroup shortest_path
2.26 +///
2.27 +/// \file
2.28 +/// \brief Howard's algorithm for finding a minimum mean cycle.
2.29 +
2.30 +#include <vector>
2.31 +#include <lemon/core.h>
2.32 +#include <lemon/path.h>
2.33 +#include <lemon/tolerance.h>
2.34 +#include <lemon/connectivity.h>
2.35 +
2.36 +namespace lemon {
2.37 +
2.38 + /// \addtogroup shortest_path
2.39 + /// @{
2.40 +
2.41 + /// \brief Implementation of Howard's algorithm for finding a minimum
2.42 + /// mean cycle.
2.43 + ///
2.44 + /// \ref MinMeanCycle implements Howard's algorithm for finding a
2.45 + /// directed cycle of minimum mean length (cost) in a digraph.
2.46 + ///
2.47 + /// \tparam GR The type of the digraph the algorithm runs on.
2.48 + /// \tparam LEN The type of the length map. The default
2.49 + /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
2.50 + ///
2.51 + /// \warning \c LEN::Value must be convertible to \c double.
2.52 +#ifdef DOXYGEN
2.53 + template <typename GR, typename LEN>
2.54 +#else
2.55 + template < typename GR,
2.56 + typename LEN = typename GR::template ArcMap<int> >
2.57 +#endif
2.58 + class MinMeanCycle
2.59 + {
2.60 + public:
2.61 +
2.62 + /// The type of the digraph the algorithm runs on
2.63 + typedef GR Digraph;
2.64 + /// The type of the length map
2.65 + typedef LEN LengthMap;
2.66 + /// The type of the arc lengths
2.67 + typedef typename LengthMap::Value Value;
2.68 + /// The type of the paths
2.69 + typedef lemon::Path<Digraph> Path;
2.70 +
2.71 + private:
2.72 +
2.73 + TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
2.74 +
2.75 + // The digraph the algorithm runs on
2.76 + const Digraph &_gr;
2.77 + // The length of the arcs
2.78 + const LengthMap &_length;
2.79 +
2.80 + // The total length of the found cycle
2.81 + Value _cycle_length;
2.82 + // The number of arcs on the found cycle
2.83 + int _cycle_size;
2.84 + // The found cycle
2.85 + Path *_cycle_path;
2.86 +
2.87 + bool _local_path;
2.88 + bool _cycle_found;
2.89 + Node _cycle_node;
2.90 +
2.91 + typename Digraph::template NodeMap<bool> _reached;
2.92 + typename Digraph::template NodeMap<double> _dist;
2.93 + typename Digraph::template NodeMap<Arc> _policy;
2.94 +
2.95 + typename Digraph::template NodeMap<int> _comp;
2.96 + int _comp_num;
2.97 +
2.98 + std::vector<Node> _nodes;
2.99 + std::vector<Arc> _arcs;
2.100 + Tolerance<double> _tol;
2.101 +
2.102 + public:
2.103 +
2.104 + /// \brief Constructor.
2.105 + ///
2.106 + /// The constructor of the class.
2.107 + ///
2.108 + /// \param digraph The digraph the algorithm runs on.
2.109 + /// \param length The lengths (costs) of the arcs.
2.110 + MinMeanCycle( const Digraph &digraph,
2.111 + const LengthMap &length ) :
2.112 + _gr(digraph), _length(length), _cycle_length(0), _cycle_size(-1),
2.113 + _cycle_path(NULL), _local_path(false), _reached(digraph),
2.114 + _dist(digraph), _policy(digraph), _comp(digraph)
2.115 + {}
2.116 +
2.117 + /// Destructor.
2.118 + ~MinMeanCycle() {
2.119 + if (_local_path) delete _cycle_path;
2.120 + }
2.121 +
2.122 + /// \brief Set the path structure for storing the found cycle.
2.123 + ///
2.124 + /// This function sets an external path structure for storing the
2.125 + /// found cycle.
2.126 + ///
2.127 + /// If you don't call this function before calling \ref run() or
2.128 + /// \ref init(), it will allocate a local \ref Path "path"
2.129 + /// structure. The destuctor deallocates this automatically
2.130 + /// allocated object, of course.
2.131 + ///
2.132 + /// \note The algorithm calls only the \ref lemon::Path::addBack()
2.133 + /// "addBack()" function of the given path structure.
2.134 + ///
2.135 + /// \return <tt>(*this)</tt>
2.136 + ///
2.137 + /// \sa cycle()
2.138 + MinMeanCycle& cyclePath(Path &path) {
2.139 + if (_local_path) {
2.140 + delete _cycle_path;
2.141 + _local_path = false;
2.142 + }
2.143 + _cycle_path = &path;
2.144 + return *this;
2.145 + }
2.146 +
2.147 + /// \name Execution control
2.148 + /// The simplest way to execute the algorithm is to call the \ref run()
2.149 + /// function.\n
2.150 + /// If you only need the minimum mean length, you may call \ref init()
2.151 + /// and \ref findMinMean().
2.152 + /// If you would like to run the algorithm again (e.g. the underlying
2.153 + /// digraph and/or the arc lengths has been modified), you may not
2.154 + /// create a new instance of the class, rather call \ref reset(),
2.155 + /// \ref findMinMean() and \ref findCycle() instead.
2.156 +
2.157 + /// @{
2.158 +
2.159 + /// \brief Run the algorithm.
2.160 + ///
2.161 + /// This function runs the algorithm.
2.162 + ///
2.163 + /// \return \c true if a directed cycle exists in the digraph.
2.164 + ///
2.165 + /// \note Apart from the return value, <tt>mmc.run()</tt> is just a
2.166 + /// shortcut of the following code.
2.167 + /// \code
2.168 + /// mmc.init();
2.169 + /// mmc.findMinMean();
2.170 + /// mmc.findCycle();
2.171 + /// \endcode
2.172 + bool run() {
2.173 + init();
2.174 + return findMinMean() && findCycle();
2.175 + }
2.176 +
2.177 + /// \brief Initialize the internal data structures.
2.178 + ///
2.179 + /// This function initializes the internal data structures.
2.180 + ///
2.181 + /// \sa reset()
2.182 + void init() {
2.183 + _tol.epsilon(1e-6);
2.184 + if (!_cycle_path) {
2.185 + _local_path = true;
2.186 + _cycle_path = new Path;
2.187 + }
2.188 + _cycle_found = false;
2.189 + _comp_num = stronglyConnectedComponents(_gr, _comp);
2.190 + }
2.191 +
2.192 + /// \brief Reset the internal data structures.
2.193 + ///
2.194 + /// This function resets the internal data structures so that
2.195 + /// findMinMean() and findCycle() can be called again (e.g. when the
2.196 + /// underlying digraph and/or the arc lengths has been modified).
2.197 + ///
2.198 + /// \sa init()
2.199 + void reset() {
2.200 + if (_cycle_path) _cycle_path->clear();
2.201 + _cycle_found = false;
2.202 + _comp_num = stronglyConnectedComponents(_gr, _comp);
2.203 + }
2.204 +
2.205 + /// \brief Find the minimum cycle mean.
2.206 + ///
2.207 + /// This function computes all the required data and finds the
2.208 + /// minimum mean length of the directed cycles in the digraph.
2.209 + ///
2.210 + /// \return \c true if a directed cycle exists in the digraph.
2.211 + ///
2.212 + /// \pre \ref init() must be called before using this function.
2.213 + bool findMinMean() {
2.214 + // Find the minimum cycle mean in the components
2.215 + for (int comp = 0; comp < _comp_num; ++comp) {
2.216 + if (!initCurrentComponent(comp)) continue;
2.217 + while (true) {
2.218 + if (!findPolicyCycles()) break;
2.219 + contractPolicyGraph(comp);
2.220 + if (!computeNodeDistances()) break;
2.221 + }
2.222 + }
2.223 + return _cycle_found;
2.224 + }
2.225 +
2.226 + /// \brief Find a minimum mean directed cycle.
2.227 + ///
2.228 + /// This function finds a directed cycle of minimum mean length
2.229 + /// in the digraph using the data computed by findMinMean().
2.230 + ///
2.231 + /// \return \c true if a directed cycle exists in the digraph.
2.232 + ///
2.233 + /// \pre \ref init() and \ref findMinMean() must be called before
2.234 + /// using this function.
2.235 + bool findCycle() {
2.236 + if (!_cycle_found) return false;
2.237 + _cycle_path->addBack(_policy[_cycle_node]);
2.238 + for ( Node v = _cycle_node;
2.239 + (v = _gr.target(_policy[v])) != _cycle_node; ) {
2.240 + _cycle_path->addBack(_policy[v]);
2.241 + }
2.242 + return true;
2.243 + }
2.244 +
2.245 + /// @}
2.246 +
2.247 + /// \name Query Functions
2.248 + /// The result of the algorithm can be obtained using these
2.249 + /// functions.\n
2.250 + /// The algorithm should be executed before using them.
2.251 +
2.252 + /// @{
2.253 +
2.254 + /// \brief Return the total length of the found cycle.
2.255 + ///
2.256 + /// This function returns the total length of the found cycle.
2.257 + ///
2.258 + /// \pre \ref run() or \ref findCycle() must be called before
2.259 + /// using this function.
2.260 + Value cycleLength() const {
2.261 + return _cycle_length;
2.262 + }
2.263 +
2.264 + /// \brief Return the number of arcs on the found cycle.
2.265 + ///
2.266 + /// This function returns the number of arcs on the found cycle.
2.267 + ///
2.268 + /// \pre \ref run() or \ref findCycle() must be called before
2.269 + /// using this function.
2.270 + int cycleArcNum() const {
2.271 + return _cycle_size;
2.272 + }
2.273 +
2.274 + /// \brief Return the mean length of the found cycle.
2.275 + ///
2.276 + /// This function returns the mean length of the found cycle.
2.277 + ///
2.278 + /// \note <tt>mmc.cycleMean()</tt> is just a shortcut of the
2.279 + /// following code.
2.280 + /// \code
2.281 + /// return double(mmc.cycleLength()) / mmc.cycleArcNum();
2.282 + /// \endcode
2.283 + ///
2.284 + /// \pre \ref run() or \ref findMinMean() must be called before
2.285 + /// using this function.
2.286 + double cycleMean() const {
2.287 + return double(_cycle_length) / _cycle_size;
2.288 + }
2.289 +
2.290 + /// \brief Return the found cycle.
2.291 + ///
2.292 + /// This function returns a const reference to the path structure
2.293 + /// storing the found cycle.
2.294 + ///
2.295 + /// \pre \ref run() or \ref findCycle() must be called before using
2.296 + /// this function.
2.297 + ///
2.298 + /// \sa cyclePath()
2.299 + const Path& cycle() const {
2.300 + return *_cycle_path;
2.301 + }
2.302 +
2.303 + ///@}
2.304 +
2.305 + private:
2.306 +
2.307 + // Initialize the internal data structures for the current strongly
2.308 + // connected component and create the policy graph.
2.309 + // The policy graph can be represented by the _policy map because
2.310 + // the out-degree of every node is 1.
2.311 + bool initCurrentComponent(int comp) {
2.312 + // Find the nodes of the current component
2.313 + _nodes.clear();
2.314 + for (NodeIt n(_gr); n != INVALID; ++n) {
2.315 + if (_comp[n] == comp) _nodes.push_back(n);
2.316 + }
2.317 + if (_nodes.size() <= 1) return false;
2.318 + // Find the arcs of the current component
2.319 + _arcs.clear();
2.320 + for (ArcIt e(_gr); e != INVALID; ++e) {
2.321 + if ( _comp[_gr.source(e)] == comp &&
2.322 + _comp[_gr.target(e)] == comp )
2.323 + _arcs.push_back(e);
2.324 + }
2.325 + // Initialize _reached, _dist, _policy maps
2.326 + for (int i = 0; i < int(_nodes.size()); ++i) {
2.327 + _reached[_nodes[i]] = false;
2.328 + _policy[_nodes[i]] = INVALID;
2.329 + }
2.330 + Node u; Arc e;
2.331 + for (int j = 0; j < int(_arcs.size()); ++j) {
2.332 + e = _arcs[j];
2.333 + u = _gr.source(e);
2.334 + if (!_reached[u] || _length[e] < _dist[u]) {
2.335 + _dist[u] = _length[e];
2.336 + _policy[u] = e;
2.337 + _reached[u] = true;
2.338 + }
2.339 + }
2.340 + return true;
2.341 + }
2.342 +
2.343 + // Find all cycles in the policy graph.
2.344 + // Set _cycle_found to true if a cycle is found and set
2.345 + // _cycle_length, _cycle_size, _cycle_node to represent the minimum
2.346 + // mean cycle in the policy graph.
2.347 + bool findPolicyCycles() {
2.348 + typename Digraph::template NodeMap<int> level(_gr, -1);
2.349 + bool curr_cycle_found = false;
2.350 + Value clength;
2.351 + int csize;
2.352 + int path_cnt = 0;
2.353 + Node u, v;
2.354 + // Searching for cycles
2.355 + for (int i = 0; i < int(_nodes.size()); ++i) {
2.356 + if (level[_nodes[i]] < 0) {
2.357 + u = _nodes[i];
2.358 + level[u] = path_cnt;
2.359 + while (level[u = _gr.target(_policy[u])] < 0)
2.360 + level[u] = path_cnt;
2.361 + if (level[u] == path_cnt) {
2.362 + // A cycle is found
2.363 + curr_cycle_found = true;
2.364 + clength = _length[_policy[u]];
2.365 + csize = 1;
2.366 + for (v = u; (v = _gr.target(_policy[v])) != u; ) {
2.367 + clength += _length[_policy[v]];
2.368 + ++csize;
2.369 + }
2.370 + if ( !_cycle_found ||
2.371 + clength * _cycle_size < _cycle_length * csize ) {
2.372 + _cycle_found = true;
2.373 + _cycle_length = clength;
2.374 + _cycle_size = csize;
2.375 + _cycle_node = u;
2.376 + }
2.377 + }
2.378 + ++path_cnt;
2.379 + }
2.380 + }
2.381 + return curr_cycle_found;
2.382 + }
2.383 +
2.384 + // Contract the policy graph to be connected by cutting all cycles
2.385 + // except for the main cycle (i.e. the minimum mean cycle).
2.386 + void contractPolicyGraph(int comp) {
2.387 + // Find the component of the main cycle using reverse BFS search
2.388 + typename Digraph::template NodeMap<int> found(_gr, false);
2.389 + std::deque<Node> queue;
2.390 + queue.push_back(_cycle_node);
2.391 + found[_cycle_node] = true;
2.392 + Node u, v;
2.393 + while (!queue.empty()) {
2.394 + v = queue.front(); queue.pop_front();
2.395 + for (InArcIt e(_gr, v); e != INVALID; ++e) {
2.396 + u = _gr.source(e);
2.397 + if (_policy[u] == e && !found[u]) {
2.398 + found[u] = true;
2.399 + queue.push_back(u);
2.400 + }
2.401 + }
2.402 + }
2.403 + // Connect all other nodes to this component using reverse BFS search
2.404 + queue.clear();
2.405 + for (int i = 0; i < int(_nodes.size()); ++i)
2.406 + if (found[_nodes[i]]) queue.push_back(_nodes[i]);
2.407 + int found_cnt = queue.size();
2.408 + while (found_cnt < int(_nodes.size())) {
2.409 + v = queue.front(); queue.pop_front();
2.410 + for (InArcIt e(_gr, v); e != INVALID; ++e) {
2.411 + u = _gr.source(e);
2.412 + if (_comp[u] == comp && !found[u]) {
2.413 + found[u] = true;
2.414 + ++found_cnt;
2.415 + _policy[u] = e;
2.416 + queue.push_back(u);
2.417 + }
2.418 + }
2.419 + }
2.420 + }
2.421 +
2.422 + // Compute node distances in the policy graph and update the
2.423 + // policy graph if the node distances can be improved.
2.424 + bool computeNodeDistances() {
2.425 + // Compute node distances using reverse BFS search
2.426 + double cycle_mean = double(_cycle_length) / _cycle_size;
2.427 + typename Digraph::template NodeMap<int> found(_gr, false);
2.428 + std::deque<Node> queue;
2.429 + queue.push_back(_cycle_node);
2.430 + found[_cycle_node] = true;
2.431 + _dist[_cycle_node] = 0;
2.432 + Node u, v;
2.433 + while (!queue.empty()) {
2.434 + v = queue.front(); queue.pop_front();
2.435 + for (InArcIt e(_gr, v); e != INVALID; ++e) {
2.436 + u = _gr.source(e);
2.437 + if (_policy[u] == e && !found[u]) {
2.438 + found[u] = true;
2.439 + _dist[u] = _dist[v] + _length[e] - cycle_mean;
2.440 + queue.push_back(u);
2.441 + }
2.442 + }
2.443 + }
2.444 + // Improving node distances
2.445 + bool improved = false;
2.446 + for (int j = 0; j < int(_arcs.size()); ++j) {
2.447 + Arc e = _arcs[j];
2.448 + u = _gr.source(e); v = _gr.target(e);
2.449 + double delta = _dist[v] + _length[e] - cycle_mean;
2.450 + if (_tol.less(delta, _dist[u])) {
2.451 + improved = true;
2.452 + _dist[u] = delta;
2.453 + _policy[u] = e;
2.454 + }
2.455 + }
2.456 + return improved;
2.457 + }
2.458 +
2.459 + }; //class MinMeanCycle
2.460 +
2.461 + ///@}
2.462 +
2.463 +} //namespace lemon
2.464 +
2.465 +#endif //LEMON_MIN_MEAN_CYCLE_H