Oops, correct previous partial commit.
[libdai.git] / include / dai / bipgraph.h
1 /* Copyright (C) 2006-2008 Joris Mooij [joris dot mooij at tuebingen dot mpg dot de]
2 Radboud University Nijmegen, The Netherlands /
3 Max Planck Institute for Biological Cybernetics, Germany
4
5 This file is part of libDAI.
6
7 libDAI is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 libDAI is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with libDAI; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22
23 /// \file
24 /// \brief Defines BipartiteGraph class
25 /// \todo Improve documentation of examples_bipgraph
26
27
28 #ifndef __defined_libdai_bipgraph_h
29 #define __defined_libdai_bipgraph_h
30
31
32 #include <ostream>
33 #include <vector>
34 #include <cassert>
35 #include <algorithm>
36 #include <dai/util.h>
37
38
39 namespace dai {
40
41
42 /// Represents the neighborhood structure of nodes in a bipartite graph.
43 /** A bipartite graph has two types of nodes: type 1 and type 2. Edges can occur only between
44 * nodes of different type. Nodes are indexed by an unsigned integer. If there are nr1()
45 * nodes of type 1 and nr2() nodes of type 2, the nodes of type 1 are numbered
46 * 0,1,2,...,nr1()-1 and the nodes of type 2 are numbered 0,1,2,...,nr2()-1. An edge
47 * between node \a n1 of type 1 and node \a n2 of type 2 is represented by a BipartiteGraph::Edge(\a n1,\a n2).
48 *
49 * A BipartiteGraph is implemented as a sparse adjacency list, i.e., it stores for each node a list of
50 * its neighboring nodes. In particular, it stores for each node of type 1 a vector of Neighbor structures
51 * (accessible by the nb1() method) describing the neighboring nodes of type 2; similarly, for each node
52 * of type 2 it stores a vector of Neighbor structures (accessibly by the nb2() method) describing the
53 * neighboring nodes of type 1.
54 * Thus, each node has an associated variable of type BipartiteGraph::Neighbors, which is a vector of
55 * Neighbor structures, describing its neighboring nodes of the other type.
56 */
57 class BipartiteGraph {
58 public:
59 /// Describes a neighboring node of some other node in a BipartiteGraph.
60 /** A Neighbor structure has three members: \a iter, \a node and \a dual. The \a
61 * node member is the most important member: it contains the index of the neighboring node. The \a iter
62 * member is useful for iterating over neighbors, and contains the index of this Neighbor entry in the
63 * corresponding BipartiteGraph::Neighbors variable. The \a dual member is useful to find the dual Neighbor
64 * element: a pair of neighboring nodes can be either specified as a node of type 1 and a neighbor of type
65 * 2, or as a node of type 2 and a neighbor of type 1; the \a dual member contains the index of the dual
66 * Neighbor element (see the example for another explanation of the dual member).
67 */
68 struct Neighbor {
69 /// Corresponds to the index of this Neighbor entry in the vector of neighbors
70 size_t iter;
71 /// Contains the number of the neighboring node
72 size_t node;
73 /// Contains the "dual" iter
74 size_t dual;
75
76 /// Default constructor
77 Neighbor() {}
78 /// Constructor that sets the Neighbor members according to the parameters
79 Neighbor( size_t iter, size_t node, size_t dual ) : iter(iter), node(node), dual(dual) {}
80
81 /// Cast to size_t returns node member
82 operator size_t () const { return node; }
83 };
84
85 /// Describes the neighbors of some node.
86 typedef std::vector<Neighbor> Neighbors;
87
88 /// Represents an edge: an Edge(\a n1,\a n2) corresponds to the edge between node \a n1 of type 1 and node \a n2 of type 2.
89 typedef std::pair<size_t,size_t> Edge;
90
91 private:
92 /// Contains for each node of type 1 a vector of its neighbors
93 std::vector<Neighbors> _nb1;
94
95 /// Contains for each node of type 2 a vector of its neighbors
96 std::vector<Neighbors> _nb2;
97
98 /// Used internally by isTree()
99 struct levelType {
100 std::vector<size_t> ind1; // indices of nodes of type 1
101 std::vector<size_t> ind2; // indices of nodes of type 2
102 };
103
104 public:
105 /// Default constructor (creates an empty bipartite graph)
106 BipartiteGraph() : _nb1(), _nb2() {}
107
108 /// Copy constructor (constructs a bipartite graph containing a copy of \c x)
109 BipartiteGraph( const BipartiteGraph & x ) : _nb1(x._nb1), _nb2(x._nb2) {}
110
111 /// Assignment operator (makes \c *this equal to \c x)
112 BipartiteGraph & operator=( const BipartiteGraph & x ) {
113 if( this != &x ) {
114 _nb1 = x._nb1;
115 _nb2 = x._nb2;
116 }
117 return *this;
118 }
119
120 /// Constructs BipartiteGraph from a range of edges.
121 /** \tparam EdgeInputIterator Iterator that iterates over instances of BipartiteGraph::Edge.
122 * \param nr1 The number of nodes of type 1.
123 * \param nr2 The number of nodes of type 2.
124 * \param begin Points to the first edge.
125 * \param end Points just beyond the last edge.
126 */
127 template<typename EdgeInputIterator>
128 BipartiteGraph( size_t nr1, size_t nr2, EdgeInputIterator begin, EdgeInputIterator end ) : _nb1( nr1 ), _nb2( nr2 ) {
129 construct( nr1, nr2, begin, end );
130 }
131
132 /// (Re)constructs BipartiteGraph from a range of edges.
133 /** \tparam EdgeInputIterator Iterator that iterates over instances of BipartiteGraph::Edge.
134 * \param nr1 The number of nodes of type 1.
135 * \param nr2 The number of nodes of type 2.
136 * \param begin Points to the first edge.
137 * \param end Points just beyond the last edge.
138 */
139 template<typename EdgeInputIterator>
140 void construct( size_t nr1, size_t nr2, EdgeInputIterator begin, EdgeInputIterator end );
141
142 /// Returns constant reference to the _i2'th neighbor of node i1 of type 1
143 const Neighbor & nb1( size_t i1, size_t _i2 ) const {
144 #ifdef DAI_DEBUG
145 assert( i1 < _nb1.size() );
146 assert( _i2 < _nb1[i1].size() );
147 #endif
148 return _nb1[i1][_i2];
149 }
150 /// Returns reference to the _i2'th neighbor of node i1 of type 1
151 Neighbor & nb1( size_t i1, size_t _i2 ) {
152 #ifdef DAI_DEBUG
153 assert( i1 < _nb1.size() );
154 assert( _i2 < _nb1[i1].size() );
155 #endif
156 return _nb1[i1][_i2];
157 }
158
159 /// Returns constant reference to the _i1'th neighbor of node i2 of type 2
160 const Neighbor & nb2( size_t i2, size_t _i1 ) const {
161 #ifdef DAI_DEBUG
162 assert( i2 < _nb2.size() );
163 assert( _i1 < _nb2[i2].size() );
164 #endif
165 return _nb2[i2][_i1];
166 }
167 /// Returns reference to the _i1'th neighbor of node i2 of type 2
168 Neighbor & nb2( size_t i2, size_t _i1 ) {
169 #ifdef DAI_DEBUG
170 assert( i2 < _nb2.size() );
171 assert( _i1 < _nb2[i2].size() );
172 #endif
173 return _nb2[i2][_i1];
174 }
175
176 /// Returns constant reference to all neighbors of node i1 of type 1
177 const Neighbors & nb1( size_t i1 ) const {
178 #ifdef DAI_DEBUG
179 assert( i1 < _nb1.size() );
180 #endif
181 return _nb1[i1];
182 }
183 /// Returns reference to all neighbors of node of i1 type 1
184 Neighbors & nb1( size_t i1 ) {
185 #ifdef DAI_DEBUG
186 assert( i1 < _nb1.size() );
187 #endif
188 return _nb1[i1];
189 }
190
191 /// Returns constant reference to all neighbors of node i2 of type 2
192 const Neighbors & nb2( size_t i2 ) const {
193 #ifdef DAI_DEBUG
194 assert( i2 < _nb2.size() );
195 #endif
196 return _nb2[i2];
197 }
198 /// Returns reference to all neighbors of node i2 of type 2
199 Neighbors & nb2( size_t i2 ) {
200 #ifdef DAI_DEBUG
201 assert( i2 < _nb2.size() );
202 #endif
203 return _nb2[i2];
204 }
205
206 /// Returns number of nodes of type 1
207 size_t nr1() const { return _nb1.size(); }
208 /// Returns number of nodes of type 2
209 size_t nr2() const { return _nb2.size(); }
210
211 /// Calculates the number of edges, time complexity: O(nr1())
212 size_t nrEdges() const {
213 size_t sum = 0;
214 for( size_t i1 = 0; i1 < nr1(); i1++ )
215 sum += nb1(i1).size();
216 return sum;
217 }
218
219 /// Adds a node of type 1 without neighbors.
220 void add1() { _nb1.push_back( Neighbors() ); }
221
222 /// Adds a node of type 2 without neighbors.
223 void add2() { _nb2.push_back( Neighbors() ); }
224
225 /// Adds a node of type 1, with neighbors specified by a range of nodes of type 2.
226 /** \tparam NodeInputIterator Iterator that iterates over instances of size_t.
227 * \param begin Points to the first index of the nodes of type 2 that should become neighbors of the added node.
228 * \param end Points just beyond the last index of the nodes of type 2 that should become neighbors of the added node.
229 * \param sizeHint For improved efficiency, the size of the range may be specified by sizeHint.
230 */
231 template <typename NodeInputIterator>
232 void add1( NodeInputIterator begin, NodeInputIterator end, size_t sizeHint = 0 ) {
233 Neighbors nbs1new;
234 nbs1new.reserve( sizeHint );
235 size_t iter = 0;
236 for( NodeInputIterator it = begin; it != end; ++it ) {
237 assert( *it < nr2() );
238 Neighbor nb1new( iter, *it, nb2(*it).size() );
239 Neighbor nb2new( nb2(*it).size(), nr1(), iter++ );
240 nbs1new.push_back( nb1new );
241 nb2( *it ).push_back( nb2new );
242 }
243 _nb1.push_back( nbs1new );
244 }
245
246 /// Adds a node of type 2, with neighbors specified by a range of nodes of type 1.
247 /** \tparam NodeInputIterator Iterator that iterates over instances of size_t.
248 * \param begin Points to the first index of the nodes of type 1 that should become neighbors of the added node.
249 * \param end Points just beyond the last index of the nodes of type 1 that should become neighbors of the added node.
250 * \param sizeHint For improved efficiency, the size of the range may be specified by sizeHint.
251 */
252 template <typename NodeInputIterator>
253 void add2( NodeInputIterator begin, NodeInputIterator end, size_t sizeHint = 0 ) {
254 Neighbors nbs2new;
255 nbs2new.reserve( sizeHint );
256 size_t iter = 0;
257 for( NodeInputIterator it = begin; it != end; ++it ) {
258 assert( *it < nr1() );
259 Neighbor nb2new( iter, *it, nb1(*it).size() );
260 Neighbor nb1new( nb1(*it).size(), nr2(), iter++ );
261 nbs2new.push_back( nb2new );
262 nb1( *it ).push_back( nb1new );
263 }
264 _nb2.push_back( nbs2new );
265 }
266
267 /// Removes node n1 of type 1 and all incident edges.
268 void erase1( size_t n1 );
269
270 /// Removes node n2 of type 2 and all incident edges.
271 void erase2( size_t n2 );
272
273 /// Adds an edge between node n1 of type 1 and node n2 of type 2.
274 /** If check == true, only adds the edge if it does not exist already.
275 */
276 void addEdge( size_t n1, size_t n2, bool check = true ) {
277 assert( n1 < nr1() );
278 assert( n2 < nr2() );
279 bool exists = false;
280 if( check ) {
281 // Check whether the edge already exists
282 foreach( const Neighbor &nb2, nb1(n1) )
283 if( nb2 == n2 ) {
284 exists = true;
285 break;
286 }
287 }
288 if( !exists ) { // Add edge
289 Neighbor nb_1( _nb1[n1].size(), n2, _nb2[n2].size() );
290 Neighbor nb_2( nb_1.dual, n1, nb_1.iter );
291 _nb1[n1].push_back( nb_1 );
292 _nb2[n2].push_back( nb_2 );
293 }
294 }
295
296 /// Calculates second-order neighbors (i.e., neighbors of neighbors) of node n1 of type 1.
297 /** If include == true, includes n1 itself, otherwise excludes n1.
298 */
299 std::vector<size_t> delta1( size_t n1, bool include = false ) const;
300
301 /// Calculates second-order neighbors (i.e., neighbors of neighbors) of node n2 of type 2.
302 /** If include == true, includes n2 itself, otherwise excludes n2.
303 */
304 std::vector<size_t> delta2( size_t n2, bool include = false ) const;
305
306 /// Returns true if the graph is connected
307 bool isConnected() const;
308
309 /// Returns true if the graph is a tree, i.e., if it is singly connected and connected.
310 bool isTree() const;
311
312 /// Writes this BipartiteGraph to an output stream in GraphViz .dot syntax
313 void printDot( std::ostream& os ) const;
314
315 private:
316 /// Checks internal consistency
317 void check() const;
318 };
319
320
321 template<typename EdgeInputIterator>
322 void BipartiteGraph::construct( size_t nr1, size_t nr2, EdgeInputIterator begin, EdgeInputIterator end ) {
323 _nb1.clear();
324 _nb1.resize( nr1 );
325 _nb2.clear();
326 _nb2.resize( nr2 );
327
328 for( EdgeInputIterator e = begin; e != end; e++ ) {
329 #ifdef DAI_DEBUG
330 addEdge( e->first, e->second, true );
331 #else
332 addEdge( e->first, e->second, false );
333 #endif
334 }
335 }
336
337
338 } // end of namespace dai
339
340
341 /** \example example_bipgraph.cpp
342 * This example deals with the following bipartite graph:
343 * \dot
344 * graph example {
345 * ordering=out;
346 * subgraph cluster_type1 {
347 * node[shape=circle,width=0.4,fixedsize=true,style=filled];
348 * 12 [label="2"];
349 * 11 [label="1"];
350 * 10 [label="0"];
351 * }
352 * subgraph cluster_type2 {
353 * node[shape=polygon,regular=true,sides=4,width=0.4,fixedsize=true,style=filled];
354 * 21 [label="1"];
355 * 20 [label="0"];
356 * }
357 * 10 -- 20;
358 * 11 -- 20;
359 * 12 -- 20;
360 * 11 -- 21;
361 * 12 -- 21;
362 * }
363 * \enddot
364 * It has three nodes of type 1 (drawn as circles) and two nodes of type 2 (drawn as rectangles).
365 * Node 0 of type 1 has only one neighbor (node 0 of type 2), but node 0 of type 2 has three neighbors (nodes 0,1,2 of type 1).
366 * The example code shows how to construct a BipartiteGraph object representing this bipartite graph and
367 * how to iterate over nodes and their neighbors.
368 *
369 * \section Output
370 * \verbinclude examples/example_bipgraph.out
371 *
372 * \section Source
373 */
374
375
376 #endif