edb14224749f5a5aa051d27063c335fd3ea71ac2
[libdai.git] / include / dai / weightedgraph.h
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
4 *
5 * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
6 */
7
8
9 /** \file
10 * \brief Defines some utility functions for (weighted) undirected graphs, trees and rooted trees.
11 * \todo Improve general support for graphs and trees (in particular, a good tree implementation is needed).
12 */
13
14
15 #ifndef __defined_libdai_weightedgraph_h
16 #define __defined_libdai_weightedgraph_h
17
18
19 #include <vector>
20 #include <map>
21 #include <iostream>
22 #include <set>
23 #include <limits>
24 #include <climits> // Work-around for bug in boost graph library
25 #include <dai/util.h>
26 #include <dai/exceptions.h>
27 #include <dai/graph.h>
28
29 #include <boost/graph/adjacency_list.hpp>
30 #include <boost/graph/prim_minimum_spanning_tree.hpp>
31 #include <boost/graph/kruskal_min_spanning_tree.hpp>
32
33
34 namespace dai {
35
36
37 /// Represents a directed edge
38 class DEdge {
39 public:
40 /// First node index (source of edge)
41 size_t first;
42
43 /// Second node index (target of edge)
44 size_t second;
45
46 /// Default constructor
47 DEdge() : first(0), second(0) {}
48
49 /// Constructs a directed edge pointing from \a m1 to \a m2
50 DEdge( size_t m1, size_t m2 ) : first(m1), second(m2) {}
51
52 /// Tests for equality
53 bool operator==( const DEdge &x ) const { return ((first == x.first) && (second == x.second)); }
54
55 /// Smaller-than operator (performs lexicographical comparison)
56 bool operator<( const DEdge &x ) const {
57 return( (first < x.first) || ((first == x.first) && (second < x.second)) );
58 }
59
60 /// Writes a directed edge to an output stream
61 friend std::ostream & operator << (std::ostream & os, const DEdge & e) {
62 os << "(" << e.first << "->" << e.second << ")";
63 return os;
64 }
65 };
66
67
68 /// Represents an undirected edge
69 class UEdge {
70 public:
71 /// First node index
72 size_t first;
73
74 /// Second node index
75 size_t second;
76
77 /// Default constructor
78 UEdge() : first(0), second(0) {}
79
80 /// Constructs an undirected edge between \a m1 and \a m2
81 UEdge( size_t m1, size_t m2 ) : first(m1), second(m2) {}
82
83 /// Construct from DEdge
84 UEdge( const DEdge &e ) : first(e.first), second(e.second) {}
85
86 /// Tests for inequality (disregarding the ordering of the nodes)
87 bool operator==( const UEdge &x ) {
88 return ((first == x.first) && (second == x.second)) || ((first == x.second) && (second == x.first));
89 }
90
91 /// Smaller-than operator
92 bool operator<( const UEdge &x ) const {
93 size_t s = std::min( first, second );
94 size_t l = std::max( first, second );
95 size_t xs = std::min( x.first, x.second );
96 size_t xl = std::max( x.first, x.second );
97 return( (s < xs) || ((s == xs) && (l < xl)) );
98 }
99
100 /// Writes an undirected edge to an output stream
101 friend std::ostream & operator << (std::ostream & os, const UEdge & e) {
102 if( e.first < e.second )
103 os << "{" << e.first << "--" << e.second << "}";
104 else
105 os << "{" << e.second << "--" << e.first << "}";
106 return os;
107 }
108 };
109
110
111 /// Represents an undirected graph, implemented as a std::set of undirected edges
112 class GraphEL : public std::set<UEdge> {
113 public:
114 /// Default constructor
115 GraphEL() {}
116
117 /// Construct from range of objects that can be cast to UEdge
118 template <class InputIterator>
119 GraphEL( InputIterator begin, InputIterator end ) {
120 insert( begin, end );
121 }
122
123 /// Construct from GraphAL
124 GraphEL( const GraphAL& G ) {
125 for( size_t n1 = 0; n1 < G.nrNodes(); n1++ )
126 foreach( const Neighbor n2, G.nb(n1) )
127 if( n1 < n2 )
128 insert( UEdge( n1, n2 ) );
129 }
130 };
131
132
133 /// Represents an undirected weighted graph, with weights of type \a T, implemented as a std::map mapping undirected edges to weights
134 template<class T> class WeightedGraph : public std::map<UEdge, T> {};
135
136
137 /// Represents a rooted tree, implemented as a vector of directed edges
138 /** By convention, the edges are stored such that they point away from
139 * the root and such that edges nearer to the root come before edges
140 * farther away from the root.
141 */
142 class RootedTree : public std::vector<DEdge> {
143 public:
144 /// Default constructor
145 RootedTree() {}
146
147 /// Constructs a rooted tree from a tree and a root
148 /** \pre T has no cycles and contains node \a Root
149 */
150 RootedTree( const GraphEL &T, size_t Root );
151 };
152
153
154 /// Constructs a minimum spanning tree from the (non-negatively) weighted graph \a G.
155 /** \param G Weighted graph that should have non-negative weights.
156 * \param usePrim If true, use Prim's algorithm (complexity O(E log(V))), otherwise, use Kruskal's algorithm (complexity O(E log(E))).
157 * \note Uses implementation from Boost Graph Library.
158 * \note The vertices of \a G must be in the range [0,N) where N is the number of vertices of \a G.
159 */
160 template<typename T> RootedTree MinSpanningTree( const WeightedGraph<T> &G, bool usePrim ) {
161 RootedTree result;
162 if( G.size() > 0 ) {
163 using namespace boost;
164 using namespace std;
165 typedef adjacency_list< vecS, vecS, undirectedS, no_property, property<edge_weight_t, double> > boostGraph;
166
167 set<size_t> nodes;
168 vector<UEdge> edges;
169 vector<double> weights;
170 edges.reserve( G.size() );
171 weights.reserve( G.size() );
172 for( typename WeightedGraph<T>::const_iterator e = G.begin(); e != G.end(); e++ ) {
173 weights.push_back( e->second );
174 edges.push_back( e->first );
175 nodes.insert( e->first.first );
176 nodes.insert( e->first.second );
177 }
178
179 size_t N = nodes.size();
180 for( set<size_t>::const_iterator it = nodes.begin(); it != nodes.end(); it++ )
181 if( *it >= N )
182 DAI_THROWE(RUNTIME_ERROR,"Vertices must be in range [0..N) where N is the number of vertices.");
183
184 boostGraph g( edges.begin(), edges.end(), weights.begin(), nodes.size() );
185 size_t root = *(nodes.begin());
186 GraphEL tree;
187 if( usePrim ) {
188 // Prim's algorithm
189 vector< graph_traits< boostGraph >::vertex_descriptor > p(N);
190 prim_minimum_spanning_tree( g, &(p[0]) );
191
192 // Store tree edges in result
193 for( size_t i = 0; i != p.size(); i++ ) {
194 if( p[i] != i )
195 tree.insert( UEdge( p[i], i ) );
196 }
197 } else {
198 // Kruskal's algorithm
199 vector< graph_traits< boostGraph >::edge_descriptor > t;
200 t.reserve( N - 1 );
201 kruskal_minimum_spanning_tree( g, std::back_inserter(t) );
202
203 // Store tree edges in result
204 for( size_t i = 0; i != t.size(); i++ ) {
205 size_t v1 = source( t[i], g );
206 size_t v2 = target( t[i], g );
207 if( v1 != v2 )
208 tree.insert( UEdge( v1, v2 ) );
209 }
210 }
211
212 // Direct edges in order to obtain a rooted tree
213 result = RootedTree( tree, root );
214 }
215 return result;
216 }
217
218
219 /// Constructs a minimum spanning tree from the (non-negatively) weighted graph \a G.
220 /** \param G Weighted graph that should have non-negative weights.
221 * \param usePrim If true, use Prim's algorithm (complexity O(E log(V))), otherwise, use Kruskal's algorithm (complexity O(E log(E))).
222 * \note Uses implementation from Boost Graph Library.
223 * \note The vertices of \a G must be in the range [0,N) where N is the number of vertices of \a G.
224 */
225 template<typename T> RootedTree MaxSpanningTree( const WeightedGraph<T> &G, bool usePrim ) {
226 if( G.size() == 0 )
227 return RootedTree();
228 else {
229 T maxweight = G.begin()->second;
230 for( typename WeightedGraph<T>::const_iterator it = G.begin(); it != G.end(); it++ )
231 if( it->second > maxweight )
232 maxweight = it->second;
233 // make a copy of the graph
234 WeightedGraph<T> gr( G );
235 // invoke MinSpanningTree with negative weights
236 // (which have to be shifted to satisfy positivity criterion)
237 for( typename WeightedGraph<T>::iterator it = gr.begin(); it != gr.end(); it++ )
238 it->second = maxweight - it->second;
239 return MinSpanningTree( gr, usePrim );
240 }
241 }
242
243
244 } // end of namespace dai
245
246
247 #endif