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