Some small fixes
[libdai.git] / include / dai / graph.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 the GraphAL class, which represents an undirected graph as an adjacency list
14
15
16 #ifndef __defined_libdai_graph_h
17 #define __defined_libdai_graph_h
18
19
20 #include <ostream>
21 #include <vector>
22 #include <algorithm>
23 #include <dai/util.h>
24 #include <dai/exceptions.h>
25
26
27 namespace dai {
28
29
30 /// Represents the neighborhood structure of nodes in an undirected graph.
31 /** A graph has nodes connected by edges. Nodes are indexed by an unsigned integer.
32 * If there are nrNodes() nodes, they are numbered 0,1,2,...,nrNodes()-1. An edge
33 * between node \a n1 and node \a n2 is represented by a GraphAL::Edge(\a n1,\a n2).
34 *
35 * GraphAL is implemented as a sparse adjacency list, i.e., it stores for each node a list of
36 * its neighboring nodes. The list of neighboring nodes is implemented as a vector of Neighbor
37 * structures (accessible by the nb() method). Thus, each node has an associated variable of
38 * type GraphAL::Neighbors, which is a vector of Neighbor structures, describing its
39 * neighboring nodes.
40 */
41 class GraphAL {
42 public:
43 /// Describes the neighbor relationship of two nodes in a GraphAL.
44 /** Sometimes we want to do an action, such as sending a
45 * message, for all edges in a graph. However, most graphs
46 * will be sparse, so we need some way of storing a set of
47 * the neighbors of a node, which is both fast and
48 * memory-efficient. We also need to be able to go between
49 * viewing node \a a as a neighbor of node \a b, and node \a b
50 * as a neighbor of node \a a. The Neighbor struct solves
51 * both of these problems. Each node has a list of neighbors,
52 * stored as a std::vector<\link Neighbor \endlink>, and
53 * extra information is included in the Neighbor struct which
54 * allows us to access a node as a neighbor of its neighbor
55 * (the \c dual member).
56 *
57 * By convention, variable identifiers naming indices into a
58 * vector of neighbors are prefixed with an underscore ("_").
59 * The neighbor list which they point into is then understood
60 * from context. For example:
61 *
62 * \code
63 * Real MR::T( size_t i, size_t _j );
64 * \endcode
65 *
66 * Here, \a i is the "absolute" index of node i, but \a _j is
67 * understood as a "relative" index, giving node \a j 's entry in
68 * <tt>nb(i)</tt>. The corresponding Neighbor structure can be
69 * accessed as <tt>nb(i,_j)</tt> or <tt>nb(i)[_j]</tt>. The
70 * absolute index of \a _j, which would be called \a j, can be
71 * recovered from the \c node member: <tt>nb(i,_j).node</tt>.
72 * The \c iter member gives the relative index \a _j, and the
73 * \c dual member gives the "dual" relative index, i.e., the
74 * index of \a i in \a j 's neighbor list.
75 *
76 * \code
77 * Neighbor n = nb(i,_j);
78 * n.node == j &&
79 * n.iter == _j &&
80 * nb(n.node,n.dual).node == i
81 * \endcode
82 *
83 * There is no easy way to transform a pair of absolute node
84 * indices \a i and \a j into a Neighbor structure relative
85 * to one of the nodes. Such a feature has never yet been
86 * found to be necessary. Iteration over edges can always be
87 * accomplished using the Neighbor lists, and by writing
88 * functions that accept relative indices:
89 * \code
90 * for( size_t i = 0; i < nrNodes(); ++i )
91 * foreach( const Neighbor &j, nb(i) )
92 * T( i, j.iter );
93 * \endcode
94 */
95 struct Neighbor {
96 /// Corresponds to the index of this Neighbor entry in the vector of neighbors
97 size_t iter;
98 /// Contains the number of the neighboring node
99 size_t node;
100 /// Contains the "dual" iter
101 size_t dual;
102
103 /// Default constructor
104 Neighbor() {}
105 /// Constructor that sets the Neighbor members according to the parameters
106 Neighbor( size_t iter, size_t node, size_t dual ) : iter(iter), node(node), dual(dual) {}
107
108 /// Cast to \c size_t returns \c node member
109 operator size_t () const { return node; }
110 };
111
112 /// Describes the neighbors of some node.
113 typedef std::vector<Neighbor> Neighbors;
114
115 /// Represents an edge: an Edge(\a n1,\a n2) corresponds to the edge between node \a n1 and node \a n2.
116 typedef std::pair<size_t,size_t> Edge;
117
118 private:
119 /// Contains for each node a vector of its neighbors
120 std::vector<Neighbors> _nb;
121
122 public:
123 /// \name Constructors and destructors
124 //@{
125 /// Default constructor (creates an empty graph).
126 GraphAL() : _nb() {}
127
128 /// Constructs GraphAL with \a nr nodes and no edges.
129 GraphAL( size_t nr ) : _nb( nr ) {}
130
131 /// Constructs GraphAL from a range of edges.
132 /** \tparam EdgeInputIterator Iterator that iterates over instances of GraphAL::Edge.
133 * \param nr The number of nodes.
134 * \param begin Points to the first edge.
135 * \param end Points just beyond the last edge.
136 * \param check Whether to only add an edge if it does not exist already.
137 */
138 template<typename EdgeInputIterator>
139 GraphAL( size_t nr, EdgeInputIterator begin, EdgeInputIterator end, bool check=true ) : _nb() {
140 construct( nr, begin, end, check );
141 }
142 //@}
143
144 /// \name Accessors and mutators
145 //@{
146 /// Returns constant reference to the \a _n2 'th neighbor of node \a n1
147 const Neighbor & nb( size_t n1, size_t _n2 ) const {
148 DAI_DEBASSERT( n1 < _nb.size() );
149 DAI_DEBASSERT( _n2 < _nb[n1].size() );
150 return _nb[n1][_n2];
151 }
152 /// Returns reference to the \a _n2 'th neighbor of node \a n1
153 Neighbor & nb( size_t n1, size_t _n2 ) {
154 DAI_DEBASSERT( n1 < _nb.size() );
155 DAI_DEBASSERT( _n2 < _nb[n1].size() );
156 return _nb[n1][_n2];
157 }
158
159 /// Returns constant reference to all neighbors of node \a n
160 const Neighbors & nb( size_t n ) const {
161 DAI_DEBASSERT( n < _nb.size() );
162 return _nb[n];
163 }
164 /// Returns reference to all neighbors of node \a n
165 Neighbors & nb( size_t n ) {
166 DAI_DEBASSERT( n < _nb.size() );
167 return _nb[n];
168 }
169 //@}
170
171 /// \name Adding nodes and edges
172 //@{
173 /// (Re)constructs GraphAL from a range of edges.
174 /** \tparam EdgeInputIterator Iterator that iterates over instances of GraphAL::Edge.
175 * \param nr The number of nodes.
176 * \param begin Points to the first edge.
177 * \param end Points just beyond the last edge.
178 * \param check Whether to only add an edge if it does not exist already.
179 */
180 template<typename EdgeInputIterator>
181 void construct( size_t nr, EdgeInputIterator begin, EdgeInputIterator end, bool check=true );
182
183 /// Adds a node without neighbors and returns the index of the added node.
184 size_t addNode() { _nb.push_back( Neighbors() ); return _nb.size() - 1; }
185
186 /// Adds a node, with neighbors specified by a range of nodes.
187 /** \tparam NodeInputIterator Iterator that iterates over instances of \c size_t.
188 * \param begin Points to the first index of the nodes that should become neighbors of the added node.
189 * \param end Points just beyond the last index of the nodes that should become neighbors of the added node.
190 * \param sizeHint For improved efficiency, the size of the range may be specified by \a sizeHint.
191 * \returns Index of the added node.
192 */
193 template <typename NodeInputIterator>
194 size_t addNode( NodeInputIterator begin, NodeInputIterator end, size_t sizeHint = 0 ) {
195 Neighbors nbsnew;
196 nbsnew.reserve( sizeHint );
197 size_t iter = 0;
198 for( NodeInputIterator it = begin; it != end; ++it ) {
199 DAI_ASSERT( *it < nrNodes() );
200 Neighbor nb1new( iter, *it, nb(*it).size() );
201 Neighbor nb2new( nb(*it).size(), nrNodes(), iter++ );
202 nbsnew.push_back( nb1new );
203 nb( *it ).push_back( nb2new );
204 }
205 _nb.push_back( nbsnew );
206 return _nb.size() - 1;
207 }
208
209 /// Adds an edge between node \a n1 and node \a n2.
210 /** If \a check == \c true, only adds the edge if it does not exist already.
211 */
212 void addEdge( size_t n1, size_t n2, bool check = true );
213 //@}
214
215 /// \name Erasing nodes and edges
216 //@{
217 /// Removes node \a n and all incident edges; indices of other nodes are changed accordingly.
218 void eraseNode( size_t n );
219
220 /// Removes edge between node \a n1 and node \a n2.
221 void eraseEdge( size_t n1, size_t n2 );
222 //@}
223
224 /// \name Queries
225 //@{
226 /// Returns number of nodes
227 size_t nrNodes() const { return _nb.size(); }
228
229 /// Calculates the number of edges, time complexity: O(nrNodes())
230 size_t nrEdges() const {
231 size_t sum = 0;
232 for( size_t i = 0; i < nrNodes(); i++ )
233 sum += nb(i).size();
234 return sum / 2;
235 }
236
237 /// Returns true if the graph contains an edge between nodes \a n1 and \a n2
238 /** \note The time complexity is linear in the number of neighbors of \a n1 or \a n2
239 */
240 bool hasEdge( size_t n1, size_t n2 ) const {
241 if( nb(n1).size() < nb(n2).size() ) {
242 for( size_t _n2 = 0; _n2 < nb(n1).size(); _n2++ )
243 if( nb( n1, _n2 ) == n2 )
244 return true;
245 } else {
246 for( size_t _n1 = 0; _n1 < nb(n2).size(); _n1++ )
247 if( nb( n2, _n1 ) == n1 )
248 return true;
249 }
250 return false;
251 }
252
253 /// Returns the index of a given node \a n2 amongst the neighbors of \a n1
254 /** \note The time complexity is linear in the number of neighbors of \a n1
255 * \throw OBJECT_NOT_FOUND if \a n2 is not a neighbor of \a n1
256 */
257 size_t findNb( size_t n1, size_t n2 ) {
258 for( size_t _n2 = 0; _n2 < nb(n1).size(); _n2++ )
259 if( nb( n1, _n2 ) == n2 )
260 return _n2;
261 DAI_THROW(OBJECT_NOT_FOUND);
262 return nb(n1).size();
263 }
264
265 /// Returns true if the graph is connected
266 bool isConnected() const;
267
268 /// Returns true if the graph is a tree, i.e., if it is singly connected and connected.
269 bool isTree() const;
270
271 /// Asserts internal consistency
272 void checkConsistency() const;
273
274 /// Comparison operator which returns true if two graphs are identical
275 /** \note Two graphs are called identical if they have the same number
276 * of nodes and the same edges (i.e., \a x has an edge between nodes
277 * n1 and n2 if and only if \c *this has an edge between nodes n1 and n2).
278 */
279 bool operator==( const GraphAL& x ) const {
280 if( nrNodes() != x.nrNodes() )
281 return false;
282 for( size_t n1 = 0; n1 < nrNodes(); n1++ ) {
283 if( nb(n1).size() != x.nb(n1).size() )
284 return false;
285 foreach( const Neighbor &n2, nb(n1) )
286 if( !x.hasEdge( n1, n2 ) )
287 return false;
288 foreach( const Neighbor &n2, x.nb(n1) )
289 if( !hasEdge( n1, n2 ) )
290 return false;
291 }
292 return true;
293 }
294 //@}
295
296 /// \name Input and output
297 //@{
298 /// Writes this GraphAL to an output stream in GraphViz .dot syntax
299 void printDot( std::ostream& os ) const;
300
301 /// Writes this GraphAL to an output stream
302 friend std::ostream& operator<<( std::ostream& os, const GraphAL& g ) {
303 g.printDot( os );
304 return os;
305 }
306 //@}
307 };
308
309
310 template<typename EdgeInputIterator>
311 void GraphAL::construct( size_t nr, EdgeInputIterator begin, EdgeInputIterator end, bool check ) {
312 _nb.clear();
313 _nb.resize( nr );
314
315 for( EdgeInputIterator e = begin; e != end; e++ )
316 addEdge( e->first, e->second, check );
317 }
318
319
320 /// Creates a fully-connected graph with \a N nodes
321 GraphAL createGraphFull( size_t N );
322 /// Creates a two-dimensional rectangular grid of \a N1 by \a N2 nodes, which can be \a periodic
323 GraphAL createGraphGrid( size_t N1, size_t N2, bool periodic );
324 /// Creates a three-dimensional rectangular grid of \a N1 by \a N2 by \a N3 nodes, which can be \a periodic
325 GraphAL createGraphGrid3D( size_t N1, size_t N2, size_t N3, bool periodic );
326 /// Creates a graph consisting of a single loop of \a N nodes
327 GraphAL createGraphLoop( size_t N );
328 /// Creates a random tree-structured graph of \a N nodes
329 GraphAL createGraphTree( size_t N );
330 /// Creates a random regular graph of \a N nodes with uniform connectivity \a d
331 /** Algorithm 1 in [\ref StW99].
332 * Draws a random graph of size \a N and uniform degree \a d
333 * from an almost uniform probability distribution over these graphs
334 * (which becomes uniform in the limit that \a d is small and \a N goes
335 * to infinity).
336 */
337 GraphAL createGraphRegular( size_t N, size_t d );
338
339
340 } // end of namespace dai
341
342
343 #endif