COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/johnson.h @ 1700:30fe294ac801

Last change on this file since 1700:30fe294ac801 was 1699:29428f7b8b66, checked in by Balazs Dezso, 18 years ago

Some shortest path algorithms
All-pair-shortest path algorithms without function interface
we may need it

File size: 17.7 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/dfs.h>
28#include <lemon/dijkstra.h>
29#include <lemon/belmann_ford.h>
30#include <lemon/invalid.h>
31#include <lemon/error.h>
32#include <lemon/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 map that stores the last edges of the
111    /// shortest paths.
112    ///
113    /// The type of the map that stores the last
114    /// edges of the shortest paths.
115    /// It must be a matrix map with \c Graph::Edge value type.
116    ///
117    typedef NodeMatrixMap<Graph, 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 map that stores the dists of the nodes.
129    ///
130    /// The type of the map that stores the dists of the nodes.
131    /// It must meet the \ref concept::WriteMap "WriteMap" concept.
132    ///
133    typedef NodeMatrixMap<Graph, 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 type of the length is determined by the
155  /// \ref concept::ReadMap::Value "Value" of the length map.
156  ///
157  /// \param _Graph The graph type the algorithm runs on. The default value
158  /// is \ref ListGraph. The value of _Graph is not used directly by
159  /// Johnson, it is only passed to \ref JohnsonDefaultTraits.
160  /// \param _LengthMap This read-only EdgeMap determines the lengths of the
161  /// edges. It is read once for each edge, so the map may involve in
162  /// relatively time consuming process to compute the edge length if
163  /// it is necessary. The default map type is \ref
164  /// concept::StaticGraph::EdgeMap "Graph::EdgeMap<int>".  The value
165  /// of _LengthMap is not used directly by Johnson, it is only passed
166  /// to \ref JohnsonDefaultTraits.  \param _Traits Traits class to set
167  /// various data types used by the algorithm.  The default traits
168  /// class is \ref JohnsonDefaultTraits
169  /// "JohnsonDefaultTraits<_Graph,_LengthMap>".  See \ref
170  /// JohnsonDefaultTraits for the documentation of a Johnson traits
171  /// class.
172  ///
173  /// \author Balazs Dezso
174
175  template <typename _Graph=ListGraph,
176            typename _LengthMap=typename _Graph::template EdgeMap<int>,
177            typename _Traits=JohnsonDefaultTraits<_Graph,_LengthMap> >
178  class Johnson {
179  public:
180   
181    /// \brief \ref Exception for uninitialized parameters.
182    ///
183    /// This error represents problems in the initialization
184    /// of the parameters of the algorithms.
185
186    class UninitializedParameter : public lemon::UninitializedParameter {
187    public:
188      virtual const char* exceptionName() const {
189        return "lemon::Johnson::UninitializedParameter";
190      }
191    };
192
193    typedef _Traits Traits;
194    ///The type of the underlying graph.
195    typedef typename _Traits::Graph Graph;
196
197    typedef typename Graph::Node Node;
198    typedef typename Graph::NodeIt NodeIt;
199    typedef typename Graph::Edge Edge;
200    typedef typename Graph::EdgeIt EdgeIt;
201   
202    /// \brief The type of the length of the edges.
203    typedef typename _Traits::LengthMap::Value Value;
204    /// \brief The type of the map that stores the edge lengths.
205    typedef typename _Traits::LengthMap LengthMap;
206    /// \brief The type of the map that stores the last
207    /// edges of the shortest paths. The type of the PredMap
208    /// is a matrix map for Edges
209    typedef typename _Traits::PredMap PredMap;
210    /// \brief The type of the map that stores the dists of the nodes.
211    /// The type of the DistMap is a matrix map for Values
212    typedef typename _Traits::DistMap DistMap;
213    /// \brief The operation traits.
214    typedef typename _Traits::OperationTraits OperationTraits;
215  private:
216    /// Pointer to the underlying graph.
217    const Graph *graph;
218    /// Pointer to the length map
219    const LengthMap *length;
220    ///Pointer to the map of predecessors edges.
221    PredMap *_pred;
222    ///Indicates if \ref _pred is locally allocated (\c true) or not.
223    bool local_pred;
224    ///Pointer to the map of distances.
225    DistMap *_dist;
226    ///Indicates if \ref _dist is locally allocated (\c true) or not.
227    bool local_dist;
228
229    /// Creates the maps if necessary.
230    void create_maps() {
231      if(!_pred) {
232        local_pred = true;
233        _pred = Traits::createPredMap(*graph);
234      }
235      if(!_dist) {
236        local_dist = true;
237        _dist = Traits::createDistMap(*graph);
238      }
239    }
240   
241  public :
242 
243    /// \name Named template parameters
244
245    ///@{
246
247    template <class T>
248    struct DefPredMapTraits : public Traits {
249      typedef T PredMap;
250      static PredMap *createPredMap(const Graph& graph) {
251        throw UninitializedParameter();
252      }
253    };
254
255    /// \brief \ref named-templ-param "Named parameter" for setting PredMap
256    /// type
257    /// \ref named-templ-param "Named parameter" for setting PredMap type
258    ///
259    template <class T>
260    class DefPredMap
261      : public Johnson< Graph, LengthMap, DefPredMapTraits<T> > {};
262   
263    template <class T>
264    struct DefDistMapTraits : public Traits {
265      typedef T DistMap;
266      static DistMap *createDistMap(const Graph& graph) {
267        throw UninitializedParameter();
268      }
269    };
270    /// \brief \ref named-templ-param "Named parameter" for setting DistMap
271    /// type
272    ///
273    /// \ref named-templ-param "Named parameter" for setting DistMap type
274    ///
275    template <class T>
276    class DefDistMap
277      : public Johnson< Graph, LengthMap, DefDistMapTraits<T> > {};
278   
279    template <class T>
280    struct DefOperationTraitsTraits : public Traits {
281      typedef T OperationTraits;
282    };
283   
284    /// \brief \ref named-templ-param "Named parameter" for setting
285    /// OperationTraits type
286    ///
287    /// \ref named-templ-param "Named parameter" for setting PredMap type
288    template <class T>
289    class DefOperationTraits
290      : public Johnson< Graph, LengthMap, DefOperationTraitsTraits<T> > {};
291   
292    ///@}
293
294  public:     
295   
296    /// \brief Constructor.
297    ///
298    /// \param _graph the graph the algorithm will run on.
299    /// \param _length the length map used by the algorithm.
300    Johnson(const Graph& _graph, const LengthMap& _length) :
301      graph(&_graph), length(&_length),
302      _pred(0), local_pred(false),
303      _dist(0), local_dist(false) {}
304   
305    ///Destructor.
306    ~Johnson() {
307      if(local_pred) delete _pred;
308      if(local_dist) delete _dist;
309    }
310
311    /// \brief Sets the length map.
312    ///
313    /// Sets the length map.
314    /// \return \c (*this)
315    Johnson &lengthMap(const LengthMap &m) {
316      length = &m;
317      return *this;
318    }
319
320    /// \brief Sets the map storing the predecessor edges.
321    ///
322    /// Sets the map storing the predecessor edges.
323    /// If you don't use this function before calling \ref run(),
324    /// it will allocate one. The destuctor deallocates this
325    /// automatically allocated map, of course.
326    /// \return \c (*this)
327    Johnson &predMap(PredMap &m) {
328      if(local_pred) {
329        delete _pred;
330        local_pred=false;
331      }
332      _pred = &m;
333      return *this;
334    }
335
336    /// \brief Sets the map storing the distances calculated by the algorithm.
337    ///
338    /// Sets the map storing the distances calculated by the algorithm.
339    /// If you don't use this function before calling \ref run(),
340    /// it will allocate one. The destuctor deallocates this
341    /// automatically allocated map, of course.
342    /// \return \c (*this)
343    Johnson &distMap(DistMap &m) {
344      if(local_dist) {
345        delete _dist;
346        local_dist=false;
347      }
348      _dist = &m;
349      return *this;
350    }
351
352    ///\name Execution control
353    /// The simplest way to execute the algorithm is to use
354    /// one of the member functions called \c run(...).
355    /// \n
356    /// If you need more control on the execution,
357    /// Finally \ref start() will perform the actual path
358    /// computation.
359
360    ///@{
361
362    /// \brief Initializes the internal data structures.
363    ///
364    /// Initializes the internal data structures.
365    void init() {
366      create_maps();
367    }
368   
369    /// \brief Executes the algorithm.
370    ///
371    /// This method runs the %Johnson algorithm in order to compute
372    /// the shortest path to each node pairs. The algorithm
373    /// computes
374    /// - The shortest path tree for each node.
375    /// - The distance between each node pairs.
376    void start() {
377      typename BelmannFord<Graph, LengthMap>::
378      template DefOperationTraits<OperationTraits>::
379      BelmannFord belmannford(*graph, *length);
380     
381      belmannford.init();
382
383      typename Graph::template NodeMap<bool> initial(*graph, false);
384
385      {
386        Dfs<Graph> dfs(*graph);
387
388        dfs.init();
389        for (NodeIt it(*graph); it != INVALID; ++it) {
390          if (!dfs.reached(it)) {
391            dfs.addSource(it);
392            while (!dfs.emptyQueue()) {
393              Edge edge = dfs.processNextEdge();
394              initial.set(graph->target(edge), false);
395            }
396            initial.set(it, true);
397          }
398        }
399        for (NodeIt it(*graph); it != INVALID; ++it) {
400          if (initial[it]) {
401            belmannford.addSource(it);
402          }
403        }
404      }
405
406      belmannford.start();
407
408      for (NodeIt it(*graph); it != INVALID; ++it) {
409        typedef PotentialDifferenceMap<Graph,
410          typename BelmannFord<Graph, LengthMap>::DistMap> PotDiffMap;
411        PotDiffMap potdiff(*graph, belmannford.distMap());
412        typedef SubMap<LengthMap, PotDiffMap> ShiftLengthMap;
413        ShiftLengthMap shiftlen(*length, potdiff);
414        Dijkstra<Graph, ShiftLengthMap> dijkstra(*graph, shiftlen);
415        dijkstra.run(it);
416        for (NodeIt jt(*graph); jt != INVALID; ++jt) {
417          if (dijkstra.reached(jt)) {
418            _dist->set(it, jt, dijkstra.dist(jt) +
419                       belmannford.dist(jt) - belmannford.dist(it));
420            _pred->set(it, jt, dijkstra.pred(jt));
421          } else {
422            _dist->set(it, jt, OperationTraits::infinity());
423            _pred->set(it, jt, INVALID);
424          }
425        }
426      }
427    }
428   
429    /// \brief Runs %Johnson algorithm.
430    ///   
431    /// This method runs the %Johnson algorithm from a each node
432    /// in order to compute the shortest path to each node pairs.
433    /// The algorithm computes
434    /// - The shortest path tree for each node.
435    /// - The distance between each node pairs.
436    ///
437    /// \note d.run(s) is just a shortcut of the following code.
438    /// \code
439    ///  d.init();
440    ///  d.start();
441    /// \endcode
442    void run() {
443      init();
444      start();
445    }
446   
447    ///@}
448
449    /// \name Query Functions
450    /// The result of the %Johnson algorithm can be obtained using these
451    /// functions.\n
452    /// Before the use of these functions,
453    /// either run() or start() must be called.
454   
455    ///@{
456
457    /// \brief Copies the shortest path to \c t into \c p
458    ///   
459    /// This function copies the shortest path to \c t into \c p.
460    /// If it \c t is a source itself or unreachable, then it does not
461    /// alter \c p.
462    /// \todo Is it the right way to handle unreachable nodes?
463    /// \return Returns \c true if a path to \c t was actually copied to \c p,
464    /// \c false otherwise.
465    /// \sa DirPath
466    template <typename Path>
467    bool getPath(Path &p, Node source, Node target) {
468      if (connected(source, target)) {
469        p.clear();
470        typename Path::Builder b(target);
471        for(b.setStartNode(target); pred(source, target) != INVALID;
472            target = predNode(target)) {
473          b.pushFront(pred(source, target));
474        }
475        b.commit();
476        return true;
477      }
478      return false;
479    }
480         
481    /// \brief The distance between two nodes.
482    ///
483    /// Returns the distance between two nodes.
484    /// \pre \ref run() must be called before using this function.
485    /// \warning If node \c v in unreachable from the root the return value
486    /// of this funcion is undefined.
487    Value dist(Node source, Node target) const {
488      return (*_dist)(source, target);
489    }
490
491    /// \brief Returns the 'previous edge' of the shortest path tree.
492    ///
493    /// For the node \c node it returns the 'previous edge' of the shortest
494    /// path tree to direction of the node \c root
495    /// i.e. it returns the last edge of a shortest path from the node \c root
496    /// to \c node. It is \ref INVALID if \c node is unreachable from the root
497    /// or if \c node=root. The shortest path tree used here is equal to the
498    /// shortest path tree used in \ref predNode().
499    /// \pre \ref run() must be called before using this function.
500    /// \todo predEdge could be a better name.
501    Edge pred(Node root, Node node) const {
502      return (*_pred)(root, node);
503    }
504
505    /// \brief Returns the 'previous node' of the shortest path tree.
506    ///
507    /// For a node \c node it returns the 'previous node' of the shortest path
508    /// tree to direction of the node \c root, i.e. it returns the last but
509    /// one node from a shortest path from the \c root to \c node. It is
510    /// INVALID if \c node is unreachable from the root or if \c node=root.
511    /// The shortest path tree used here is equal to the
512    /// shortest path tree used in \ref pred(). 
513    /// \pre \ref run() must be called before using this function.
514    Node predNode(Node root, Node node) const {
515      return (*_pred)(root, node) == INVALID ?
516      INVALID : graph->source((*_pred)(root, node));
517    }
518   
519    /// \brief Returns a reference to the matrix node map of distances.
520    ///
521    /// Returns a reference to the matrix node map of distances.
522    ///
523    /// \pre \ref run() must be called before using this function.
524    const DistMap &distMap() const { return *_dist;}
525 
526    /// \brief Returns a reference to the shortest path tree map.
527    ///
528    /// Returns a reference to the matrix node map of the edges of the
529    /// shortest path tree.
530    /// \pre \ref run() must be called before using this function.
531    const PredMap &predMap() const { return *_pred;}
532 
533    /// \brief Checks if a node is reachable from the root.
534    ///
535    /// Returns \c true if \c v is reachable from the root.
536    /// \pre \ref run() must be called before using this function.
537    ///
538    bool connected(Node source, Node target) {
539      return (*_dist)(source, target) != OperationTraits::infinity();
540    }
541   
542    ///@}
543  };
544 
545} //END OF NAMESPACE LEMON
546
547#endif
Note: See TracBrowser for help on using the repository browser.