Mapselector widget reached its first release, but there are still work to do on it, I know...
2 * lemon/johnson.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
17 #ifndef LEMON_JOHNSON_H
18 #define LEMON_JOHNSON_H
22 /// \brief Johnson algorithm.
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>
38 /// \brief Default OperationTraits for the Johnson algorithm class.
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
47 bool has_infinity = std::numeric_limits<Value>::has_infinity>
48 struct JohnsonDefaultOperationTraits {
49 /// \brief Gives back the zero value of the type.
51 return static_cast<Value>(0);
53 /// \brief Gives back the positive infinity value of the type.
54 static Value infinity() {
55 return std::numeric_limits<Value>::infinity();
57 /// \brief Gives back the sum of the given two elements.
58 static Value plus(const Value& left, const Value& right) {
61 /// \brief Gives back true only if the first value less than the second.
62 static bool less(const Value& left, const Value& right) {
67 template <typename Value>
68 struct JohnsonDefaultOperationTraits<Value, false> {
70 return static_cast<Value>(0);
72 static Value infinity() {
73 return std::numeric_limits<Value>::max();
75 static Value plus(const Value& left, const Value& right) {
76 if (left == infinity() || right == infinity()) return infinity();
79 static bool less(const Value& left, const Value& right) {
84 /// \brief Default traits class of Johnson class.
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.
94 /// \brief The type of the map that stores the edge lengths.
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;
100 // The type of the length of the edges.
101 typedef typename _LengthMap::Value Value;
103 /// \brief Operation traits for belmann-ford algorithm.
105 /// It defines the infinity type on the given Value type
106 /// and the used operation.
107 /// \see JohnsonDefaultOperationTraits
108 typedef JohnsonDefaultOperationTraits<Value> OperationTraits;
110 /// \brief The type of the matrix map that stores the last edges of the
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.
116 typedef DynamicMatrixMap<Graph, typename Graph::Node,
117 typename Graph::Edge> PredMap;
119 /// \brief Instantiates a PredMap.
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);
128 /// \brief The type of the matrix map that stores the dists of the nodes.
130 /// The type of the matrix map that stores the dists of the nodes.
131 /// It must meet the \ref concept::WriteMatrixMap "WriteMatrixMap" concept.
133 typedef DynamicMatrixMap<Graph, typename Graph::Node, Value> DistMap;
135 /// \brief Instantiates a DistMap.
137 /// This function instantiates a \ref DistMap.
138 /// \param G is the graph, to which we would like to define the
140 static DistMap *createDistMap(const _Graph& graph) {
141 return new DistMap(graph);
146 /// \brief Johnson algorithm class.
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
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.
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).
163 /// The type of the length is determined by the
164 /// \ref concept::ReadMap::Value "Value" of the length map.
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
182 /// \author Balazs Dezso
185 template <typename _Graph, typename _LengthMap, typename _Traits>
187 template <typename _Graph=ListGraph,
188 typename _LengthMap=typename _Graph::template EdgeMap<int>,
189 typename _Traits=JohnsonDefaultTraits<_Graph,_LengthMap> >
194 /// \brief \ref Exception for uninitialized parameters.
196 /// This error represents problems in the initialization
197 /// of the parameters of the algorithms.
199 class UninitializedParameter : public lemon::UninitializedParameter {
201 virtual const char* exceptionName() const {
202 return "lemon::Johnson::UninitializedParameter";
206 typedef _Traits Traits;
207 ///The type of the underlying graph.
208 typedef typename _Traits::Graph Graph;
210 typedef typename Graph::Node Node;
211 typedef typename Graph::NodeIt NodeIt;
212 typedef typename Graph::Edge Edge;
213 typedef typename Graph::EdgeIt EdgeIt;
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;
229 /// Pointer to the underlying graph.
231 /// Pointer to the length map
232 const LengthMap *length;
233 ///Pointer to the map of predecessors edges.
235 ///Indicates if \ref _pred is locally allocated (\c true) or not.
237 ///Pointer to the map of distances.
239 ///Indicates if \ref _dist is locally allocated (\c true) or not.
242 /// Creates the maps if necessary.
246 _pred = Traits::createPredMap(*graph);
250 _dist = Traits::createDistMap(*graph);
256 /// \name Named template parameters
261 struct DefPredMapTraits : public Traits {
263 static PredMap *createPredMap(const Graph& graph) {
264 throw UninitializedParameter();
268 /// \brief \ref named-templ-param "Named parameter" for setting PredMap
270 /// \ref named-templ-param "Named parameter" for setting PredMap type
274 : public Johnson< Graph, LengthMap, DefPredMapTraits<T> > {
275 typedef Johnson< Graph, LengthMap, DefPredMapTraits<T> > Create;
279 struct DefDistMapTraits : public Traits {
281 static DistMap *createDistMap(const Graph& graph) {
282 throw UninitializedParameter();
285 /// \brief \ref named-templ-param "Named parameter" for setting DistMap
288 /// \ref named-templ-param "Named parameter" for setting DistMap type
292 : public Johnson< Graph, LengthMap, DefDistMapTraits<T> > {
293 typedef Johnson< Graph, LengthMap, DefDistMapTraits<T> > Create;
297 struct DefOperationTraitsTraits : public Traits {
298 typedef T OperationTraits;
301 /// \brief \ref named-templ-param "Named parameter" for setting
302 /// OperationTraits type
304 /// \ref named-templ-param "Named parameter" for setting
305 /// OperationTraits type
307 struct DefOperationTraits
308 : public Johnson< Graph, LengthMap, DefOperationTraitsTraits<T> > {
309 typedef Johnson< Graph, LengthMap, DefOperationTraitsTraits<T> > Create;
320 /// \brief Constructor.
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) {}
331 if(local_pred) delete _pred;
332 if(local_dist) delete _dist;
335 /// \brief Sets the length map.
337 /// Sets the length map.
338 /// \return \c (*this)
339 Johnson &lengthMap(const LengthMap &m) {
344 /// \brief Sets the map storing the predecessor edges.
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) {
360 /// \brief Sets the map storing the distances calculated by the algorithm.
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) {
376 ///\name Execution control
377 /// The simplest way to execute the algorithm is to use
378 /// one of the member functions called \c run(...).
380 /// If you need more control on the execution,
381 /// Finally \ref start() will perform the actual path
386 /// \brief Initializes the internal data structures.
388 /// Initializes the internal data structures.
393 /// \brief Executes the algorithm.
395 /// This method runs the %Johnson algorithm in order to compute
396 /// the shortest path to each node pairs. The algorithm
398 /// - The shortest path tree for each node.
399 /// - The distance between each node pairs.
401 typedef typename BelmannFord<Graph, LengthMap>::
402 template DefOperationTraits<OperationTraits>::
403 template DefPredMap<NullMap<Node, Edge> >::
404 Create BelmannFordType;
406 BelmannFordType belmannford(*graph, *length);
408 NullMap<Node, Edge> predMap;
410 belmannford.predMap(predMap);
412 belmannford.init(OperationTraits::zero());
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);
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));
429 _dist->set(it, jt, OperationTraits::infinity());
430 _pred->set(it, jt, INVALID);
436 /// \brief Runs %Johnson algorithm.
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.
444 /// \note d.run(s) is just a shortcut of the following code.
456 /// \name Query Functions
457 /// The result of the %Johnson algorithm can be obtained using these
459 /// Before the use of these functions,
460 /// either run() or start() must be called.
464 /// \brief Copies the shortest path to \c t into \c p
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
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.
473 template <typename Path>
474 bool getPath(Path &p, Node source, Node target) {
475 if (connected(source, target)) {
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));
488 /// \brief The distance between two nodes.
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);
498 /// \brief Returns the 'previous edge' of the shortest path tree.
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);
512 /// \brief Returns the 'previous node' of the shortest path tree.
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));
526 /// \brief Returns a reference to the matrix node map of distances.
528 /// Returns a reference to the matrix node map of distances.
530 /// \pre \ref run() must be called before using this function.
531 const DistMap &distMap() const { return *_dist;}
533 /// \brief Returns a reference to the shortest path tree map.
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;}
540 /// \brief Checks if a node is reachable from the root.
542 /// Returns \c true if \c v is reachable from the root.
543 /// \pre \ref run() must be called before using this function.
545 bool connected(Node source, Node target) {
546 return (*_dist)(source, target) != OperationTraits::infinity();
552 } //END OF NAMESPACE LEMON