COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/johnson.h @ 1740:4cade8579363

Last change on this file since 1740:4cade8579363 was 1723:fb4f801dd692, checked in by Balazs Dezso, 15 years ago

Really short description of these shortest path algorithms

File size: 18.3 KB
Line 
1/* -*- C++ -*-
2 * lemon/johnson.h - Part of LEMON, a generic C++ optimization library
3 *
4 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Research Group on Combinatorial Optimization, EGRES).
6 *
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
10 *
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
13 * purpose.
14 *
15 */
16
17#ifndef LEMON_JOHNSON_H
18#define LEMON_JOHNSON_H
19
20///\ingroup flowalgs
21/// \file
22/// \brief Johnson algorithm.
23///
24
25#include <lemon/list_graph.h>
26#include <lemon/graph_utils.h>
27#include <lemon/dijkstra.h>
28#include <lemon/belmann_ford.h>
29#include <lemon/invalid.h>
30#include <lemon/error.h>
31#include <lemon/maps.h>
32#include <lemon/matrix_maps.h>
33
34#include <limits>
35
36namespace lemon {
37
38  /// \brief Default OperationTraits for the Johnson algorithm class.
39  /// 
40  /// It defines all computational operations and constants which are
41  /// used in the Floyd-Warshall algorithm. The default implementation
42  /// is based on the numeric_limits class. If the numeric type does not
43  /// have infinity value then the maximum value is used as extremal
44  /// infinity value.
45  template <
46    typename Value,
47    bool has_infinity = std::numeric_limits<Value>::has_infinity>
48  struct JohnsonDefaultOperationTraits {
49    /// \brief Gives back the zero value of the type.
50    static Value zero() {
51      return static_cast<Value>(0);
52    }
53    /// \brief Gives back the positive infinity value of the type.
54    static Value infinity() {
55      return std::numeric_limits<Value>::infinity();
56    }
57    /// \brief Gives back the sum of the given two elements.
58    static Value plus(const Value& left, const Value& right) {
59      return left + right;
60    }
61    /// \brief Gives back true only if the first value less than the second.
62    static bool less(const Value& left, const Value& right) {
63      return left < right;
64    }
65  };
66
67  template <typename Value>
68  struct JohnsonDefaultOperationTraits<Value, false> {
69    static Value zero() {
70      return static_cast<Value>(0);
71    }
72    static Value infinity() {
73      return std::numeric_limits<Value>::max();
74    }
75    static Value plus(const Value& left, const Value& right) {
76      if (left == infinity() || right == infinity()) return infinity();
77      return left + right;
78    }
79    static bool less(const Value& left, const Value& right) {
80      return left < right;
81    }
82  };
83 
84  /// \brief Default traits class of Johnson class.
85  ///
86  /// Default traits class of Johnson class.
87  /// \param _Graph Graph type.
88  /// \param _LegthMap Type of length map.
89  template<class _Graph, class _LengthMap>
90  struct JohnsonDefaultTraits {
91    /// The graph type the algorithm runs on.
92    typedef _Graph Graph;
93
94    /// \brief The type of the map that stores the edge lengths.
95    ///
96    /// The type of the map that stores the edge lengths.
97    /// It must meet the \ref concept::ReadMap "ReadMap" concept.
98    typedef _LengthMap LengthMap;
99
100    // The type of the length of the edges.
101    typedef typename _LengthMap::Value Value;
102
103    /// \brief Operation traits for belmann-ford algorithm.
104    ///
105    /// It defines the infinity type on the given Value type
106    /// and the used operation.
107    /// \see JohnsonDefaultOperationTraits
108    typedef JohnsonDefaultOperationTraits<Value> OperationTraits;
109 
110    /// \brief The type of the matrix map that stores the last edges of the
111    /// shortest paths.
112    ///
113    /// The type of the map that stores the last edges of the shortest paths.
114    /// It must be a matrix map with \c Graph::Edge value type.
115    ///
116    typedef DynamicMatrixMap<Graph, typename Graph::Node,
117                             typename Graph::Edge> PredMap;
118
119    /// \brief Instantiates a PredMap.
120    ///
121    /// This function instantiates a \ref PredMap.
122    /// \param G is the graph, to which we would like to define the PredMap.
123    /// \todo The graph alone may be insufficient for the initialization
124    static PredMap *createPredMap(const _Graph& graph) {
125      return new PredMap(graph);
126    }
127
128    /// \brief The type of the matrix map that stores the dists of the nodes.
129    ///
130    /// The type of the matrix map that stores the dists of the nodes.
131    /// It must meet the \ref concept::WriteMatrixMap "WriteMatrixMap" concept.
132    ///
133    typedef DynamicMatrixMap<Graph, typename Graph::Node, Value> DistMap;
134   
135    /// \brief Instantiates a DistMap.
136    ///
137    /// This function instantiates a \ref DistMap.
138    /// \param G is the graph, to which we would like to define the
139    /// \ref DistMap
140    static DistMap *createDistMap(const _Graph& graph) {
141      return new DistMap(graph);
142    }
143
144  };
145
146  /// \brief Johnson algorithm class.
147  ///
148  /// \ingroup flowalgs
149  /// This class provides an efficient implementation of \c Johnson
150  /// algorithm. The edge lengths are passed to the algorithm using a
151  /// \ref concept::ReadMap "ReadMap", so it is easy to change it to any
152  /// kind of length.
153  ///
154  /// The algorithm solves the shortest path problem for each pairs
155  /// of node when the edges can have negative length but the graph should
156  /// not contain circle with negative sum of length. If we can assume
157  /// that all edge is non-negative in the graph then the dijkstra algorithm
158  /// should be used from each node.
159  ///
160  /// The complexity of this algorithm is $O(n^2 * log(n) + n * log(n) * e)$ or
161  /// with fibonacci heap O(n^2 * log(n) + n * e).
162  ///
163  /// The type of the length is determined by the
164  /// \ref concept::ReadMap::Value "Value" of the length map.
165  ///
166  /// \param _Graph The graph type the algorithm runs on. The default value
167  /// is \ref ListGraph. The value of _Graph is not used directly by
168  /// Johnson, it is only passed to \ref JohnsonDefaultTraits.
169  /// \param _LengthMap This read-only EdgeMap determines the lengths of the
170  /// edges. It is read once for each edge, so the map may involve in
171  /// relatively time consuming process to compute the edge length if
172  /// it is necessary. The default map type is \ref
173  /// concept::StaticGraph::EdgeMap "Graph::EdgeMap<int>".  The value
174  /// of _LengthMap is not used directly by Johnson, it is only passed
175  /// to \ref JohnsonDefaultTraits.  \param _Traits Traits class to set
176  /// various data types used by the algorithm.  The default traits
177  /// class is \ref JohnsonDefaultTraits
178  /// "JohnsonDefaultTraits<_Graph,_LengthMap>".  See \ref
179  /// JohnsonDefaultTraits for the documentation of a Johnson traits
180  /// class.
181  ///
182  /// \author Balazs Dezso
183
184#ifdef DOXYGEN
185  template <typename _Graph, typename _LengthMap, typename _Traits>
186#else
187  template <typename _Graph=ListGraph,
188            typename _LengthMap=typename _Graph::template EdgeMap<int>,
189            typename _Traits=JohnsonDefaultTraits<_Graph,_LengthMap> >
190#endif
191  class Johnson {
192  public:
193   
194    /// \brief \ref Exception for uninitialized parameters.
195    ///
196    /// This error represents problems in the initialization
197    /// of the parameters of the algorithms.
198
199    class UninitializedParameter : public lemon::UninitializedParameter {
200    public:
201      virtual const char* exceptionName() const {
202        return "lemon::Johnson::UninitializedParameter";
203      }
204    };
205
206    typedef _Traits Traits;
207    ///The type of the underlying graph.
208    typedef typename _Traits::Graph Graph;
209
210    typedef typename Graph::Node Node;
211    typedef typename Graph::NodeIt NodeIt;
212    typedef typename Graph::Edge Edge;
213    typedef typename Graph::EdgeIt EdgeIt;
214   
215    /// \brief The type of the length of the edges.
216    typedef typename _Traits::LengthMap::Value Value;
217    /// \brief The type of the map that stores the edge lengths.
218    typedef typename _Traits::LengthMap LengthMap;
219    /// \brief The type of the map that stores the last
220    /// edges of the shortest paths. The type of the PredMap
221    /// is a matrix map for Edges
222    typedef typename _Traits::PredMap PredMap;
223    /// \brief The type of the map that stores the dists of the nodes.
224    /// The type of the DistMap is a matrix map for Values
225    typedef typename _Traits::DistMap DistMap;
226    /// \brief The operation traits.
227    typedef typename _Traits::OperationTraits OperationTraits;
228  private:
229    /// Pointer to the underlying graph.
230    const Graph *graph;
231    /// Pointer to the length map
232    const LengthMap *length;
233    ///Pointer to the map of predecessors edges.
234    PredMap *_pred;
235    ///Indicates if \ref _pred is locally allocated (\c true) or not.
236    bool local_pred;
237    ///Pointer to the map of distances.
238    DistMap *_dist;
239    ///Indicates if \ref _dist is locally allocated (\c true) or not.
240    bool local_dist;
241
242    /// Creates the maps if necessary.
243    void create_maps() {
244      if(!_pred) {
245        local_pred = true;
246        _pred = Traits::createPredMap(*graph);
247      }
248      if(!_dist) {
249        local_dist = true;
250        _dist = Traits::createDistMap(*graph);
251      }
252    }
253   
254  public :
255 
256    /// \name Named template parameters
257
258    ///@{
259
260    template <class T>
261    struct DefPredMapTraits : public Traits {
262      typedef T PredMap;
263      static PredMap *createPredMap(const Graph& graph) {
264        throw UninitializedParameter();
265      }
266    };
267
268    /// \brief \ref named-templ-param "Named parameter" for setting PredMap
269    /// type
270    /// \ref named-templ-param "Named parameter" for setting PredMap type
271    ///
272    template <class T>
273    struct DefPredMap
274      : public Johnson< Graph, LengthMap, DefPredMapTraits<T> > {
275      typedef Johnson< Graph, LengthMap, DefPredMapTraits<T> > Create;
276    };
277   
278    template <class T>
279    struct DefDistMapTraits : public Traits {
280      typedef T DistMap;
281      static DistMap *createDistMap(const Graph& graph) {
282        throw UninitializedParameter();
283      }
284    };
285    /// \brief \ref named-templ-param "Named parameter" for setting DistMap
286    /// type
287    ///
288    /// \ref named-templ-param "Named parameter" for setting DistMap type
289    ///
290    template <class T>
291    struct DefDistMap
292      : public Johnson< Graph, LengthMap, DefDistMapTraits<T> > {
293      typedef Johnson< Graph, LengthMap, DefDistMapTraits<T> > Create;
294    };
295   
296    template <class T>
297    struct DefOperationTraitsTraits : public Traits {
298      typedef T OperationTraits;
299    };
300   
301    /// \brief \ref named-templ-param "Named parameter" for setting
302    /// OperationTraits type
303    ///
304    /// \ref named-templ-param "Named parameter" for setting
305    /// OperationTraits type
306    template <class T>
307    struct DefOperationTraits
308      : public Johnson< Graph, LengthMap, DefOperationTraitsTraits<T> > {
309      typedef Johnson< Graph, LengthMap, DefOperationTraitsTraits<T> > Create;
310    };
311   
312    ///@}
313
314  protected:
315
316    Johnson() {}
317
318  public:     
319   
320    /// \brief Constructor.
321    ///
322    /// \param _graph the graph the algorithm will run on.
323    /// \param _length the length map used by the algorithm.
324    Johnson(const Graph& _graph, const LengthMap& _length) :
325      graph(&_graph), length(&_length),
326      _pred(0), local_pred(false),
327      _dist(0), local_dist(false) {}
328   
329    ///Destructor.
330    ~Johnson() {
331      if(local_pred) delete _pred;
332      if(local_dist) delete _dist;
333    }
334
335    /// \brief Sets the length map.
336    ///
337    /// Sets the length map.
338    /// \return \c (*this)
339    Johnson &lengthMap(const LengthMap &m) {
340      length = &m;
341      return *this;
342    }
343
344    /// \brief Sets the map storing the predecessor edges.
345    ///
346    /// Sets the map storing the predecessor edges.
347    /// If you don't use this function before calling \ref run(),
348    /// it will allocate one. The destuctor deallocates this
349    /// automatically allocated map, of course.
350    /// \return \c (*this)
351    Johnson &predMap(PredMap &m) {
352      if(local_pred) {
353        delete _pred;
354        local_pred=false;
355      }
356      _pred = &m;
357      return *this;
358    }
359
360    /// \brief Sets the map storing the distances calculated by the algorithm.
361    ///
362    /// Sets the map storing the distances calculated by the algorithm.
363    /// If you don't use this function before calling \ref run(),
364    /// it will allocate one. The destuctor deallocates this
365    /// automatically allocated map, of course.
366    /// \return \c (*this)
367    Johnson &distMap(DistMap &m) {
368      if(local_dist) {
369        delete _dist;
370        local_dist=false;
371      }
372      _dist = &m;
373      return *this;
374    }
375
376    ///\name Execution control
377    /// The simplest way to execute the algorithm is to use
378    /// one of the member functions called \c run(...).
379    /// \n
380    /// If you need more control on the execution,
381    /// Finally \ref start() will perform the actual path
382    /// computation.
383
384    ///@{
385
386    /// \brief Initializes the internal data structures.
387    ///
388    /// Initializes the internal data structures.
389    void init() {
390      create_maps();
391    }
392   
393    /// \brief Executes the algorithm.
394    ///
395    /// This method runs the %Johnson algorithm in order to compute
396    /// the shortest path to each node pairs. The algorithm
397    /// computes
398    /// - The shortest path tree for each node.
399    /// - The distance between each node pairs.
400    void start() {
401      typedef typename BelmannFord<Graph, LengthMap>::
402      template DefOperationTraits<OperationTraits>::
403      template DefPredMap<NullMap<Node, Edge> >::
404      Create BelmannFordType;
405
406      BelmannFordType belmannford(*graph, *length);
407
408      NullMap<Node, Edge> predMap;
409
410      belmannford.predMap(predMap);
411     
412      belmannford.init(OperationTraits::zero());
413      belmannford.start();
414
415      for (NodeIt it(*graph); it != INVALID; ++it) {
416        typedef PotentialDifferenceMap<Graph,
417          typename BelmannFordType::DistMap> PotDiffMap;
418        PotDiffMap potdiff(*graph, belmannford.distMap());
419        typedef SubMap<LengthMap, PotDiffMap> ShiftLengthMap;
420        ShiftLengthMap shiftlen(*length, potdiff);
421        Dijkstra<Graph, ShiftLengthMap> dijkstra(*graph, shiftlen);
422        dijkstra.run(it);
423        for (NodeIt jt(*graph); jt != INVALID; ++jt) {
424          if (dijkstra.reached(jt)) {
425            _dist->set(it, jt, dijkstra.dist(jt) +
426                       belmannford.dist(jt) - belmannford.dist(it));
427            _pred->set(it, jt, dijkstra.pred(jt));
428          } else {
429            _dist->set(it, jt, OperationTraits::infinity());
430            _pred->set(it, jt, INVALID);
431          }
432        }
433      }
434    }
435   
436    /// \brief Runs %Johnson algorithm.
437    ///   
438    /// This method runs the %Johnson algorithm from a each node
439    /// in order to compute the shortest path to each node pairs.
440    /// The algorithm computes
441    /// - The shortest path tree for each node.
442    /// - The distance between each node pairs.
443    ///
444    /// \note d.run(s) is just a shortcut of the following code.
445    /// \code
446    ///  d.init();
447    ///  d.start();
448    /// \endcode
449    void run() {
450      init();
451      start();
452    }
453   
454    ///@}
455
456    /// \name Query Functions
457    /// The result of the %Johnson algorithm can be obtained using these
458    /// functions.\n
459    /// Before the use of these functions,
460    /// either run() or start() must be called.
461   
462    ///@{
463
464    /// \brief Copies the shortest path to \c t into \c p
465    ///   
466    /// This function copies the shortest path to \c t into \c p.
467    /// If it \c t is a source itself or unreachable, then it does not
468    /// alter \c p.
469    /// \todo Is it the right way to handle unreachable nodes?
470    /// \return Returns \c true if a path to \c t was actually copied to \c p,
471    /// \c false otherwise.
472    /// \sa DirPath
473    template <typename Path>
474    bool getPath(Path &p, Node source, Node target) {
475      if (connected(source, target)) {
476        p.clear();
477        typename Path::Builder b(target);
478        for(b.setStartNode(target); pred(source, target) != INVALID;
479            target = predNode(target)) {
480          b.pushFront(pred(source, target));
481        }
482        b.commit();
483        return true;
484      }
485      return false;
486    }
487         
488    /// \brief The distance between two nodes.
489    ///
490    /// Returns the distance between two nodes.
491    /// \pre \ref run() must be called before using this function.
492    /// \warning If node \c v in unreachable from the root the return value
493    /// of this funcion is undefined.
494    Value dist(Node source, Node target) const {
495      return (*_dist)(source, target);
496    }
497
498    /// \brief Returns the 'previous edge' of the shortest path tree.
499    ///
500    /// For the node \c node it returns the 'previous edge' of the shortest
501    /// path tree to direction of the node \c root
502    /// i.e. it returns the last edge of a shortest path from the node \c root
503    /// to \c node. It is \ref INVALID if \c node is unreachable from the root
504    /// or if \c node=root. The shortest path tree used here is equal to the
505    /// shortest path tree used in \ref predNode().
506    /// \pre \ref run() must be called before using this function.
507    /// \todo predEdge could be a better name.
508    Edge pred(Node root, Node node) const {
509      return (*_pred)(root, node);
510    }
511
512    /// \brief Returns the 'previous node' of the shortest path tree.
513    ///
514    /// For a node \c node it returns the 'previous node' of the shortest path
515    /// tree to direction of the node \c root, i.e. it returns the last but
516    /// one node from a shortest path from the \c root to \c node. It is
517    /// INVALID if \c node is unreachable from the root or if \c node=root.
518    /// The shortest path tree used here is equal to the
519    /// shortest path tree used in \ref pred(). 
520    /// \pre \ref run() must be called before using this function.
521    Node predNode(Node root, Node node) const {
522      return (*_pred)(root, node) == INVALID ?
523      INVALID : graph->source((*_pred)(root, node));
524    }
525   
526    /// \brief Returns a reference to the matrix node map of distances.
527    ///
528    /// Returns a reference to the matrix node map of distances.
529    ///
530    /// \pre \ref run() must be called before using this function.
531    const DistMap &distMap() const { return *_dist;}
532 
533    /// \brief Returns a reference to the shortest path tree map.
534    ///
535    /// Returns a reference to the matrix node map of the edges of the
536    /// shortest path tree.
537    /// \pre \ref run() must be called before using this function.
538    const PredMap &predMap() const { return *_pred;}
539 
540    /// \brief Checks if a node is reachable from the root.
541    ///
542    /// Returns \c true if \c v is reachable from the root.
543    /// \pre \ref run() must be called before using this function.
544    ///
545    bool connected(Node source, Node target) {
546      return (*_dist)(source, target) != OperationTraits::infinity();
547    }
548   
549    ///@}
550  };
551 
552} //END OF NAMESPACE LEMON
553
554#endif
Note: See TracBrowser for help on using the repository browser.