graph.cc 17.4 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006  Tiago de Paula Peixoto <tiago@forked.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#include <algorithm>
#include <tr1/unordered_set>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/gursoy_atun_layout.hpp>
#include <boost/graph/fruchterman_reingold.hpp>
#include <boost/graph/random_layout.hpp>
#include <boost/random.hpp>
31
#include <boost/python/make_function.hpp>
Tiago Peixoto's avatar
Tiago Peixoto committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

#include <unistd.h>    /* standard unix functions, like getpid()         */
#include <sys/types.h> /* various type definitions, like pid_t           */
#include <signal.h>    /* signal name macros, and the signal() prototype */

#include "graph.hh"
#include "histogram.hh"
#include "graph_filtering.hh"
#include "graph_selectors.hh"
#include "graph_properties.hh"

using namespace std;
using namespace boost;
using namespace boost::lambda;
using namespace graph_tool;


pair<GraphInterface::degree_t,string> graph_tool::get_degree_type(GraphInterface::deg_t degree)
{
    GraphInterface::degree_t deg;
    string name;
    try 
    {
	deg = boost::get<GraphInterface::degree_t>(degree);
    }
    catch (bad_get)
    {
	name = boost::get<std::string>(degree);
	deg = GraphInterface::SCALAR;
    }
    return make_pair(deg,name);
}


//==============================================================================
// GraphInterface()
//==============================================================================
GraphInterface::GraphInterface()
:_mg(), 
 _reversed(false),
 _directed(true),
 _vertex_index(get(vertex_index,_mg)),
 _edge_index(get(edge_index_t(),_mg)),
 _vertex_range(make_pair(numeric_limits<double>::min(), numeric_limits<double>::max())),
 _edge_range(make_pair(numeric_limits<double>::min(), numeric_limits<double>::max()))
{

}

//==============================================================================
// ~GraphInterface()
//==============================================================================
GraphInterface::~GraphInterface()
{
}

//==============================================================================
// SetVertexFilter()
//==============================================================================

92
93
94
void GraphInterface::SetVertexFilterProperty(string property)
{
    _vertex_filter_property = property;
Tiago Peixoto's avatar
Tiago Peixoto committed
95
    
96
    if (property != "")
Tiago Peixoto's avatar
Tiago Peixoto committed
97
    {
98
	try 
Tiago Peixoto's avatar
Tiago Peixoto committed
99
	{
100
101
102
103
104
105
106
107
108
109
110
111
112
113
	    dynamic_property_map& pmap = find_property_map(_properties, property, typeid(graph_traits<multigraph_t>::vertex_descriptor));

	    if (get_static_property_map<vector_property_map<double,vertex_index_map_t> >(&pmap))
		_vertex_filter_map = get_static_property_map<vector_property_map<double,vertex_index_map_t> >(pmap);
	    else if (get_static_property_map<HashedDescriptorMap<vertex_index_map_t,double> >(&pmap))
		_vertex_filter_map = get_static_property_map<HashedDescriptorMap<vertex_index_map_t,double> >(pmap);
	    else if (get_static_property_map<vector_property_map<size_t,vertex_index_map_t> >(&pmap))
		_vertex_filter_map = get_static_property_map<vector_property_map<size_t,vertex_index_map_t> >(pmap);
	    else if (get_static_property_map<HashedDescriptorMap<vertex_index_map_t,size_t> >(&pmap))
		_vertex_filter_map = get_static_property_map<HashedDescriptorMap<vertex_index_map_t,size_t> >(pmap);
	    else if (get_static_property_map<vertex_index_map_t>(&pmap))
		_vertex_filter_map = get_static_property_map<vertex_index_map_t>(pmap);
	    else 
		_vertex_filter_map = DynamicPropertyMapWrap<double, graph_traits<multigraph_t>::vertex_descriptor>(pmap);
114
115
116
117
118
119
	}
	catch (property_not_found) 
	{
	    throw GraphException("property " + property + " not found");
	}
    }
Tiago Peixoto's avatar
Tiago Peixoto committed
120
121
122
123
124
125
}

bool GraphInterface::IsVertexFilterActive() const { return _vertex_filter_property != "" || _vertex_python_filter != python::object(); }

void GraphInterface::SetEdgeFilterProperty(string property) 
{
126
    _edge_filter_property = property;
Tiago Peixoto's avatar
Tiago Peixoto committed
127
    
128
    if (property != "")
Tiago Peixoto's avatar
Tiago Peixoto committed
129
    {
130
	try
Tiago Peixoto's avatar
Tiago Peixoto committed
131
	{
132
133
134
135
136
137
138
139
140
141
142
143
144
145
	    dynamic_property_map& pmap = find_property_map(_properties, property, typeid(graph_traits<multigraph_t>::edge_descriptor));
	    
	    if (get_static_property_map<vector_property_map<double,edge_index_map_t> >(&pmap))
		_edge_filter_map = get_static_property_map<vector_property_map<double,edge_index_map_t> >(pmap);
	    else if (get_static_property_map<HashedDescriptorMap<edge_index_map_t,double> >(&pmap))
		_edge_filter_map = get_static_property_map<HashedDescriptorMap<edge_index_map_t,double> >(pmap);
	    else if (get_static_property_map<vector_property_map<size_t,edge_index_map_t> >(&pmap))
		_edge_filter_map = get_static_property_map<vector_property_map<size_t,edge_index_map_t> >(pmap);
	    else if (get_static_property_map<HashedDescriptorMap<edge_index_map_t,size_t> >(&pmap))
		_edge_filter_map = get_static_property_map<HashedDescriptorMap<edge_index_map_t,size_t> >(pmap);
	    else if (get_static_property_map<edge_index_map_t>(&pmap))
		_edge_filter_map = get_static_property_map<edge_index_map_t>(pmap);
	    else 
		_edge_filter_map = DynamicPropertyMapWrap<double, graph_traits<multigraph_t>::edge_descriptor>(pmap);
146
147
148
149
150
151
	}
	catch (property_not_found) 
	{
	    throw GraphException("property " + property + " not found");
	}
    }
Tiago Peixoto's avatar
Tiago Peixoto committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
}

bool GraphInterface::IsEdgeFilterActive() const {return _edge_filter_property != "" || _edge_python_filter != python::object();}


//==============================================================================
// GetNumberOfVertices()
//==============================================================================
size_t GraphInterface::GetNumberOfVertices() const
{
    size_t n = 0;
    if (IsVertexFilterActive())
	check_filter(*this,var(n)=bind<size_t>(HardNumVertices(),_1),reverse_check(),directed_check()); 
    else
        check_filter(*this,var(n)=bind<size_t>(SoftNumVertices(),_1),reverse_check(),directed_check());
    return n;
}

//==============================================================================
// GetNumberOfEdges()
//==============================================================================
size_t GraphInterface::GetNumberOfEdges() const
{
    size_t n = 0;
    if (IsEdgeFilterActive() || IsVertexFilterActive())
	check_filter(*this,var(n)=bind<size_t>(HardNumEdges(),_1),reverse_check(),directed_check()); 
    else
        check_filter(*this,var(n)=bind<size_t>(SoftNumEdges(),_1),reverse_check(),directed_check());
    return n;
}

//==============================================================================
184
185
// get_vertex_histogram
// generalized functor to obtain histogram of different types of "degrees"
Tiago Peixoto's avatar
Tiago Peixoto committed
186
187
//==============================================================================
template <class DegreeSelector>
188
struct get_vertex_histogram
Tiago Peixoto's avatar
Tiago Peixoto committed
189
{
190
    get_vertex_histogram(DegreeSelector& deg): _degree(deg) {}
Tiago Peixoto's avatar
Tiago Peixoto committed
191
    template <class Graph, class Hist>
192
    void operator()(const Graph& g, Hist& hist) const
Tiago Peixoto's avatar
Tiago Peixoto committed
193
194
195
196
197
198
199
200
201
    {
	typename graph_traits<Graph>::vertex_iterator v, v_begin, v_end;
        tie(v_begin, v_end) = vertices(g);
        for(v = v_begin; v != v_end; ++v)
            hist[_degree(*v,g)]++;
    }
    DegreeSelector& _degree;
};

202
struct choose_vertex_histogram
Tiago Peixoto's avatar
Tiago Peixoto committed
203
{
204
    choose_vertex_histogram(const GraphInterface& g, GraphInterface::deg_t deg, GraphInterface::hist_t& hist)
Tiago Peixoto's avatar
Tiago Peixoto committed
205
206
207
208
209
210
211
212
213
214
	: _g(g), _hist(hist) 
    {
	tie(_deg, _deg_name) = get_degree_type(deg);
    }
    template <class DegreeSelector>
    void operator()(DegreeSelector)
    {
	if (mpl::at<degree_selector_index,DegreeSelector>::type::value == _deg)
	{
	    DegreeSelector selector(_deg_name, _g);
215
	    check_filter(_g, bind<void>(get_vertex_histogram<DegreeSelector>(selector), _1, var(_hist)),reverse_check(),directed_check());
Tiago Peixoto's avatar
Tiago Peixoto committed
216
217
218
219
220
221
222
223
224
	}
    }
    const GraphInterface &_g;
    GraphInterface::hist_t &_hist;
    GraphInterface::degree_t _deg;
    string _deg_name;    
};

//==============================================================================
225
// GetVertexHistogram(deg_type)
Tiago Peixoto's avatar
Tiago Peixoto committed
226
//==============================================================================
227
GraphInterface::hist_t GraphInterface::GetVertexHistogram(GraphInterface::deg_t deg) const
Tiago Peixoto's avatar
Tiago Peixoto committed
228
229
230
231
{
    hist_t hist;
    try 
    {
232
	mpl::for_each<mpl::vector<in_degreeS, out_degreeS, total_degreeS, scalarS> >(choose_vertex_histogram(*this, deg, hist));
Tiago Peixoto's avatar
Tiago Peixoto committed
233
234
235
236
237
238
239
240
241
    }
    catch (dynamic_get_failure &e)
    {
	throw GraphException("error getting scalar property: " + string(e.what()));
    }

    return hist;
}

242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//==============================================================================
// get_edge_histogram
// generalized functor to obtain histogram of edge properties
//==============================================================================
struct get_edge_histogram
{
    get_edge_histogram(scalarS& prop): _prop(prop) {}
    template <class Graph, class Hist>
    void operator()(const Graph& g, Hist& hist) const
    {
	typename graph_traits<Graph>::edge_iterator e, e_begin, e_end;
        tie(e_begin, e_end) = edges(g);
        for(e = e_begin; e != e_end; ++e)
            hist[_prop(*e,g)]++;
    }
    scalarS& _prop;
};

//==============================================================================
// GetEdgeHistogram(property)
//==============================================================================
GraphInterface::hist_t GraphInterface::GetEdgeHistogram(string property) const
{
    hist_t hist;
    try 
    {
	scalarS prop(property, *this);
	check_filter(*this, bind<void>(get_edge_histogram(prop), _1, var(hist)),reverse_check(),directed_check());
    }
    catch (dynamic_get_failure &e)
    {
	throw GraphException("error getting scalar property: " + string(e.what()));
    }


    return hist;
}

Tiago Peixoto's avatar
Tiago Peixoto committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//==============================================================================
// GetComponentSizeHistogram()
//==============================================================================

struct strong_component
{
    template <class Graph, class ComponentMap>
    void operator()(const Graph &g, ComponentMap comp_map) const
    {
	strong_components(g, comp_map);
    }
};

struct connected_component
{
    template <class Graph, class ComponentMap>
    void operator()(const Graph &g, ComponentMap comp_map) const
    {
	connected_components(g, comp_map);
    }
};

template <class ComponentSelector>
struct get_component_size_histogram
{
    template <class Graph, class IndexMap, class Hist>
    void operator()(const Graph &g, IndexMap index_map, Hist &hist) const
    {   
308
309
	typedef HashedDescriptorMap<IndexMap, size_t> comp_map_t;
	comp_map_t comp_map(index_map);
Tiago Peixoto's avatar
Tiago Peixoto committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389

	_components(g, comp_map);

	tr1::unordered_map<size_t, size_t> comp_count;
	typename graph_traits<Graph>::vertex_iterator v, v_begin, v_end;
	tie(v_begin, v_end) = vertices(g);
	for(v = v_begin; v != v_end; ++v)
	    comp_count[comp_map[*v]]++;
	for(typeof(comp_count.begin()) iter = comp_count.begin(); iter != comp_count.end(); ++iter)
	    hist[iter->second]++;
    }
    ComponentSelector _components;
};

GraphInterface::hist_t GraphInterface::GetComponentSizeHistogram() const
{

    hist_t hist;
    if (_directed)
	check_filter(*this, bind<void>(get_component_size_histogram<strong_component>(), _1, _vertex_index, var(hist)),
		     reverse_check(),always_directed()); 
    else
	check_filter(*this, bind<void>(get_component_size_histogram<connected_component>(), _1, _vertex_index, var(hist)),
		     reverse_check(),always_undirected());
    return hist;
}

//==============================================================================
// InsertEdgeIndexProperty(property)
//==============================================================================
void GraphInterface::InsertEdgeIndexProperty(string property)
{
    _properties.property(property, _edge_index);
}

//==============================================================================
// InsertVertexIndexProperty(property)
//==============================================================================
void GraphInterface::InsertVertexIndexProperty(string property)
{
    _properties.property(property, _vertex_index);
}

//==============================================================================
// ComputeGraphLayoutGursoy(iter, seed)
//==============================================================================

struct compute_gursoy
{
    template <class Graph, class PosMap, class IndexMap>
    void operator()(Graph &g, size_t iter, size_t seed, PosMap pos, IndexMap index_map) const
    {
	mt19937 rng(seed);
	size_t n = HardNumVertices()(g);
	
	vector_property_map<square_topology<mt19937>::point_type, IndexMap> position_map(index_map);
	if (iter == 0)
	    iter = n;
	square_topology<mt19937> topology(rng, n);
	gursoy_atun_layout(g, topology, position_map, iterations(iter).
			   diameter_range(make_pair(sqrt(double(n)), 1.0)).
			   learning_constant_range(make_pair(0.8, 0.2)).
			   vertex_index_map(index_map));
	typename graph_traits<Graph>::vertex_iterator v, v_begin, v_end;
	tie(v_begin, v_end) = vertices(g);
	for(v = v_begin; v != v_end; ++v)
	{
	    pos[*v].x = position_map[*v][0];
	    pos[*v].y = position_map[*v][1];
	}
    }
};

typedef struct { double x; double y; } pos_t;
ostream& operator<<(ostream &o, const pos_t &p ) { o << p.x << "," << p.y; return o;}
istream& operator>>(istream &o, pos_t &p ) { char c; o >> p.x >> c >> p.y; return o;}

void GraphInterface::ComputeGraphLayoutGursoy(size_t iter, size_t seed)
{       
    // vertex postion map
390
391
    typedef HashedDescriptorMap<vertex_index_map_t, pos_t> pos_map_t;
    pos_map_t pos_map(_vertex_index);    
Tiago Peixoto's avatar
Tiago Peixoto committed
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424

    check_filter(*this,bind<void>(compute_gursoy(),_1,iter,seed,var(pos_map),var(_vertex_index)),reverse_check(),directed_check());

    _properties.property("pos", pos_map);
}

//==============================================================================
// ComputeGraphLayoutSpringBlock(iter,seed)
//==============================================================================
struct compute_spring_block
{

    template <class Graph, class PosMap, class IndexMap>
    void operator()(Graph &g, size_t iter, size_t seed, PosMap pos, IndexMap index_map) const
    {
  
	mt19937 rng(seed);
	size_t n = HardNumVertices()(g);

        if (iter == 0)
            iter = 100;
        double radius = n*iter;
        random_graph_layout(g, pos, -radius/2, radius/2, -radius/2, radius/2, rng);
        fruchterman_reingold_force_directed_layout(g, pos, radius, radius, 
                                                   cooling(linear_cooling<double>(iter)).
                                                   vertex_index_map(index_map));
    }
    
};

void GraphInterface::ComputeGraphLayoutSpringBlock(size_t iter, size_t seed)
{
    // vertex postion map
425
426
    typedef HashedDescriptorMap<vertex_index_map_t,pos_t> pos_map_t;
    pos_map_t pos_map(_vertex_index);    
Tiago Peixoto's avatar
Tiago Peixoto committed
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494

    check_filter(*this,bind<void>(compute_spring_block(),_1,iter,seed,var(pos_map),var(_vertex_index)),reverse_check(),directed_check()); 

    _properties.property("pos", pos_map);
}

//==============================================================================
// InitSignalHandling()
//==============================================================================

void catch_sig_stop(int sig_num)
{
    std::cerr << "graph-tool: received signal ";
    switch (sig_num)
    {
    case SIGINT:
        std::cerr << "SIGINT (Interrupt).";
        break;
    case SIGTERM:
        std::cerr << "SIGTERM (Termination).";
        break;
    case SIGQUIT:
        std::cerr << "SIGQUIT (Terminal quit).";
        break;
    case SIGHUP:
        std::cerr << "SIGHUP (Hangup).";
        break;
    case SIGPWR:
        std::cerr << "SIGPWR (Power failure restart).";
        break;
    case SIGSEGV:
        std::cerr << "SIGSEGV (Segmentation fault). There's a bug somewhere in the program. Go fix it.";
        break;
    case SIGBUS:
        std::cerr << "SIGBUS (BUS error). The bus is broken, I guess...";
        break;
    case SIGFPE:
        std::cerr << "SIGFPE (Floating-point exception). INFs and NANs are wreaking havoc.";
        break;
    case SIGILL:
        std::cerr << "SIGILL (Illegal instruction). Did you compile it right?";
        break;
    case SIGXCPU:
        std::cerr << "SIGXCPU (CPU limit exceeded). Time's over.";
        break;
    case SIGXFSZ:
        std::cerr << "SIGXFSZ (File size limit exceeded). The fascist sysadmin doesn't let you write more.";
        break;
    }
    std::cerr << " Bailing out cowardly and calling abort()." << std::endl;
    abort();
}


void GraphInterface::InitSignalHandling()
{
    signal(SIGINT, catch_sig_stop);
    signal(SIGTERM, catch_sig_stop);
    signal(SIGQUIT, catch_sig_stop);
    signal(SIGHUP, catch_sig_stop);
    signal(SIGPWR, catch_sig_stop);
    signal(SIGSEGV, catch_sig_stop);
    signal(SIGBUS, catch_sig_stop);
    signal(SIGFPE, catch_sig_stop);
    signal(SIGILL, catch_sig_stop);
    signal(SIGXCPU, catch_sig_stop);
    signal(SIGXFSZ, catch_sig_stop);
}