1 /* This file is part of libDAI - http://www.libdai.org/
2 *
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 */
12 /// \file
13 /// \brief Defines the GraphAL class, which represents an undirected graph as an adjacency list
16 #ifndef __defined_libdai_graph_h
17 #define __defined_libdai_graph_h
20 #include <ostream>
21 #include <vector>
22 #include <algorithm>
23 #include <dai/util.h>
24 #include <dai/exceptions.h>
25 #include <dai/smallset.h>
28 namespace dai {
31 /// Describes the neighbor relationship of two nodes in a graph.
32 /** Most graphs that libDAI deals with are sparse. Therefore,
33 * a fast and memory-efficient way of representing the structure
34 * of a sparse graph is needed. A frequently used operation that
35 * also needs to be fast is switching between viewing node \a a as a
36 * neighbor of node \a b, and node \a b as a neighbor of node \a a.
37 * The Neighbor struct solves both of these problems.
38 *
39 * Most sparse graphs in libDAI are represented by storing for each
40 * node in the graph the set of its neighbors. In practice, this set
41 * of neighbors is stored using the Neighbors type, which is simply a
42 * std::vector<\link Neighbor \endlink>. The Neighbor struct contains
43 * the label of the neighboring node (the \c node member) and
44 * additional information which allows to access a node as a neighbor
45 * of its neighbor (the \c dual member). For convenience, each Neighbor
46 * structure also stores its index in the Neighbors vector that it is
47 * part of (the \c iter member).
48 *
49 * By convention, variable identifiers naming indices into a vector
50 * of neighbors are prefixed with an underscore ("_"). The neighbor list
51 * which they point into is then understood from the context.
52 *
53 * Let us denote the \a _j 'th neighbor of node \a i by <tt>nb(i,_j)</tt>,
54 * which is of the Neighbor type. Here, \a i is the "absolute" index of
55 * node \a i, but \a _j is understood as a "relative" index, giving node
56 * \a j 's entry in the Neighbors <tt>nb(i)</tt> of node \a i. The absolute
57 * index of \a _j, which would be denoted \a j, can be recovered from the
58 * \c node member, <tt>nb(i,_j).node</tt>. The \c iter member
59 * <tt>nb(i,_j).iter</tt> gives the relative index \a _j, and the \c dual
60 * member <tt>nb(i,_j).dual</tt> gives the "dual" relative index, i.e.,
61 * the index of \a i in \a j 's neighbor list.
62 *
63 * Iteration over edges can be easily accomplished:
64 * \code
65 * for( size_t i = 0; i < nrNodes(); ++i ) {
66 * size_t _j = 0;
67 * foreach( const Neighbor &j, nb(i) ) {
68 * assert( j == nb(i,j.iter) );
69 * assert( nb(j.node,j.dual).node == i );
70 * assert( _j = j.iter );
71 * _j++;
72 * }
73 * }
74 * \endcode
75 */
76 struct Neighbor {
77 /// Corresponds to the index of this Neighbor entry in the vector of neighbors
78 size_t iter;
79 /// Contains the absolute index of the neighboring node
80 size_t node;
81 /// Contains the "dual" index (i.e., the index of this node in the Neighbors vector of the neighboring node)
82 size_t dual;
84 /// Default constructor
85 Neighbor() {}
86 /// Constructor that allows setting the values of the member variables
87 Neighbor( size_t iter, size_t node, size_t dual ) : iter(iter), node(node), dual(dual) {}
89 /// Cast to \c size_t returns \c node member
90 operator size_t () const { return node; }
91 };
94 /// Describes the set of neighbors of some node in a graph
95 typedef std::vector<Neighbor> Neighbors;
98 /// Represents an edge in a graph: an Edge(\a i,\a j) corresponds to the edge between node \a i and node \a j.
99 /** \note If the edge is interpreted as a directed edge, then it points from \a i to \a j.
100 * \note If the edge is part of a bipartite graph, \a i is understood to correspond to a node of type 1, and
101 * \a j to a node of type 2.
102 */
103 typedef std::pair<size_t,size_t> Edge;
106 /// Represents the neighborhood structure of nodes in an undirected graph.
107 /** A graph has nodes connected by edges. Nodes are indexed by an unsigned integer.
108 * If there are nrNodes() nodes, they are numbered 0,1,2,...,nrNodes()-1. An edge
109 * between node \a n1 and node \a n2 is represented by a Edge(\a n1,\a n2).
110 *
111 * GraphAL is implemented as a sparse adjacency list, i.e., it stores for each node a list of
112 * its neighboring nodes. The list of neighboring nodes is implemented as a vector of Neighbor
113 * structures (accessible by the nb() method). Thus, each node has an associated variable of
114 * type GraphAL::Neighbors, which is a vector of Neighbor structures, describing its
115 * neighboring nodes.
116 */
117 class GraphAL {
118 private:
119 /// Contains for each node a vector of its neighbors
120 std::vector<Neighbors> _nb;
122 public:
123 /// \name Constructors and destructors
124 //@{
125 /// Default constructor (creates an empty graph).
126 GraphAL() : _nb() {}
128 /// Constructs GraphAL with \a nr nodes and no edges.
129 GraphAL( size_t nr ) : _nb( nr ) {}
131 /// Constructs GraphAL from a range of edges.
132 /** \tparam EdgeInputIterator Iterator that iterates over instances of 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 //@}
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 }
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 //@}
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 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 );
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; }
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 }
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 GraphAL& addEdge( size_t n1, size_t n2, bool check = true );
213 //@}
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 );
220 /// Removes edge between node \a n1 and node \a n2.
221 void eraseEdge( size_t n1, size_t n2 );
222 //@}
224 /// \name Queries
225 //@{
226 /// Returns number of nodes
227 size_t nrNodes() const { return _nb.size(); }
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 }
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 }
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 }
265 /// Returns neighbors of node \a n as a SmallSet<size_t>.
266 SmallSet<size_t> nbSet( size_t n ) const;
268 /// Returns true if the graph is connected
269 bool isConnected() const;
271 /// Returns true if the graph is a tree, i.e., if it is singly connected and connected.
272 bool isTree() const;
274 /// Asserts internal consistency
275 void checkConsistency() const;
277 /// Comparison operator which returns true if two graphs are identical
278 /** \note Two graphs are called identical if they have the same number
279 * of nodes and the same edges (i.e., \a x has an edge between nodes
280 * \a n1 and \a n2 if and only if \c *this has an edge between nodes \a n1 and \a n2).
281 */
282 bool operator==( const GraphAL& x ) const {
283 if( nrNodes() != x.nrNodes() )
284 return false;
285 for( size_t n1 = 0; n1 < nrNodes(); n1++ ) {
286 if( nb(n1).size() != x.nb(n1).size() )
287 return false;
288 foreach( const Neighbor &n2, nb(n1) )
289 if( !x.hasEdge( n1, n2 ) )
290 return false;
291 foreach( const Neighbor &n2, x.nb(n1) )
292 if( !hasEdge( n1, n2 ) )
293 return false;
294 }
295 return true;
296 }
297 //@}
299 /// \name Input and output
300 //@{
301 /// Writes this GraphAL to an output stream in GraphViz .dot syntax
302 void printDot( std::ostream& os ) const;
304 /// Writes this GraphAL to an output stream
305 friend std::ostream& operator<<( std::ostream& os, const GraphAL& g ) {
306 g.printDot( os );
307 return os;
308 }
309 //@}
310 };
313 template<typename EdgeInputIterator>
314 void GraphAL::construct( size_t nr, EdgeInputIterator begin, EdgeInputIterator end, bool check ) {
315 _nb.clear();
316 _nb.resize( nr );
318 for( EdgeInputIterator e = begin; e != end; e++ )
319 addEdge( e->first, e->second, check );
320 }
323 /// Creates a fully-connected graph with \a N nodes
324 GraphAL createGraphFull( size_t N );
325 /// Creates a two-dimensional rectangular grid of \a N1 by \a N2 nodes, which can be \a periodic
326 GraphAL createGraphGrid( size_t N1, size_t N2, bool periodic );
327 /// Creates a three-dimensional rectangular grid of \a N1 by \a N2 by \a N3 nodes, which can be \a periodic
328 GraphAL createGraphGrid3D( size_t N1, size_t N2, size_t N3, bool periodic );
329 /// Creates a graph consisting of a single loop of \a N nodes
330 GraphAL createGraphLoop( size_t N );
331 /// Creates a random tree-structured graph of \a N nodes
332 GraphAL createGraphTree( size_t N );
333 /// Creates a random regular graph of \a N nodes with uniform connectivity \a d
334 /** Algorithm 1 in [\ref StW99].
335 * Draws a random graph of size \a N and uniform degree \a d
336 * from an almost uniform probability distribution over these graphs
337 * (which becomes uniform in the limit that \a d is small and \a N goes
338 * to infinity).
339 */
340 GraphAL createGraphRegular( size_t N, size_t d );
343 } // end of namespace dai
346 #endif