1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2013
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
19 #ifndef LEMON_HOWARD_MMC_H
20 #define LEMON_HOWARD_MMC_H
22 /// \ingroup min_mean_cycle
25 /// \brief Howard's algorithm for finding a minimum mean cycle.
29 #include <lemon/core.h>
30 #include <lemon/path.h>
31 #include <lemon/tolerance.h>
32 #include <lemon/connectivity.h>
36 /// \brief Default traits class of HowardMmc class.
38 /// Default traits class of HowardMmc class.
39 /// \tparam GR The type of the digraph.
40 /// \tparam CM The type of the cost map.
41 /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
43 template <typename GR, typename CM>
45 template <typename GR, typename CM,
46 bool integer = std::numeric_limits<typename CM::Value>::is_integer>
48 struct HowardMmcDefaultTraits
50 /// The type of the digraph
52 /// The type of the cost map
54 /// The type of the arc costs
55 typedef typename CostMap::Value Cost;
57 /// \brief The large cost type used for internal computations
59 /// The large cost type used for internal computations.
60 /// It is \c long \c long if the \c Cost type is integer,
61 /// otherwise it is \c double.
62 /// \c Cost must be convertible to \c LargeCost.
63 typedef double LargeCost;
65 /// The tolerance type used for internal computations
66 typedef lemon::Tolerance<LargeCost> Tolerance;
68 /// \brief The path type of the found cycles
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;
76 // Default traits class for integer cost types
77 template <typename GR, typename CM>
78 struct HowardMmcDefaultTraits<GR, CM, true>
82 typedef typename CostMap::Value Cost;
83 #ifdef LEMON_HAVE_LONG_LONG
84 typedef long long LargeCost;
86 typedef long LargeCost;
88 typedef lemon::Tolerance<LargeCost> Tolerance;
89 typedef lemon::Path<Digraph> Path;
93 /// \addtogroup min_mean_cycle
96 /// \brief Implementation of Howard's algorithm for finding a minimum
99 /// This class implements Howard's policy iteration algorithm for finding
100 /// a directed cycle of minimum mean cost in a digraph
101 /// \cite dasdan98minmeancycle, \cite dasdan04experimental.
102 /// This class provides the most efficient algorithm for the
103 /// minimum mean cycle problem, though the best known theoretical
104 /// bound on its running time is exponential.
106 /// \tparam GR The type of the digraph the algorithm runs on.
107 /// \tparam CM The type of the cost map. The default
108 /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
109 /// \tparam TR The traits class that defines various types used by the
110 /// algorithm. By default, it is \ref HowardMmcDefaultTraits
111 /// "HowardMmcDefaultTraits<GR, CM>".
112 /// In most cases, this parameter should not be set directly,
113 /// consider to use the named template parameters instead.
115 template <typename GR, typename CM, typename TR>
117 template < typename GR,
118 typename CM = typename GR::template ArcMap<int>,
119 typename TR = HowardMmcDefaultTraits<GR, CM> >
125 /// The type of the digraph
126 typedef typename TR::Digraph Digraph;
127 /// The type of the cost map
128 typedef typename TR::CostMap CostMap;
129 /// The type of the arc costs
130 typedef typename TR::Cost Cost;
132 /// \brief The large cost type
134 /// The large cost type used for internal computations.
135 /// By default, it is \c long \c long if the \c Cost type is integer,
136 /// otherwise it is \c double.
137 typedef typename TR::LargeCost LargeCost;
139 /// The tolerance type
140 typedef typename TR::Tolerance Tolerance;
142 /// \brief The path type of the found cycles
144 /// The path type of the found cycles.
145 /// Using the \ref lemon::HowardMmcDefaultTraits "default traits class",
146 /// it is \ref lemon::Path "Path<Digraph>".
147 typedef typename TR::Path Path;
149 /// The \ref lemon::HowardMmcDefaultTraits "traits class" of the algorithm
152 /// \brief Constants for the causes of search termination.
154 /// Enum type containing constants for the different causes of search
155 /// termination. The \ref findCycleMean() function returns one of
157 enum TerminationCause {
159 /// No directed cycle can be found in the digraph.
162 /// Optimal solution (minimum cycle mean) is found.
165 /// The iteration count limit is reached.
171 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
173 // The digraph the algorithm runs on
175 // The cost of the arcs
176 const CostMap &_cost;
178 // Data for the found cycles
179 bool _curr_found, _best_found;
180 LargeCost _curr_cost, _best_cost;
181 int _curr_size, _best_size;
182 Node _curr_node, _best_node;
187 // Internal data used by the algorithm
188 typename Digraph::template NodeMap<Arc> _policy;
189 typename Digraph::template NodeMap<bool> _reached;
190 typename Digraph::template NodeMap<int> _level;
191 typename Digraph::template NodeMap<LargeCost> _dist;
193 // Data for storing the strongly connected components
195 typename Digraph::template NodeMap<int> _comp;
196 std::vector<std::vector<Node> > _comp_nodes;
197 std::vector<Node>* _nodes;
198 typename Digraph::template NodeMap<std::vector<Arc> > _in_arcs;
200 // Queue used for BFS search
201 std::vector<Node> _queue;
204 Tolerance _tolerance;
211 /// \name Named Template Parameters
214 template <typename T>
215 struct SetLargeCostTraits : public Traits {
217 typedef lemon::Tolerance<T> Tolerance;
220 /// \brief \ref named-templ-param "Named parameter" for setting
221 /// \c LargeCost type.
223 /// \ref named-templ-param "Named parameter" for setting \c LargeCost
224 /// type. It is used for internal computations in the algorithm.
225 template <typename T>
227 : public HowardMmc<GR, CM, SetLargeCostTraits<T> > {
228 typedef HowardMmc<GR, CM, SetLargeCostTraits<T> > Create;
231 template <typename T>
232 struct SetPathTraits : public Traits {
236 /// \brief \ref named-templ-param "Named parameter" for setting
239 /// \ref named-templ-param "Named parameter" for setting the \c %Path
240 /// type of the found cycles.
241 /// It must conform to the \ref lemon::concepts::Path "Path" concept
242 /// and it must have an \c addBack() function.
243 template <typename T>
245 : public HowardMmc<GR, CM, SetPathTraits<T> > {
246 typedef HowardMmc<GR, CM, SetPathTraits<T> > Create;
257 /// \brief Constructor.
259 /// The constructor of the class.
261 /// \param digraph The digraph the algorithm runs on.
262 /// \param cost The costs of the arcs.
263 HowardMmc( const Digraph &digraph,
264 const CostMap &cost ) :
265 _gr(digraph), _cost(cost), _best_found(false),
266 _best_cost(0), _best_size(1), _cycle_path(NULL), _local_path(false),
267 _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
268 _comp(digraph), _in_arcs(digraph),
269 INF(std::numeric_limits<LargeCost>::has_infinity ?
270 std::numeric_limits<LargeCost>::infinity() :
271 std::numeric_limits<LargeCost>::max())
276 if (_local_path) delete _cycle_path;
279 /// \brief Set the path structure for storing the found cycle.
281 /// This function sets an external path structure for storing the
284 /// If you don't call this function before calling \ref run() or
285 /// \ref findCycleMean(), a local \ref Path "path" structure
286 /// will be allocated. The destuctor deallocates this automatically
287 /// allocated object, of course.
289 /// \note The algorithm calls only the \ref lemon::Path::addBack()
290 /// "addBack()" function of the given path structure.
292 /// \return <tt>(*this)</tt>
293 HowardMmc& cycle(Path &path) {
302 /// \brief Set the tolerance used by the algorithm.
304 /// This function sets the tolerance object used by the algorithm.
306 /// \return <tt>(*this)</tt>
307 HowardMmc& tolerance(const Tolerance& tolerance) {
308 _tolerance = tolerance;
312 /// \brief Return a const reference to the tolerance.
314 /// This function returns a const reference to the tolerance object
315 /// used by the algorithm.
316 const Tolerance& tolerance() const {
320 /// \name Execution control
321 /// The simplest way to execute the algorithm is to call the \ref run()
323 /// If you only need the minimum mean cost, you may call
324 /// \ref findCycleMean().
328 /// \brief Run the algorithm.
330 /// This function runs the algorithm.
331 /// It can be called more than once (e.g. if the underlying digraph
332 /// and/or the arc costs have been modified).
334 /// \return \c true if a directed cycle exists in the digraph.
336 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
338 /// return mmc.findCycleMean() && mmc.findCycle();
341 return findCycleMean() && findCycle();
344 /// \brief Find the minimum cycle mean (or an upper bound).
346 /// This function finds the minimum mean cost of the directed
347 /// cycles in the digraph (or an upper bound for it).
349 /// By default, the function finds the exact minimum cycle mean,
350 /// but an optional limit can also be specified for the number of
351 /// iterations performed during the search process.
352 /// The return value indicates if the optimal solution is found
353 /// or the iteration limit is reached. In the latter case, an
354 /// approximate solution is provided, which corresponds to a directed
355 /// cycle whose mean cost is relatively small, but not necessarily
358 /// \param limit The maximum allowed number of iterations during
359 /// the search process. Its default value implies that the algorithm
360 /// runs until it finds the exact optimal solution.
362 /// \return The termination cause of the search process.
363 /// For more information, see \ref TerminationCause.
364 TerminationCause findCycleMean(int limit = std::numeric_limits<int>::max()) {
365 // Initialize and find strongly connected components
369 // Find the minimum cycle mean in the components
371 bool iter_limit_reached = false;
372 for (int comp = 0; comp < _comp_num; ++comp) {
373 // Find the minimum mean cycle in the current component
374 if (!buildPolicyGraph(comp)) continue;
376 if (++iter_count > limit) {
377 iter_limit_reached = true;
381 if (!computeNodeDistances()) break;
384 // Update the best cycle (global minimum mean cycle)
385 if ( _curr_found && (!_best_found ||
386 _curr_cost * _best_size < _best_cost * _curr_size) ) {
388 _best_cost = _curr_cost;
389 _best_size = _curr_size;
390 _best_node = _curr_node;
393 if (iter_limit_reached) break;
396 if (iter_limit_reached) {
397 return ITERATION_LIMIT;
399 return _best_found ? OPTIMAL : NO_CYCLE;
403 /// \brief Find a minimum mean directed cycle.
405 /// This function finds a directed cycle of minimum mean cost
406 /// in the digraph using the data computed by findCycleMean().
408 /// \return \c true if a directed cycle exists in the digraph.
410 /// \pre \ref findCycleMean() must be called before using this function.
412 if (!_best_found) return false;
413 _cycle_path->addBack(_policy[_best_node]);
414 for ( Node v = _best_node;
415 (v = _gr.target(_policy[v])) != _best_node; ) {
416 _cycle_path->addBack(_policy[v]);
423 /// \name Query Functions
424 /// The results of the algorithm can be obtained using these
426 /// The algorithm should be executed before using them.
430 /// \brief Return the total cost of the found cycle.
432 /// This function returns the total cost of the found cycle.
434 /// \pre \ref run() or \ref findCycleMean() must be called before
435 /// using this function.
436 Cost cycleCost() const {
437 return static_cast<Cost>(_best_cost);
440 /// \brief Return the number of arcs on the found cycle.
442 /// This function returns the number of arcs on the found cycle.
444 /// \pre \ref run() or \ref findCycleMean() must be called before
445 /// using this function.
446 int cycleSize() const {
450 /// \brief Return the mean cost of the found cycle.
452 /// This function returns the mean cost of the found cycle.
454 /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
457 /// return static_cast<double>(alg.cycleCost()) / alg.cycleSize();
460 /// \pre \ref run() or \ref findCycleMean() must be called before
461 /// using this function.
462 double cycleMean() const {
463 return static_cast<double>(_best_cost) / _best_size;
466 /// \brief Return the found cycle.
468 /// This function returns a const reference to the path structure
469 /// storing the found cycle.
471 /// \pre \ref run() or \ref findCycle() must be called before using
473 const Path& cycle() const {
485 _cycle_path = new Path;
487 _queue.resize(countNodes(_gr));
491 _cycle_path->clear();
494 // Find strongly connected components and initialize _comp_nodes
496 void findComponents() {
497 _comp_num = stronglyConnectedComponents(_gr, _comp);
498 _comp_nodes.resize(_comp_num);
499 if (_comp_num == 1) {
500 _comp_nodes[0].clear();
501 for (NodeIt n(_gr); n != INVALID; ++n) {
502 _comp_nodes[0].push_back(n);
504 for (InArcIt a(_gr, n); a != INVALID; ++a) {
505 _in_arcs[n].push_back(a);
509 for (int i = 0; i < _comp_num; ++i)
510 _comp_nodes[i].clear();
511 for (NodeIt n(_gr); n != INVALID; ++n) {
513 _comp_nodes[k].push_back(n);
515 for (InArcIt a(_gr, n); a != INVALID; ++a) {
516 if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
522 // Build the policy graph in the given strongly connected component
523 // (the out-degree of every node is 1)
524 bool buildPolicyGraph(int comp) {
525 _nodes = &(_comp_nodes[comp]);
526 if (_nodes->size() < 1 ||
527 (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
530 for (int i = 0; i < int(_nodes->size()); ++i) {
531 _dist[(*_nodes)[i]] = INF;
535 for (int i = 0; i < int(_nodes->size()); ++i) {
537 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
540 if (_cost[e] < _dist[u]) {
549 // Find the minimum mean cycle in the policy graph
550 void findPolicyCycle() {
551 for (int i = 0; i < int(_nodes->size()); ++i) {
552 _level[(*_nodes)[i]] = -1;
558 for (int i = 0; i < int(_nodes->size()); ++i) {
560 if (_level[u] >= 0) continue;
561 for (; _level[u] < 0; u = _gr.target(_policy[u])) {
564 if (_level[u] == i) {
566 ccost = _cost[_policy[u]];
568 for (v = u; (v = _gr.target(_policy[v])) != u; ) {
569 ccost += _cost[_policy[v]];
573 (ccost * _curr_size < _curr_cost * csize) ) {
583 // Contract the policy graph and compute node distances
584 bool computeNodeDistances() {
585 // Find the component of the main cycle and compute node distances
587 for (int i = 0; i < int(_nodes->size()); ++i) {
588 _reached[(*_nodes)[i]] = false;
590 _qfront = _qback = 0;
591 _queue[0] = _curr_node;
592 _reached[_curr_node] = true;
593 _dist[_curr_node] = 0;
596 while (_qfront <= _qback) {
597 v = _queue[_qfront++];
598 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
601 if (_policy[u] == e && !_reached[u]) {
603 _dist[u] = _dist[v] + _cost[e] * _curr_size - _curr_cost;
604 _queue[++_qback] = u;
609 // Connect all other nodes to this component and compute node
610 // distances using reverse BFS
612 while (_qback < int(_nodes->size())-1) {
613 v = _queue[_qfront++];
614 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
620 _dist[u] = _dist[v] + _cost[e] * _curr_size - _curr_cost;
621 _queue[++_qback] = u;
626 // Improve node distances
627 bool improved = false;
628 for (int i = 0; i < int(_nodes->size()); ++i) {
630 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
633 LargeCost delta = _dist[v] + _cost[e] * _curr_size - _curr_cost;
634 if (_tolerance.less(delta, _dist[u])) {
650 #endif //LEMON_HOWARD_MMC_H