graph_blockmodel.cc 33.7 KB
Newer Older
1
2
// graph-tool -- a general graph modification and manipulation thingy
//
Tiago Peixoto's avatar
Tiago Peixoto committed
3
// Copyright (C) 2006-2014 Tiago de Paula Peixoto <tiago@skewed.de>
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
31
32
33
34
35
36
//
// 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 3
// 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, see <http://www.gnu.org/licenses/>.


#define BOOST_PYTHON_MAX_ARITY 30
#include <boost/python.hpp>
#include <cmath>
#include <iostream>

#include "numpy_bind.hh"

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include "graph_filtering.hh"

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

#include "random.hh"

37
#include "config.h"
38
39
40
#include "graph_blockmodel.hh"

using namespace boost;
41
using namespace graph_tool;
42
43
44
45
46

// ====================
// Entropy calculation
// ====================

47
48
49
50
51
52
53
54
55
56
57
58

// Repeated computation of x*log(x) and log(x) actually adds up to a lot of
// time. A significant speedup can be made by caching pre-computed values. This
// is doable since the values of mrse are bounded in [0, 2E], where E is the
// total number of edges in the network. Here we simply grow the cache as
// needed.

vector<double> __safelog_cache;
vector<double> __xlogx_cache;
vector<double> __lgamma_cache;

namespace graph_tool
59
{
60
61
62
63
64
__attribute__((always_inline))
inline double safelog(size_t x)
{
    return __safelog_cache[x];
}
65

66
67
68
69
70
71
72
73
74
void init_safelog(size_t x)
{
    size_t old_size = __safelog_cache.size();
    if (x >= old_size)
    {
        __safelog_cache.resize(x + 1);
        for (size_t i = old_size; i < __safelog_cache.size(); ++i)
            __safelog_cache[i] = safelog(double(i));
    }
75
76
}

77
void clear_safelog()
78
{
79
    vector<double>().swap(__safelog_cache);
80
81
}

82
83

void init_xlogx(size_t x)
84
{
85
86
87
88
89
90
91
    size_t old_size = __xlogx_cache.size();
    if (x >= old_size)
    {
        __xlogx_cache.resize(x + 1);
        for (size_t i = old_size; i < __xlogx_cache.size(); ++i)
            __xlogx_cache[i] = i * safelog(i);
    }
92
93
}

94
95
96
97
void clear_xlogx()
{
    vector<double>().swap(__xlogx_cache);
}
98
99


100
101
__attribute__((always_inline))
inline double xlogx(size_t x)
102
{
103
104
    return __xlogx_cache[x];
}
105

106
107
108
109
110
111
112
113
114
115
void init_lgamma(size_t x)
{
    size_t old_size = __lgamma_cache.size();
    if (x >= old_size)
    {
        __lgamma_cache.resize(x + 1);
        for (size_t i = old_size; i < __lgamma_cache.size(); ++i)
            __lgamma_cache[i] = lgamma(i);
    }
}
116

117
118
119
120
void clear_lgamma()
{
    vector<double>().swap(__lgamma_cache);
}
121

122
123
124
125
126
127
128

__attribute__((always_inline))
inline double lgamma_fast(size_t x)
{
    if (x >= __lgamma_cache.size())
        return lgamma(x);
    return __lgamma_cache[x];
129
130
}

131
132
133
134
}

double do_get_ent(GraphInterface& gi, boost::any omrs, boost::any omrp,
                  boost::any omrm, boost::any owr, bool deg_corr)
135
136
137
138
139
140
141
142
143
144
145
146
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    emap_t mrs = any_cast<emap_t>(omrs);
    vmap_t mrp = any_cast<vmap_t>(omrp);
    vmap_t mrm = any_cast<vmap_t>(omrm);
    vmap_t wr = any_cast<vmap_t>(owr);

147
148
    double S = 0;
    run_action<>()
Tiago Peixoto's avatar
Tiago Peixoto committed
149
150
151
        (gi, std::bind(entropy(), mrs, mrp, mrm, wr, deg_corr,
                       placeholders::_1,
                       std::ref(S)))();
152
    return S;
153
154
}

155
156
double do_get_ent_dense(GraphInterface& gi, boost::any omrs, boost::any owr,
                        bool multigraph)
157
158
159
160
161
162
163
164
165
166
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    emap_t mrs = any_cast<emap_t>(omrs);
    vmap_t wr = any_cast<vmap_t>(owr);

167
168
    double S = 0;
    run_action<>()
Tiago Peixoto's avatar
Tiago Peixoto committed
169
170
        (gi, std::bind(entropy_dense(), mrs, wr, multigraph,
                       placeholders::_1, std::ref(S)))();
171
    return S;
172
173
}

174

175
176
177
178
// ===============================
// Block moves
// ===============================

179
boost::any do_create_emat(GraphInterface& gi)
180
181
{
    boost::any emat;
Tiago Peixoto's avatar
Tiago Peixoto committed
182
183
    run_action<>()(gi, std::bind<void>(create_emat(), placeholders::_1,
                                       std::ref(emat)))();
184
185
186
    return emat;
}

187
188
189
boost::any do_create_ehash(GraphInterface& gi)
{
    boost::any emat;
Tiago Peixoto's avatar
Tiago Peixoto committed
190
191
    run_action<>()(gi, std::bind<void>(create_ehash(), placeholders::_1,
                                       std::ref(emat)))();
192
193
    return emat;
}
194
195
196
197
198

template <class Eprop, class Vprop>
struct remove_vertex_dispatch
{
    remove_vertex_dispatch(Eprop eweight, Vprop vweight,
Tiago Peixoto's avatar
Tiago Peixoto committed
199
                           GraphInterface& bgi)
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        : eweight(eweight), vweight(vweight), bgi(bgi) {}

    Eprop eweight;
    Vprop vweight;
    GraphInterface& bgi;

    template <class Graph>
    void operator()(size_t v, Eprop mrs, Vprop mrp, Vprop mrm,
                    Vprop wr, Vprop b, Graph& g, boost::any& emat) const
    {
        if (is_directed::apply<Graph>::type::value)
        {
            dispatch(v, mrs, mrp, mrm, wr, b, g, emat, bgi.GetGraph());
        }
        else
        {
            UndirectedAdaptor<GraphInterface::multigraph_t> ug(bgi.GetGraph());
            dispatch(v, mrs, mrp, mrm, wr, b, g, emat, ug);
        }
    }

    template <class Graph, class BGraph>
    void dispatch(size_t v, Eprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b,
                  Graph& g, boost::any& aemat, BGraph& bg) const
    {
        typedef typename get_emat_t::apply<BGraph>::type emat_t;
        emat_t& emat = any_cast<emat_t&>(aemat);
        remove_vertex(v, mrs, mrp, mrm, wr, b, eweight, vweight, g, bg, emat);
    }
};



void do_remove_vertex(GraphInterface& gi, GraphInterface& gbi, size_t v,
                      boost::any omrs, boost::any omrp, boost::any omrm,
                      boost::any owr, boost::any ob, boost::any oeweight,
                      boost::any ovweight, boost::any& emat)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    emap_t mrs = any_cast<emap_t>(omrs);
    vmap_t mrp = any_cast<vmap_t>(omrp);
    vmap_t mrm = any_cast<vmap_t>(omrm);
    vmap_t wr = any_cast<vmap_t>(owr);
    vmap_t b = any_cast<vmap_t>(ob);
    emap_t eweight = any_cast<emap_t>(oeweight);
    vmap_t vweight = any_cast<vmap_t>(ovweight);

Tiago Peixoto's avatar
Tiago Peixoto committed
252
253
254
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind(remove_vertex_dispatch<emap_t, vmap_t>(eweight, vweight, gbi),
                       v, mrs, mrp, mrm, wr, b, placeholders::_1, std::ref(emat)))();
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
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
308
309
310
311
312
313
}

template <class Eprop, class Vprop>
struct add_vertex_dispatch
{
    add_vertex_dispatch(Eprop eweight, Vprop vweight,
                        GraphInterface& bgi)
        : eweight(eweight), vweight(vweight), bgi(bgi) {}

    Eprop eweight;
    Vprop vweight;
    GraphInterface& bgi;

    template <class Graph>
    void operator()(pair<size_t, size_t> vr, Eprop mrs, Vprop mrp, Vprop mrm,
                    Vprop wr, Vprop b, Graph& g, boost::any& emat) const
    {
        if (is_directed::apply<Graph>::type::value)
        {
            dispatch(vr.first, vr.second, mrs, mrp, mrm, wr, b, g, emat,
                     bgi.GetGraph());
        }
        else
        {
            UndirectedAdaptor<GraphInterface::multigraph_t> ug(bgi.GetGraph());
            dispatch(vr.first, vr.second, mrs, mrp, mrm, wr, b, g, emat, ug);
        }
    }

    template <class Graph, class BGraph>
    void dispatch(size_t v, size_t r, Eprop mrs, Vprop mrp, Vprop mrm,
                  Vprop wr, Vprop b, Graph& g, boost::any& aemat, BGraph& bg) const
    {
        typedef typename get_emat_t::apply<BGraph>::type emat_t;
        emat_t& emat = any_cast<emat_t&>(aemat);
        add_vertex(v, r, mrs, mrp, mrm, wr, b, eweight, vweight, g, bg, emat);
    }
};


void do_add_vertex(GraphInterface& gi, GraphInterface& gbi, size_t v, size_t r,
                   boost::any omrs, boost::any omrp, boost::any omrm,
                   boost::any owr, boost::any ob, boost::any ovweight,
                   boost::any oeweight, boost::any& emat)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    emap_t mrs = any_cast<emap_t>(omrs);
    vmap_t mrp = any_cast<vmap_t>(omrp);
    vmap_t mrm = any_cast<vmap_t>(omrm);
    vmap_t wr = any_cast<vmap_t>(owr);
    vmap_t b = any_cast<vmap_t>(ob);
    emap_t eweight = any_cast<emap_t>(oeweight);
    vmap_t vweight = any_cast<vmap_t>(ovweight);

Tiago Peixoto's avatar
Tiago Peixoto committed
314
315
316
317
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind<void>(add_vertex_dispatch<emap_t, vmap_t>(eweight, vweight, gbi),
                             make_pair(v, r), mrs, mrp, mrm, wr,
                             b, placeholders::_1, std::ref(emat)))();
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
}


template <class Eprop, class Vprop>
struct move_vertex_dispatch
{
    move_vertex_dispatch(Eprop eweight, Vprop vweight, bool deg_corr, double& S,
                         GraphInterface& bgi)
        : eweight(eweight), vweight(vweight), deg_corr(deg_corr), S(S), bgi(bgi) {}

    Eprop eweight;
    Vprop vweight;
    bool deg_corr;
    double& S;
    GraphInterface& bgi;

    template <class Graph>
    void operator()(pair<size_t, size_t> vnr, Eprop mrs, Vprop mrp, Vprop mrm,
                    Vprop wr, Vprop b, Graph& g, boost::any& emat) const
    {
        if (is_directed::apply<Graph>::type::value)
        {
            dispatch(vnr.first, vnr.second, mrs, mrp, mrm, wr, b, g, emat,
                     bgi.GetGraph());
        }
        else
        {
            UndirectedAdaptor<GraphInterface::multigraph_t> ug(bgi.GetGraph());
            dispatch(vnr.first, vnr.second, mrs, mrp, mrm, wr, b, g, emat,
                     ug);
        }
    }

    template <class Graph, class BGraph>
    void dispatch(size_t v, size_t nr, Eprop mrs, Vprop mrp, Vprop mrm,
                  Vprop wr, Vprop b, Graph& g, boost::any& aemat, BGraph& bg) const
    {
        typedef typename get_emat_t::apply<BGraph>::type emat_t;
        emat_t& emat = any_cast<emat_t&>(aemat);
357
358
359
360
361
362
        size_t B = num_vertices(bg);
        EntrySet<Graph> m_entries(B);
        S = virtual_move(v, nr, mrs, mrp, mrm, wr, b, deg_corr, eweight, vweight,
                         g, bg, emat, m_entries);
        move_vertex(v, nr, mrs, mrp, mrm, wr, b, deg_corr, eweight, vweight,
                    g, bg, emat);
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
    }
};

double do_move_vertex(GraphInterface& gi, GraphInterface& bgi, boost::any& emat,
                      size_t v, size_t nr, boost::any omrs, boost::any omrp,
                      boost::any omrm, boost::any owr, boost::any ob,
                      bool deg_corr, boost::any oeweight, boost::any ovweight)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    emap_t mrs = any_cast<emap_t>(omrs);
    vmap_t mrp = any_cast<vmap_t>(omrp);
    vmap_t mrm = any_cast<vmap_t>(omrm);
    vmap_t wr = any_cast<vmap_t>(owr);
    vmap_t b = any_cast<vmap_t>(ob);
    emap_t eweight = any_cast<emap_t>(oeweight);
    vmap_t vweight = any_cast<vmap_t>(ovweight);

    double S;
Tiago Peixoto's avatar
Tiago Peixoto committed
386
387
388
389
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind(move_vertex_dispatch<emap_t, vmap_t>(eweight, vweight, deg_corr, S, bgi),
                       make_pair(v, nr), mrs, mrp, mrm, wr,
                       b, placeholders::_1, std::ref(emat)))();
390
391
392
393
394
395
396
397
398
399
400
401
402
    return S;
}


//============
// Main loops
//============


template <class Eprop, class Vprop, class VEprop>
struct move_sweep_dispatch
{
    move_sweep_dispatch(Eprop eweight, Vprop vweight, boost::any egroups,
403
404
405
406
                        VEprop esrcpos, VEprop etgtpos, Vprop label,
                        vector<int>& vlist, bool deg_corr, bool dense,
                        bool multigraph, double beta, bool sequential,
                        bool random_move, double c, bool verbose,
407
408
                        size_t max_edge_index, rng_t& rng, double& S,
                        size_t& nmoves, GraphInterface& bgi)
409
410

        : eweight(eweight), vweight(vweight), oegroups(egroups), esrcpos(esrcpos),
411
412
413
414
415
          etgtpos(etgtpos), label(label), vlist(vlist),
          deg_corr(deg_corr), dense(dense), multigraph(multigraph), beta(beta),
          sequential(sequential), random_move(random_move), c(c), verbose(verbose),
          max_edge_index(max_edge_index), rng(rng), S(S),
          nmoves(nmoves), bgi(bgi)
416
417
418
419
420
421
422
423
424
425
426
    {}

    Eprop eweight;
    Vprop vweight;
    boost::any oegroups;
    VEprop esrcpos;
    VEprop etgtpos;
    Vprop label;
    size_t n;
    vector<int>& vlist;
    bool deg_corr;
427
428
    bool dense;
    bool multigraph;
429
430
    double beta;
    bool sequential;
431
    bool random_move;
432
    double c;
433
434
435
436
437
438
439
440
441
    bool verbose;
    size_t max_edge_index;
    rng_t& rng;
    double& S;
    size_t& nmoves;
    GraphInterface& bgi;

    template <class Graph>
    void operator()(Eprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b,
442
443
                    Graph& g, boost::any& emat, boost::any sampler,
                    bool weighted) const
444
445
446
    {
        if (is_directed::apply<Graph>::type::value)
        {
447
448
            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, bgi.GetGraph(),
                     weighted);
449
450
451
452
        }
        else
        {
            UndirectedAdaptor<GraphInterface::multigraph_t> ug(bgi.GetGraph());
453
            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, ug, weighted);
454
455
456
457
458
        }
    }

    template <class Graph, class BGraph>
    void dispatch(Eprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b, Graph& g,
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
                  boost::any& aemat, boost::any asampler, BGraph& bg, bool weighted) const
    {
        if (weighted)
        {
            typedef typename property_map_type::apply<DynamicSampler<std::tuple<typename graph_traits<Graph>::edge_descriptor, bool> >,
                                                      GraphInterface::vertex_index_map_t>::type vemap_t;
            vemap_t egroups = any_cast<vemap_t>(oegroups);
            dispatch(mrs, mrp, mrm, wr, b, g, aemat, asampler, bg, egroups);
        }
        else
        {
            typedef typename property_map_type::apply<vector<std::tuple<typename graph_traits<Graph>::edge_descriptor, bool> >,
                                                      GraphInterface::vertex_index_map_t>::type vemap_t;
            vemap_t egroups = any_cast<vemap_t>(oegroups);
            dispatch(mrs, mrp, mrm, wr, b, g, aemat, asampler, bg, egroups);
        }
    }

    template <class Graph, class BGraph, class Egroups>
    void dispatch(Eprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b, Graph& g,
                  boost::any& aemat, boost::any asampler, BGraph& bg,
                  Egroups egroups) const
481
    {
482
483
484
485
486
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

        size_t B = num_vertices(bg);
        size_t max_BE = is_directed::apply<Graph>::type::value ?
            B * B : (B * (B + 1)) / 2;
487
488


489
490
491
        size_t eidx = random_move ? 1 : max_edge_index;

        typedef typename property_map<Graph, vertex_index_t>::type vindex_map_t;
Tiago Peixoto's avatar
Tiago Peixoto committed
492
        typedef typename property_map_type::apply<Sampler<vertex_t, boost::mpl::false_>,
493
494
495
496
497
498
499
500
501
                                                  vindex_map_t>::type::unchecked_t
            sampler_map_t;
        sampler_map_t sampler = any_cast<sampler_map_t>(asampler);

        try
        {
            typedef typename get_emat_t::apply<BGraph>::type emat_t;
            emat_t& emat = any_cast<emat_t&>(aemat);

502
503
            // make sure the properties are _unchecked_, since otherwise it
            // affects performance
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538

            move_sweep(mrs.get_unchecked(max_BE),
                       mrp.get_unchecked(num_vertices(bg)),
                       mrm.get_unchecked(num_vertices(bg)),
                       wr.get_unchecked(num_vertices(bg)),
                       b.get_unchecked(num_vertices(g)),
                       label.get_unchecked(num_vertices(bg)),
                       vlist, deg_corr, dense, multigraph, beta,
                       eweight.get_unchecked(max_edge_index),
                       vweight.get_unchecked(num_vertices(g)),
                       egroups.get_unchecked(num_vertices(bg)),
                       esrcpos.get_unchecked(eidx),
                       etgtpos.get_unchecked(eidx),
                       g, bg, emat, sampler, sequential, random_move,
                       c, verbose, rng, S, nmoves);
        }
        catch (bad_any_cast&)
        {
            typedef typename get_ehash_t::apply<BGraph>::type emat_t;
            emat_t& emat = any_cast<emat_t&>(aemat);
            move_sweep(mrs.get_unchecked(num_edges(g)),
                       mrp.get_unchecked(num_vertices(bg)),
                       mrm.get_unchecked(num_vertices(bg)),
                       wr.get_unchecked(num_vertices(bg)),
                       b.get_unchecked(num_vertices(g)),
                       label.get_unchecked(num_vertices(bg)),
                       vlist, deg_corr, dense, multigraph, beta,
                       eweight.get_unchecked(max_edge_index),
                       vweight.get_unchecked(num_vertices(g)),
                       egroups.get_unchecked(num_vertices(bg)),
                       esrcpos.get_unchecked(eidx),
                       etgtpos.get_unchecked(eidx),
                       g, bg, emat, sampler, sequential, random_move,
                       c, verbose, rng, S, nmoves);
        }
539
540
541
542
543
    }

};


Tiago Peixoto's avatar
Tiago Peixoto committed
544
545
546
547
548
549
550
551
552
boost::python::object do_move_sweep(GraphInterface& gi, GraphInterface& bgi,
                                    boost::any& emat, boost::any sampler,
                                    boost::any omrs, boost::any omrp, boost::any omrm,
                                    boost::any owr, boost::any ob, boost::any olabel,
                                    vector<int>& vlist, bool deg_corr, bool dense,
                                    bool multigraph, boost::any oeweight,
                                    boost::any ovweight, boost::any oegroups,
                                    boost::any oesrcpos, boost::any oetgtpos,
                                    double beta, bool sequential, bool random_move,
553
554
                                    double c, bool weighted, bool verbose,
                                    rng_t& rng)
555
556
557
558
559
560
561
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
562
    typedef property_map_type::apply<int32_t,
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
                                     GraphInterface::edge_index_map_t>::type
        vemap_t;
    emap_t mrs = any_cast<emap_t>(omrs);
    vmap_t mrp = any_cast<vmap_t>(omrp);
    vmap_t mrm = any_cast<vmap_t>(omrm);
    vmap_t wr = any_cast<vmap_t>(owr);
    vmap_t b = any_cast<vmap_t>(ob);
    vmap_t label = any_cast<vmap_t>(olabel);
    emap_t eweight = any_cast<emap_t>(oeweight);
    vmap_t vweight = any_cast<vmap_t>(ovweight);

    vemap_t esrcpos = any_cast<vemap_t>(oesrcpos);
    vemap_t etgtpos = any_cast<vemap_t>(oetgtpos);

    double S = 0;
    size_t nmoves = 0;
579

Tiago Peixoto's avatar
Tiago Peixoto committed
580
581
582
583
584
585
586
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind(move_sweep_dispatch<emap_t, vmap_t, vemap_t>
                       (eweight, vweight, oegroups, esrcpos, etgtpos,
                        label, vlist, deg_corr, dense, multigraph, beta,
                        sequential, random_move, c, verbose,
                        gi.GetMaxEdgeIndex(), rng, S, nmoves, bgi),
                       mrs, mrp, mrm, wr, b, placeholders::_1,
587
                       std::ref(emat), sampler, weighted))();
Tiago Peixoto's avatar
Tiago Peixoto committed
588
    return boost::python::make_tuple(S, nmoves);
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
}

struct merge_sweep_dispatch
{
    merge_sweep_dispatch(bool deg_corr, bool dense, bool multigraph,
                         size_t nsweeps, size_t nmerges, bool random_moves,
                         bool verbose, size_t max_edge_index, rng_t& rng,
                         double& S, size_t& nmoves)

        : deg_corr(deg_corr), dense(dense), multigraph(multigraph),
          nsweeps(nsweeps), nmerges(nmerges), random_moves(random_moves),
          verbose(verbose), max_edge_index(max_edge_index), rng(rng), S(S),
          nmoves(nmoves)
    {}

    bool deg_corr;
    bool dense;
    bool multigraph;
    size_t nsweeps;
    size_t nmerges;
    bool random_moves;
    bool verbose;
    size_t max_edge_index;
    rng_t& rng;
    double& S;
    size_t& nmoves;

    template <class Graph, class Eprop, class Vprop>
    void operator()(Eprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b,
                    Vprop clabel, Graph& bg, boost::any& aemat,
                    boost::any asampler) const
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

        size_t B = num_vertices(bg);

        typedef typename property_map<Graph, vertex_index_t>::type vindex_map_t;
Tiago Peixoto's avatar
Tiago Peixoto committed
626
        typedef typename property_map_type::apply<Sampler<vertex_t, boost::mpl::false_>,
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
                                                  vindex_map_t>::type::unchecked_t
            sampler_map_t;
        sampler_map_t sampler = any_cast<sampler_map_t>(asampler);

        try
        {
            typedef typename get_emat_t::apply<Graph>::type emat_t;
            emat_t& emat = any_cast<emat_t&>(aemat);
            size_t max_BE = is_directed::apply<Graph>::type::value ?
                B * B : (B * (B + 1)) / 2;

            //make sure the properties are _unchecked_, since otherwise it
            //affects performance

            merge_sweep(mrs.get_unchecked(max_BE),
                        mrp.get_unchecked(num_vertices(bg)),
                        mrm.get_unchecked(num_vertices(bg)),
                        wr.get_unchecked(num_vertices(bg)),
                        b.get_unchecked(num_vertices(bg)),
                        clabel.get_unchecked(num_vertices(bg)),
                        deg_corr, dense, multigraph,
                        bg, emat, sampler, nmerges, nsweeps,
                        random_moves, verbose, rng, S, nmoves);
        }
        catch (bad_any_cast&)
        {
            typedef typename get_ehash_t::apply<Graph>::type emat_t;
            emat_t& emat = any_cast<emat_t&>(aemat);
            merge_sweep(mrs.get_unchecked(max_edge_index),
                        mrp.get_unchecked(num_vertices(bg)),
                        mrm.get_unchecked(num_vertices(bg)),
                        wr.get_unchecked(num_vertices(bg)),
                        b.get_unchecked(num_vertices(bg)),
                        clabel.get_unchecked(num_vertices(bg)),
                        deg_corr, dense, multigraph, bg, emat, sampler,
                        nmerges, nsweeps, random_moves, verbose,
                        rng, S, nmoves);
        }
    }

};


Tiago Peixoto's avatar
Tiago Peixoto committed
670
671
672
673
674
675
676
boost::python::object do_merge_sweep(GraphInterface& bgi, boost::any& emat,
                                     boost::any sampler, boost::any omrs,
                                     boost::any omrp, boost::any omrm, boost::any owr,
                                     boost::any ob, boost::any oclabel, bool deg_corr,
                                     bool dense, bool multigraph, size_t nsweeps,
                                     size_t nmerges, bool random_moves, bool verbose,
                                     rng_t& rng)
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    emap_t mrs = any_cast<emap_t>(omrs);
    vmap_t mrp = any_cast<vmap_t>(omrp);
    vmap_t mrm = any_cast<vmap_t>(omrm);
    vmap_t wr = any_cast<vmap_t>(owr);
    vmap_t b = any_cast<vmap_t>(ob);
    vmap_t clabel = any_cast<vmap_t>(oclabel);

    double S = 0;
    size_t nmoves = 0;

Tiago Peixoto's avatar
Tiago Peixoto committed
694
695
696
697
698
699
700
701
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (bgi, std::bind(merge_sweep_dispatch
                              (deg_corr, dense, multigraph, nsweeps, nmerges,
                               random_moves, verbose,
                               bgi.GetGraph().get_last_index(), rng, S, nmoves),
                        mrs, mrp, mrm, wr, b, clabel, placeholders::_1,
                        std::ref(emat), sampler))();
    return boost::python::make_tuple(S, nmoves);
702
703
}

704
705
706
707
708
709
710
711
712
713
714
715
716
717
718

struct build_egroups
{
    template <class Eprop, class Vprop, class VEprop, class Graph, class VertexIndex>
    void operator()(Vprop b, boost::any& oegroups, VEprop esrcpos,
                    VEprop etgtpos, Eprop eweight, Graph& g,
                    VertexIndex vertex_index, bool weighted, bool empty) const
    {
        if (empty)
            return;
        egroups_manage::build(b, oegroups, esrcpos, etgtpos, eweight, g,
                              vertex_index, weighted);
    }
};

719
720
boost::any do_build_egroups(GraphInterface& gi, GraphInterface& bgi,
                            boost::any ob, boost::any oeweights,
721
                            boost::any oesrcpos, boost::any oetgtpos,
722
                            bool weighted, bool empty)
723
724
725
726
727
728
729
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
730
    typedef property_map_type::apply<int32_t,
731
732
733
734
735
736
737
738
739
                                     GraphInterface::edge_index_map_t>::type
        vemap_t;
    vmap_t b = any_cast<vmap_t>(ob);

    vemap_t esrcpos = any_cast<vemap_t>(oesrcpos);
    vemap_t etgtpos = any_cast<vemap_t>(oetgtpos);
    emap_t eweights = any_cast<emap_t>(oeweights);

    boost::any oegroups;
Tiago Peixoto's avatar
Tiago Peixoto committed
740
741
742
743
744
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind<void>(build_egroups(), b, std::ref(oegroups),
                             esrcpos.get_unchecked(gi.GetMaxEdgeIndex()),
                             etgtpos.get_unchecked(gi.GetMaxEdgeIndex()),
                             eweights.get_unchecked(gi.GetMaxEdgeIndex()),
745
746
                             placeholders::_1, bgi.GetVertexIndex(), weighted,
                             empty))();
747
748
749
    return oegroups;
}

750
751
752
753
754
755
756
757
boost::any do_init_neighbour_sampler(GraphInterface& gi, boost::any oeweights)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    emap_t eweights = any_cast<emap_t>(oeweights);

    boost::any osampler;
Tiago Peixoto's avatar
Tiago Peixoto committed
758
759
760
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind(init_neighbour_sampler(), placeholders::_1, eweights,
                       std::ref(osampler)))();
761
762
763
    return osampler;
}

764
765
766
767
struct collect_edge_marginals_dispatch
{
    template <class Graph, class Vprop, class MEprop>
    void operator()(Graph& g, size_t B, Vprop cb, MEprop p,
Tiago Peixoto's avatar
Tiago Peixoto committed
768
                    std::tuple<boost::any, GraphInterface&> abg) const
769
    {
770
        Graph& bg = *any_cast<Graph*>(get<0>(abg));
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
        collect_edge_marginals(B, cb.get_unchecked(num_vertices(bg)), p, g, bg);
    }
};

void do_collect_edge_marginals(GraphInterface& gi, GraphInterface& gbi,
                               size_t B, boost::any ob, boost::any op)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    vmap_t b = any_cast<vmap_t>(ob);
    emap_t p = any_cast<emap_t>(op);

Tiago Peixoto's avatar
Tiago Peixoto committed
787
788
789
790
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind<void>(collect_edge_marginals_dispatch(),
                             placeholders::_1, B, b, p,
                             std::tuple<boost::any, GraphInterface&>(gbi.GetGraphView(), gbi)))();
791
792
}

Tiago Peixoto's avatar
Tiago Peixoto committed
793
794
boost::python::tuple do_bethe_entropy(GraphInterface& gi, size_t B, boost::any op,
                                      boost::any opv)
795
796
797
798
799
800
801
802
803
804
805
{
    typedef property_map_type::apply<vector<double>,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
    emap_t p = any_cast<emap_t>(op);
    vmap_t pv = any_cast<vmap_t>(opv);

    double H=0, sH=0, Hmf=0, sHmf=0;
Tiago Peixoto's avatar
Tiago Peixoto committed
806
807
808
809
810
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind<void>(bethe_entropy(),
                             placeholders::_1, B, p, pv, std::ref(H), std::ref(sH),
                             std::ref(Hmf), std::ref(sHmf)))();
    return boost::python::make_tuple(H, sH, Hmf, sHmf);
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
}


struct collect_vertex_marginals_dispatch
{
    template <class Graph, class Vprop, class MEprop>
    void operator()(Graph& g, Vprop cb, MEprop p) const
    {
        collect_vertex_marginals(cb.get_unchecked(num_vertices(g)),
                                 p.get_unchecked(num_vertices(g)), g);
    }
};


void do_collect_vertex_marginals(GraphInterface& gi, boost::any ob,
                                 boost::any op)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    vmap_t b = any_cast<vmap_t>(ob);

Tiago Peixoto's avatar
Tiago Peixoto committed
833
834
835
    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind(collect_vertex_marginals_dispatch(),
                       placeholders::_1, b, placeholders::_2),
836
837
838
         vertex_scalar_vector_properties())(op);
}

839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
struct get_deg_entropy
{
    template <class Graph, class Vprop>
    void operator()(Graph& g, Vprop b, size_t B, double& S) const
    {
#ifdef HAVE_SPARSEHASH
        typedef dense_hash_map<pair<size_t,size_t>, int, boost::hash<pair<size_t,size_t>>> map_t;
#else
        typedef unordered_map<pair<size_t,size_t>, int, boost::hash<pair<size_t,size_t>>> map_t;
#endif
        vector<map_t> hist(B);
        vector<int> total(B);

#ifdef HAVE_SPARSEHASH
        for (size_t r = 0; r < B; ++r)
            hist[r].set_empty_key(make_pair(numeric_limits<size_t>::max(),
                                            numeric_limits<size_t>::max()));
#endif

        typename graph_traits<Graph>::vertex_iterator v, v_end;
        for (tie(v, v_end) = vertices(g); v != v_end; ++v)
        {
            hist[b[*v]][make_pair(in_degreeS()(*v, g), out_degree(*v, g))]++;
            total[b[*v]]++;
        }

        S = 0;
        for (size_t r = 0; r < B; ++r)
        {
            for (auto iter = hist[r].begin(); iter != hist[r].end(); ++iter)
            {
                double p = iter->second / double(total[r]);
                S -= p * log(p) * total[r];
            }
        }
    }
};


double do_get_deg_entropy(GraphInterface& gi, boost::any ob, size_t B)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    vmap_t b = any_cast<vmap_t>(ob);

    double S = 0;
    run_action<>()
        (gi, std::bind(get_deg_entropy(),
                       placeholders::_1, b, B, std::ref(S)))();
    return S;
}


893
894
895
896
897
vector<int32_t> get_vector(size_t n)
{
    return vector<int32_t>(n);
}

Tiago Peixoto's avatar
Tiago Peixoto committed
898
void vector_map(boost::python::object ovals, boost::python::object omap)
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
{

    multi_array_ref<int32_t,1> vals = get_array<int32_t,1>(ovals);
    multi_array_ref<int32_t,1> map = get_array<int32_t,1>(omap);

    size_t pos = 0;
    for (size_t i = 0; i < vals.size(); ++i)
    {
        int32_t v = vals[i];
        if (map[v] == -1)
            map[v] = pos++;
        vals[i] = map[v];
    }
}

Tiago Peixoto's avatar
Tiago Peixoto committed
914
void vector_rmap(boost::python::object ovals, boost::python::object omap)
915
916
917
918
919
920
921
922
923
924
925
{

    multi_array_ref<int32_t,1> vals = get_array<int32_t,1>(ovals);
    multi_array_ref<int32_t,1> map = get_array<int32_t,1>(omap);

    for (size_t i = 0; i < vals.size(); ++i)
    {
        map[vals[i]] = i;
    }
}

926
927
928
929
void export_blockmodel()
{
    using namespace boost::python;

930
931
932
933
934
935
936
    def("init_safelog", init_safelog);
    def("clear_safelog", clear_safelog);
    def("init_xlogx", init_xlogx);
    def("clear_xlogx", clear_xlogx);
    def("init_lgamma", init_lgamma);
    def("clear_lgamma", clear_lgamma);

937
    def("get_vector", get_vector);
938
939
    def("vector_map", vector_map);
    def("vector_rmap", vector_rmap);
940
941
942
943
944
945

    def("add_vertex", do_add_vertex);
    def("remove_vertex", do_remove_vertex);
    def("move_vertex", do_move_vertex);

    def("create_emat", do_create_emat);
946
    def("create_ehash", do_create_ehash);
947
    def("build_egroups", do_build_egroups);
948
    def("init_neighbour_sampler", do_init_neighbour_sampler);
949
950

    def("move_sweep", do_move_sweep);
951
    def("merge_sweep", do_merge_sweep);
952
953

    def("entropy", do_get_ent);
954
    def("entropy_dense", do_get_ent_dense);
955
    def("deg_entropy", do_get_deg_entropy);
956
957
958
959
960

    def("edge_marginals", do_collect_edge_marginals);
    def("bethe_entropy", do_bethe_entropy);
    def("vertex_marginals", do_collect_vertex_marginals);
}