3526ef621926a2f9475127a106b05bd953e487b8
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]
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>
27 namespace dai {
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,
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;
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) {}
108 /// Cast to \c size_t returns \c node member
109 operator size_t () const { return node; }
110 };
112 /// Describes the neighbors of some node.
113 typedef std::vector<Neighbor> Neighbors;
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;
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 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 */
137 template<typename EdgeInputIterator>
138 GraphAL( size_t nr, EdgeInputIterator begin, EdgeInputIterator end ) : _nb() {
139 construct( nr, begin, end );
140 }
141 //@}
143 /// \name Accessors and mutators
144 //@{
145 /// Returns constant reference to the \a _n2 'th neighbor of node \a n1
146 const Neighbor & nb( size_t n1, size_t _n2 ) const {
147 DAI_DEBASSERT( n1 < _nb.size() );
148 DAI_DEBASSERT( _n2 < _nb[n1].size() );
149 return _nb[n1][_n2];
150 }
151 /// Returns reference to the \a _n2 'th neighbor of node \a n1
152 Neighbor & nb( size_t n1, size_t _n2 ) {
153 DAI_DEBASSERT( n1 < _nb.size() );
154 DAI_DEBASSERT( _n2 < _nb[n1].size() );
155 return _nb[n1][_n2];
156 }
158 /// Returns constant reference to all neighbors of node \a n
159 const Neighbors & nb( size_t n ) const {
160 DAI_DEBASSERT( n < _nb.size() );
161 return _nb[n];
162 }
163 /// Returns reference to all neighbors of node \a n
164 Neighbors & nb( size_t n ) {
165 DAI_DEBASSERT( n < _nb.size() );
166 return _nb[n];
167 }
168 //@}
170 /// \name Adding nodes and edges
171 //@{
172 /// (Re)constructs GraphAL from a range of edges.
173 /** \tparam EdgeInputIterator Iterator that iterates over instances of GraphAL::Edge.
174 * \param nr The number of nodes.
175 * \param begin Points to the first edge.
176 * \param end Points just beyond the last edge.
177 */
178 template<typename EdgeInputIterator>
179 void construct( size_t nr, EdgeInputIterator begin, EdgeInputIterator end );
181 /// Adds a node without neighbors and returns the index of the added node.
182 size_t addNode() { _nb.push_back( Neighbors() ); return _nb.size() - 1; }
184 /// Adds a node, with neighbors specified by a range of nodes.
185 /** \tparam NodeInputIterator Iterator that iterates over instances of \c size_t.
186 * \param begin Points to the first index of the nodes that should become neighbors of the added node.
187 * \param end Points just beyond the last index of the nodes that should become neighbors of the added node.
188 * \param sizeHint For improved efficiency, the size of the range may be specified by \a sizeHint.
189 * \returns Index of the added node.
190 */
191 template <typename NodeInputIterator>
192 size_t addNode( NodeInputIterator begin, NodeInputIterator end, size_t sizeHint = 0 ) {
193 Neighbors nbsnew;
194 nbsnew.reserve( sizeHint );
195 size_t iter = 0;
196 for( NodeInputIterator it = begin; it != end; ++it ) {
197 DAI_ASSERT( *it < nrNodes() );
198 Neighbor nb1new( iter, *it, nb(*it).size() );
199 Neighbor nb2new( nb(*it).size(), nrNodes(), iter++ );
200 nbsnew.push_back( nb1new );
201 nb( *it ).push_back( nb2new );
202 }
203 _nb.push_back( nbsnew );
204 return _nb.size() - 1;
205 }
207 /// Adds an edge between node \a n1 and node \a n2.
208 /** If \a check == \c true, only adds the edge if it does not exist already.
209 */
210 void addEdge( size_t n1, size_t n2, bool check = true );
211 //@}
213 /// \name Erasing nodes and edges
214 //@{
215 /// Removes node \a n and all incident edges; indices of other nodes are changed accordingly.
216 void eraseNode( size_t n );
218 /// Removes edge between node \a n1 and node \a n2.
219 void eraseEdge( size_t n1, size_t n2 );
220 //@}
222 /// \name Queries
223 //@{
224 /// Returns number of nodes
225 size_t nrNodes() const { return _nb.size(); }
227 /// Calculates the number of edges, time complexity: O(nrNodes())
228 size_t nrEdges() const {
229 size_t sum = 0;
230 for( size_t i = 0; i < nrNodes(); i++ )
231 sum += nb(i).size();
232 return sum / 2;
233 }
235 /// Returns true if the graph contains an edge between nodes \a n1 and \a n2
236 /** \note The time complexity is linear in the number of neighbors of \a n1
237 */
238 bool hasEdge( size_t n1, size_t n2 ) {
239 for( size_t _n2 = 0; _n2 < nb(n1).size(); _n2++ )
240 if( nb( n1, _n2 ) == n2 )
241 return true;
242 return false;
243 }
245 /// Returns the index of a given node \a n2 amongst the neighbors of \a n1
246 /** \note The time complexity is linear in the number of neighbors of \a n1
247 * \throw OBJECT_NOT_FOUND if \a n2 is not a neighbor of \a n1
248 */
249 size_t findNb( size_t n1, size_t n2 ) {
250 for( size_t _n2 = 0; _n2 < nb(n1).size(); _n2++ )
251 if( nb( n1, _n2 ) == n2 )
252 return _n2;
253 DAI_THROW(OBJECT_NOT_FOUND);
254 return nb(n1).size();
255 }
257 /// Returns true if the graph is connected
258 bool isConnected() const;
260 /// Returns true if the graph is a tree, i.e., if it is singly connected and connected.
261 bool isTree() const;
263 /// Asserts internal consistency
264 void checkConsistency() const;
265 //@}
267 /// \name Input and output
268 //@{
269 /// Writes this GraphAL to an output stream in GraphViz .dot syntax
270 void printDot( std::ostream& os ) const;
271 //@}
272 };
275 template<typename EdgeInputIterator>
276 void GraphAL::construct( size_t nr, EdgeInputIterator begin, EdgeInputIterator end ) {
277 _nb.clear();
278 _nb.resize( nr );
280 for( EdgeInputIterator e = begin; e != end; e++ ) {
281 #ifdef DAI_DEBUG
282 addEdge( e->first, e->second, true );
283 #else
284 addEdge( e->first, e->second, false );
285 #endif
286 }
287 }
290 /// Creates a fully-connected graph with \a N nodes
291 GraphAL createGraphFull( size_t N );
292 /// Creates a two-dimensional rectangular grid of \a N1 by \a N2 nodes, which can be \a periodic
293 GraphAL createGraphGrid( size_t N1, size_t N2, bool periodic );
294 /// Creates a three-dimensional rectangular grid of \a N1 by \a N2 by \a N3 nodes, which can be \a periodic
295 GraphAL createGraphGrid3D( size_t N1, size_t N2, size_t N3, bool periodic );
296 /// Creates a graph consisting of a single loop of \a N nodes
297 GraphAL createGraphLoop( size_t N );
298 /// Creates a random tree-structured graph of \a N nodes
299 GraphAL createGraphTree( size_t N );
300 /// Creates a random regular graph of \a N nodes with uniform connectivity \a d
301 /** Algorithm 1 in [\ref StW99].
302 * Draws a random graph of size \a N and uniform degree \a d
303 * from an almost uniform probability distribution over these graphs
304 * (which becomes uniform in the limit that \a d is small and \a N goes
305 * to infinity).
306 */
307 GraphAL createGraphRegular( size_t N, size_t d );
310 } // end of namespace dai
313 #endif