graph_blockmodel_overlap.cc 33.8 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-2015 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
//
// 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 40
#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"
34
#include "graph_util.hh"
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

#include "random.hh"

#include "config.h"
#include "graph_blockmodel.hh"
#include "graph_blockmodel_overlap.hh"


using namespace boost;
using namespace graph_tool;

namespace graph_tool
{
template <class Eprop, class Vprop, class VEprop>
struct move_sweep_overlap_dispatch
{
    move_sweep_overlap_dispatch(Eprop eweight, Vprop vweight,
                                boost::any egroups, VEprop esrcpos,
53
54
                                VEprop etgtpos, Vprop label,
                                vector<int64_t>& vlist,
55
                                vector<int64_t>& block_list,
56
                                vector<int64_t>& target_blocks,
57
58
59
60
                                bool deg_corr, bool dense, bool multigraph,
                                bool parallel_edges, double beta,
                                bool sequential, bool parallel,
                                bool random_move, double c, bool node_coherent,
61
                                bool verbose, size_t edge_index_range,
62
                                size_t nmerges, size_t niter, Vprop merge_map,
63
64
65
66
67
68
                                overlap_stats_t& overlap_stats,
                                overlap_partition_stats_t& partition_stats,
                                rng_t& rng, double& S, size_t& nmoves,
                                GraphInterface& bgi)

        : eweight(eweight), vweight(vweight), oegroups(egroups), esrcpos(esrcpos),
69
70
71
72
73
          etgtpos(etgtpos), label(label), vlist(vlist), block_list(block_list),
          target_blocks(target_blocks), deg_corr(deg_corr), dense(dense),
          multigraph(multigraph), parallel_edges(parallel_edges), beta(beta),
          sequential(sequential), parallel(parallel), random_move(random_move),
          c(c), node_coherent(node_coherent), verbose(verbose),
74
          edge_index_range(edge_index_range), nmerges(nmerges),
75
          niter(niter), merge_map(merge_map), overlap_stats(overlap_stats),
76
77
78
79
80
81
82
83
84
85
          partition_stats(partition_stats), rng(rng), S(S), nmoves(nmoves), bgi(bgi)
    {}

    Eprop eweight;
    Vprop vweight;
    boost::any oegroups;
    VEprop esrcpos;
    VEprop etgtpos;
    Vprop label;
    size_t n;
86
    vector<int64_t>& vlist;
87
    vector<int64_t>& block_list;
88
    vector<int64_t>& target_blocks;
89
90
91
92
93
94
95
96
97
98
99
    bool deg_corr;
    bool dense;
    bool multigraph;
    bool parallel_edges;
    double beta;
    bool sequential;
    bool parallel;
    bool random_move;
    double c;
    bool node_coherent;
    bool verbose;
100
    size_t edge_index_range;
101
    size_t nmerges;
102
    size_t niter;
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    Vprop merge_map;
    overlap_stats_t& overlap_stats;
    overlap_partition_stats_t& partition_stats;
    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,
                    Graph& g, boost::any& emat, boost::any sampler,
                    boost::any cavity_sampler, bool weighted) const
    {
        if (is_directed::apply<Graph>::type::value)
        {
            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, cavity_sampler,
119
                     bgi.get_graph(), weighted);
120
121
122
        }
        else
        {
123
            UndirectedAdaptor<GraphInterface::multigraph_t> ug(bgi.get_graph());
124
125
126
127
128
129
            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, cavity_sampler, ug,
                     weighted);
        }
    }

    template <class Graph, class BGraph>
130
131
132
    void dispatch(Eprop& mrs, Vprop& mrp, Vprop& mrm, Vprop& wr, Vprop& b,
                  Graph& g, boost::any& aemat, boost::any asampler,
                  boost::any& cavity_sampler, BGraph& bg, bool weighted) const
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
    {
        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, cavity_sampler,
                     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, cavity_sampler,
                     bg, egroups);
        }
    }

    template <class Graph, class BGraph, class Egroups>
153
154
155
    void dispatch(Eprop& mrs, Vprop& mrp, Vprop& mrm, Vprop& wr, Vprop& b,
                  Graph& g, boost::any& aemat, boost::any& asampler,
                  boost::any& acavity_sampler, BGraph& bg, Egroups& egroups) const
156
    {
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
        try
        {
            typedef typename get_emat_t::apply<BGraph>::type emat_t;
            emat_t& emat = any_cast<emat_t&>(aemat);
            size_t B = num_vertices(bg);
            size_t max_BE = is_directed::apply<Graph>::type::value ?
                B * B : (B * (B + 1)) / 2;
            dispatch(mrs.get_unchecked(max_BE), mrp, mrm, wr, b, g,
                     asampler, acavity_sampler, bg, egroups, emat);
        }
        catch (bad_any_cast&)
        {
            typedef typename get_ehash_t::apply<BGraph>::type emat_t;
            emat_t& emat = any_cast<emat_t&>(aemat);
            dispatch(mrs, mrp, mrm, wr, b, g, asampler, acavity_sampler,
                     bg, egroups, emat);
        }
    }
175

176
177
178
179
180
181
    template <class Graph, class BGraph, class Egroups, class Emat, class MEprop>
    void dispatch(MEprop mrs, Vprop& mrp, Vprop& mrm, Vprop& wr, Vprop& b,
                  Graph& g, boost::any& asampler, boost::any& acavity_sampler,
                  BGraph& bg, Egroups& egroups, Emat& emat) const
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
182

183
        size_t eidx = random_move ? 1 : edge_index_range;
184
185
186
187
188
189
190
191

        typedef typename property_map<Graph, vertex_index_t>::type vindex_map_t;
        typedef typename property_map_type::apply<Sampler<vertex_t, boost::mpl::false_>,
                                                  vindex_map_t>::type::unchecked_t
            sampler_map_t;
        sampler_map_t sampler = any_cast<sampler_map_t>(asampler);
        sampler_map_t cavity_sampler = any_cast<sampler_map_t>(acavity_sampler);

192
        ConstantPropertyMap<int, typename graph_traits<Graph>::edge_descriptor> ce(0);
193
194
        ConstantPropertyMap<std::array<int, 1>, typename graph_traits<Graph>::vertex_descriptor>
            cv(std::array<int, 1>({{-1}}));
195
196
197
198
199
        IdentityArrayPropertyMap<typename graph_traits<Graph>::vertex_descriptor> vmap;
        boost::typed_identity_property_map<int> identity;

        vector<size_t> free_blocks;
        auto state = make_block_state(g,
200
                                      eweight.get_unchecked(edge_index_range),
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
                                      vweight.get_unchecked(num_vertices(g)),
                                      b.get_unchecked(num_vertices(g)),
                                      bg, emat, mrs,
                                      mrp.get_unchecked(num_vertices(bg)),
                                      mrm.get_unchecked(num_vertices(bg)),
                                      wr.get_unchecked(num_vertices(bg)),
                                      egroups.get_unchecked(num_vertices(bg)),
                                      esrcpos.get_unchecked(eidx),
                                      etgtpos.get_unchecked(eidx),
                                      sampler, cavity_sampler,
                                      partition_stats, overlap_stats,
                                      identity, identity, free_blocks,
                                      false, false, true);

        vector<decltype(state)> states = {state};
        vector<SingleEntrySet<Graph>> m_entries(1);

218
        if (target_blocks.empty())
219
        {
220
            if (nmerges == 0)
221
            {
222
223
224
225
226
227
                if (!node_coherent)
                {
                    move_sweep_overlap(states, m_entries, overlap_stats,
                                       wr.get_unchecked(num_vertices(bg)),
                                       b.get_unchecked(num_vertices(g)), cv,
                                       vmap, label.get_unchecked(num_vertices(bg)),
228
229
                                       vlist, block_list, deg_corr, dense,
                                       multigraph, beta,
230
231
232
233
234
235
236
237
238
239
240
                                       vweight.get_unchecked(num_vertices(g)), g,
                                       sequential, parallel, random_move, c, niter,
                                       num_vertices(bg), verbose, rng, S, nmoves);
                }
                else
                {
                    vector<EntrySet<Graph>> m_entries(1, EntrySet<Graph>(num_vertices(bg)));
                    coherent_move_sweep_overlap(states, m_entries, overlap_stats,
                                                wr.get_unchecked(num_vertices(bg)),
                                                b.get_unchecked(num_vertices(g)), cv,
                                                vmap, label.get_unchecked(num_vertices(bg)),
241
242
                                                vlist, block_list, deg_corr,
                                                dense, multigraph, beta,
243
244
245
246
247
                                                vweight.get_unchecked(num_vertices(g)), g,
                                                sequential,  random_move, c,
                                                false, niter,
                                                num_vertices(bg), rng, S, nmoves);
                }
248
249
250
            }
            else
            {
251
252
                merge_sweep_overlap(states, m_entries, overlap_stats,
                                    wr.get_unchecked(num_vertices(bg)),
253
254
255
256
257
258
                                    b.get_unchecked(num_vertices(g)), ce, cv,
                                    vmap,
                                    label.get_unchecked(num_vertices(bg)),
                                    vlist, block_list, deg_corr, dense,
                                    multigraph, g, random_move, false, nmerges,
                                    niter, num_vertices(bg), rng, S, nmoves);
259
260
            }
        }
261
        else
262
        {
263
264
265
266
267
268
269
270
271
272
273
274
            half_edge_neighbour_policy<Graph> npolicy(g);
            auto ub = b.get_unchecked(num_vertices(g));
            for (size_t i = 0; i < vlist.size(); ++i)
            {
                size_t v = vlist[i];
                size_t s = target_blocks[i];
                S += virtual_move(v, s, ub, cv, vmap, states, m_entries,
                                  dense, deg_corr, multigraph, npolicy);
                move_vertex(v, s, ub, cv, vmap, deg_corr, states,
                            not random_move, npolicy);
                nmoves++;
            }
275
276
277
278
279
280
281
282
283
284
        }
    }
};


boost::python::object
do_move_sweep_overlap(GraphInterface& gi, GraphInterface& bgi, boost::any& emat,
                      boost::any sampler, boost::any cavity_sampler,
                      boost::any omrs, boost::any omrp, boost::any omrm,
                      boost::any owr, boost::any ob, boost::any olabel,
285
286
                      vector<int64_t>& vlist, vector<int64_t>& block_list,
                      vector<int64_t>& target_blocks, bool deg_corr, bool dense,
287
288
289
290
291
                      bool multigraph, bool parallel_edges, boost::any oeweight,
                      boost::any ovweight, boost::any oegroups,
                      boost::any oesrcpos, boost::any oetgtpos, double beta,
                      bool sequential, bool parallel, bool random_move,
                      double c, bool node_coherent, bool weighted,
292
                      size_t nmerges, boost::any omerge_map, size_t niter,
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
                      overlap_stats_t& overlap_stats,
                      overlap_partition_stats_t& partition_stats, bool verbose,
                      rng_t& rng)
{
    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;
    typedef property_map_type::apply<int32_t,
                                     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;

    vmap_t merge_map = any_cast<vmap_t>(omerge_map);

    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()
        (gi, std::bind(move_sweep_overlap_dispatch<emap_t, vmap_t, vemap_t>
                       (eweight, vweight, oegroups, esrcpos, etgtpos,
326
327
                        label, vlist, block_list, target_blocks, deg_corr, dense,
                        multigraph, parallel_edges, beta, sequential, parallel,
328
                        random_move, c, node_coherent, verbose, gi.get_edge_index_range(),
329
330
                        nmerges, niter, merge_map, overlap_stats, partition_stats,
                        rng, S, nmoves, bgi),
331
                       mrs, mrp, mrm, wr, b, std::placeholders::_1,
332
333
334
335
336
337
                       std::ref(emat), sampler, cavity_sampler, weighted))();
    return boost::python::make_tuple(S, nmoves);
}

struct get_overlap_stats
{
338
339
    template <class Graph, class Vprop, class VIprop, class VVprop>
    void operator()(Graph& g, Vprop b, VVprop half_edges, VIprop node_index,
340
341
                    size_t B, overlap_stats_t& overlap_stats) const
    {
342
343
344
        overlap_stats = overlap_stats_t(g, b.get_unchecked(num_vertices(g)),
                                        half_edges,
                                        node_index.get_unchecked(num_vertices(g)), B);
345
346
347
348
349
350
    }
};

overlap_stats_t
do_get_overlap_stats(GraphInterface& gi, boost::any ob,
                     boost::any ohalf_edges, boost::any onode_index,
351
                     size_t NN, size_t B)
352
353
354
355
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
356
357
358
359
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
    typedef property_map_type::apply<vector<int64_t>,
360
361
362
363
364
365
366
                                     GraphInterface::vertex_index_map_t>::type
        vvmap_t;

    overlap_stats_t overlap_stats;

    vmap_t b = any_cast<vmap_t>(ob);
    vvmap_t half_edges = any_cast<vvmap_t>(ohalf_edges);
367
    vimap_t node_index = any_cast<vimap_t>(onode_index);
368

369
    run_action<>()(gi, std::bind(get_overlap_stats(), std::placeholders::_1, b,
370
                                 half_edges.get_unchecked(NN), node_index, B,
371
372
373
374
375
376
377
378
                                 std::ref(overlap_stats)))();
    return overlap_stats;
}

struct get_overlap_partition_stats
{
    template <class Graph, class Vprop, class Eprop>
    void operator()(Graph& g, Vprop b, Eprop eweight, size_t N, size_t B,
379
                    bool edges_dl, overlap_stats_t& overlap_stats,
380
381
382
                    overlap_partition_stats_t& partition_stats) const
    {
        partition_stats = overlap_partition_stats_t(g, b, overlap_stats,
383
                                                    eweight, N, B, edges_dl);
384
385
386
387
388
389
    }
};

overlap_partition_stats_t
do_get_overlap_partition_stats(GraphInterface& gi, boost::any ob,
                               boost::any aeweight, size_t N, size_t B,
390
                               bool edges_dl, overlap_stats_t& overlap_stats)
391
392
393
394
395
396
397
398
399
400
401
402
403
404
{
    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;

    overlap_partition_stats_t partition_stats;

    vmap_t b = any_cast<vmap_t>(ob);
    emap_t eweight = any_cast<emap_t>(aeweight);

    run_action<>()(gi, std::bind(get_overlap_partition_stats(),
405
                                 std::placeholders::_1, b, eweight, N, B, edges_dl,
406
407
408
409
410
411
                                 std::ref(overlap_stats),
                                 std::ref(partition_stats)))();

    return partition_stats;
}

412
double do_get_overlap_parallel_entropy(GraphInterface& gi,
413
414
415
416
417
                                       overlap_stats_t& overlap_stats)
{
    double S = 0;
    run_action<>()
        (gi, std::bind(entropy_parallel_edges_overlap(),
418
                       std::placeholders::_1, std::ref(overlap_stats),
419
420
421
422
423
424
425
426
                       std::ref(S)))();
    return S;
}


struct get_eg_overlap
{
    template <class Graph, class EGraph, class EVprop, class VProp,
427
428
429
              class VIProp, class VVProp, class EProp>
    void operator()(Graph& g, EGraph& eg, EVprop be, VProp b, VIProp node_index,
                    VVProp half_edges, EProp egindex) const
430
    {
431
        auto eindex = get(edge_index, g);
432
433
434
435
436
437
438
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
        for (auto e : edges_range(g))
        {
            vertex_t s = get_source(e, g);
            vertex_t t = get_target(e, g);
            vertex_t u = add_vertex(eg);
            vertex_t v = add_vertex(eg);
439
440
            auto ne = add_edge(u, v, eg).first;
            egindex[ne] = eindex[e];
441
442
            if (be[e].size() != 2)
                throw GraphException("Edge block property map must have two values per edge");
443
444
445
446
447
448
449
450
451
452
453
454
            b[u] = be[e][0];
            b[v] = be[e][1];
            node_index[u] = s;
            node_index[v] = t;
            half_edges[s].push_back(u);
            half_edges[t].push_back(v);
        }
    }
};

void do_get_eg_overlap(GraphInterface& gi, GraphInterface& egi, boost::any obe,
                       boost::any ob, boost::any onode_index,
455
                       boost::any ohalf_edges, boost::any oeindex)
456
457
458
459
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
460
461
462
463
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
    typedef property_map_type::apply<vector<int64_t>,
464
465
466
467
468
                                     GraphInterface::vertex_index_map_t>::type
        vvmap_t;
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::edge_index_map_t>::type
        evmap_t;
469
470
471
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
472
473
474

    vmap_t b = any_cast<vmap_t>(ob);
    evmap_t be = any_cast<evmap_t>(obe);
475
    vimap_t node_index = any_cast<vimap_t>(onode_index);
476
    vvmap_t half_edges = any_cast<vvmap_t>(ohalf_edges);
477
    emap_t eindex = any_cast<emap_t>(oeindex);
478

479
    run_action<>()(gi, std::bind(get_eg_overlap(), std::placeholders::_1,
480
                                 std::ref(egi.get_graph()), be, b, node_index,
481
                                 half_edges, eindex))();
482
483
484
485
}

struct get_be_overlap
{
486
487
    template <class Graph, class EGraph, class EVprop, class VProp, class VIProp>
    void operator()(Graph& g, EGraph& eg, EVprop be, VProp b, VIProp node_index)
488
489
490
491
        const
    {
        for (auto ei : edges_range(eg))
        {
492
493
            auto u = source(ei, eg);
            auto v = target(ei, eg);
494

495
496
            auto s = vertex(node_index[u], g);
            auto t = vertex(node_index[v], g);
497
498
499
500
501
502
503
504
505

            for (auto e : out_edges_range(s, g))
            {
                if (!be[e].empty() || target(e, g) != t)
                    continue;
                if (is_directed::apply<Graph>::type::value || s < target(e, g))
                    be[e] = {b[u], b[v]};
                else
                    be[e] = {b[v], b[u]};
506
                break;
507
508
509
510
511
512
513
            }

            for (auto e : in_edges_range(t, g))
            {
                if (!be[e].empty() || source(e, g) != s)
                    continue;
                be[e] = {b[u], b[v]};
514
                break;
515
516
517
518
519
520
521
522
523
524
525
            }
        }
    }
};

void do_get_be_overlap(GraphInterface& gi, GraphInterface& egi, boost::any obe,
                       boost::any ob, boost::any onode_index)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
526
527
528
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
529
530
531
532
533
534
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::edge_index_map_t>::type
        evmap_t;

    vmap_t b = any_cast<vmap_t>(ob);
    evmap_t be = any_cast<evmap_t>(obe);
535
    vimap_t node_index = any_cast<vimap_t>(onode_index);
536

537
    run_action<>()(gi, std::bind(get_be_overlap(), std::placeholders::_1,
538
                                 std::ref(egi.get_graph()), be, b,
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
                                 node_index))();
}


struct get_be_from_b_overlap
{
    template <class Graph, class EVprop, class VProp>
    void operator()(Graph& g, EVprop be, VProp b)
        const
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
        typename graph_traits<Graph>::edge_iterator ei, ei_end;
        for (auto e : edges_range(g))
        {
            vertex_t s = get_source(e, g);
            vertex_t t = get_target(e, g);
            be[e] = {b[s], b[t]};
        }
    }
};

void do_get_be_from_b_overlap(GraphInterface& gi, boost::any obe, boost::any ob)
{
    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
        evmap_t;

    vmap_t b = any_cast<vmap_t>(ob);
    evmap_t be = any_cast<evmap_t>(obe);

572
    run_action<>()(gi, std::bind(get_be_from_b_overlap(), std::placeholders::_1,
573
574
575
576
577
578
                                 be, b))();
}


struct get_bv_overlap
{
579
580
581
    template <class Graph, class VProp, class VIProp, class VVProp>
    void operator()(Graph& g, VProp b, VIProp node_index, VVProp bv,
                    VVProp bc_in, VVProp bc_out, VVProp bc_total) const
582
583
584
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

585
        typedef gt_hash_map<int, int> map_t;
586
587
588
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
        vector<map_t> hist_in;
        vector<map_t> hist_out;

        for (auto v : vertices_range(g))
        {
            if (out_degree(v, g) > 0)
            {
                vertex_t s = node_index[v];
                if (s >= hist_out.size())
                    hist_out.resize(s + 1);
                hist_out[s][b[v]]++;
            }

            if (in_degreeS()(v, g) > 0)
            {
                vertex_t t = node_index[v];
                if (t >= hist_in.size())
                    hist_in.resize(t + 1);
                hist_in[t][b[v]]++;
            }
        }

        size_t N = max(hist_in.size(), hist_out.size());
        hist_in.resize(N);
        hist_out.resize(N);

        set<size_t> rs;
        for (size_t i = 0; i < N; ++i)
        {
            rs.clear();
            for (auto iter = hist_out[i].begin(); iter != hist_out[i].end(); ++iter)
                rs.insert(iter->first);
            for (auto iter = hist_in[i].begin(); iter != hist_in[i].end(); ++iter)
                rs.insert(iter->first);
            // if (rs.empty())
            //     throw GraphException("Cannot have empty overlapping block membership!");
            for (size_t r : rs)
            {
                bv[i].push_back(r);

                auto iter_in = hist_in[i].find(r);
                if (iter_in != hist_in[i].end())
                    bc_in[i].push_back(iter_in->second);
                else
                    bc_in[i].push_back(0);

                auto iter_out = hist_out[i].find(r);
                if (iter_out != hist_out[i].end())
                    bc_out[i].push_back(iter_out->second);
                else
                    bc_out[i].push_back(0);

                bc_total[i].push_back(bc_in[i].back() +
                                      bc_out[i].back());
            }
        }
    }
};

void do_get_bv_overlap(GraphInterface& gi, boost::any ob,  boost::any onode_index,
                       boost::any obv, boost::any obc_in, boost::any obc_out,
                       boost::any obc_total)
{
649
650
651
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
652
653
654
655
656
657
658
659
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::vertex_index_map_t>::type
        vvmap_t;

    vmap_t b = any_cast<vmap_t>(ob);
660
    vimap_t node_index = any_cast<vimap_t>(onode_index);
661
662
663
664
665
    vvmap_t bv = any_cast<vvmap_t>(obv);
    vvmap_t bc_in = any_cast<vvmap_t>(obc_in);
    vvmap_t bc_out = any_cast<vvmap_t>(obc_out);
    vvmap_t bc_total = any_cast<vvmap_t>(obc_total);

666
    run_action<>()(gi, std::bind(get_bv_overlap(), std::placeholders::_1, b,
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
                                 node_index, bv, bc_in, bc_out, bc_total))();
 }

struct get_wr_overlap
{
    template <class Graph, class VProp, class VVProp>
    void operator()(Graph& g, VVProp bv, VProp wr) const
    {
        for (auto v : vertices_range(g))
        {
            for (size_t i = 0; i < bv[v].size(); ++i)
                wr[bv[v][i]]++;
        }
    }
};

void do_get_wr_overlap(GraphInterface& gi, boost::any obv,
                       boost::any owr)
{
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::vertex_index_map_t>::type
        vvmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;

    vvmap_t bv = any_cast<vvmap_t>(obv);
    vmap_t wr = any_cast<vmap_t>(owr);

696
    run_action<>()(gi, std::bind(get_wr_overlap(), std::placeholders::_1, bv, wr))();
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
}

struct get_nodeset_overlap
{
    template <class Graph, class VProp, class VVProp>
    void operator()(Graph& g, VProp node_index, VVProp half_edges)
        const
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
        for (auto e : edges_range(g))
        {
            vertex_t s = get_source(e, g);
            vertex_t t = get_target(e, g);
            half_edges[node_index[s]].push_back(s);
            half_edges[node_index[t]].push_back(t);
        }
    }
};

void do_get_nodeset_overlap(GraphInterface& gi, boost::any onode_index,
                            boost::any ohalf_edges)
{
719
    typedef property_map_type::apply<int64_t,
720
721
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
722
    typedef property_map_type::apply<vector<int64_t>,
723
724
725
726
727
728
                                     GraphInterface::vertex_index_map_t>::type
        vvmap_t;

    vmap_t node_index = any_cast<vmap_t>(onode_index);
    vvmap_t half_edges = any_cast<vvmap_t>(ohalf_edges);

729
    run_action<>()(gi, std::bind(get_nodeset_overlap(), std::placeholders::_1,
730
731
732
733
734
                                 node_index, half_edges))();
}

struct get_augmented_overlap
{
735
736
    template <class Graph, class VProp, class VIProp>
    void operator()(Graph& g, VProp b, VIProp node_index, VProp br_map,
737
738
                    vector<int32_t>& br_b, vector<int32_t>& br_ni) const
    {
739
        gt_hash_map<std::tuple<int, int>, size_t> idx_map;
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
        vector<std::tuple<int, int>> idx_rmap;
        size_t pos = 0;

        for (auto v : vertices_range(g))
        {
            size_t vi = node_index[v];
            auto br = std::make_tuple(b[v], vi);
            size_t idx;
            auto iter = idx_map.find(br);
            if (iter != idx_map.end())
            {
                idx = iter->second;
            }
            else
            {
                idx = pos;
                idx_map[br] = pos++;
                idx_rmap.push_back(br);
            }
            br_map[v] = idx;
        }

        for (size_t i = 0; i < idx_rmap.size(); ++i)
        {
            auto& br = idx_rmap[i];
            br_b.push_back(get<0>(br));
            br_ni.push_back(get<1>(br));
        }
    }
};

void do_get_augmented_overlap(GraphInterface& gi, boost::any ob,
                              boost::any onode_index, boost::any obr_map,
                              vector<int32_t>& br_b, vector<int32_t>& br_ni)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
778
779
780
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
781
782

    vmap_t b = any_cast<vmap_t>(ob);
783
    vimap_t node_index = any_cast<vimap_t>(onode_index);
784
785
    vmap_t br_map = any_cast<vmap_t>(obr_map);

786
    run_action<>()(gi, std::bind(get_augmented_overlap(), std::placeholders::_1,
787
788
789
790
791
792
793
794
795
796
                                 b, node_index, br_map, std::ref(br_b),
                                 std::ref(br_ni)))();
}


struct get_overlap_split
{
    template <class Graph, class VVProp, class VProp>
    void operator()(Graph& g, VVProp bv, VProp b) const
    {
797
        gt_hash_map<vector<int>, size_t> bvset;
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

        for (auto v : vertices_range(g))
        {
            auto r = bv[v];
            auto iter = bvset.find(r);
            if (iter == bvset.end())
                iter = bvset.insert(make_pair(r, bvset.size())).first;
            b[v] = iter->second;
        }
    }
};

void do_get_overlap_split(GraphInterface& gi, boost::any obv, boost::any ob)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::vertex_index_map_t>::type
        vvmap_t;

    vvmap_t bv = any_cast<vvmap_t>(obv);
    vmap_t b = any_cast<vmap_t>(ob);

    run_action<>()(gi, std::bind(get_overlap_split(),
823
                                 std::placeholders::_1, bv, b))();
824
825
}

826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861

struct get_maj_overlap
{
    template <class Graph, class VProp, class VVProp>
    void operator()(Graph& g, VVProp bv, VVProp bc_total, VProp b) const
    {
        for (auto v : vertices_range(g))
        {
            if (bv[v].empty())
            {
                b[v] = numeric_limits<int32_t>::max();
                continue;
            }

            auto& c = bc_total[v];
            auto pos = std::max_element(c.begin(), c.end());
            auto r = *(bv[v].begin() + (pos - c.begin()));
            b[v] = r;
        }
    }
};

void do_get_maj_overlap(GraphInterface& gi, boost::any obv,
                        boost::any obc_total, boost::any ob)
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::vertex_index_map_t>::type
        vvmap_t;

    vmap_t b = any_cast<vmap_t>(ob);
    vvmap_t bv = any_cast<vvmap_t>(obv);
    vvmap_t bc_total = any_cast<vvmap_t>(obc_total);

862
    run_action<>()(gi, std::bind(get_maj_overlap(), std::placeholders::_1, bv,
863
864
865
866
                                 bc_total, b))();
}


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
893
894
895
896
} // namespace graph_tool


void export_blockmodel_overlap()
{
    using namespace boost::python;

    class_<overlap_stats_t>("overlap_stats")
        .def("is_enabled", &overlap_stats_t::is_enabled);
    class_<overlap_partition_stats_t>("overlap_partition_stats")
        .def("is_enabled", &overlap_partition_stats_t::is_enabled)
        .def("get_partition_dl", &overlap_partition_stats_t::get_partition_dl)
        .def("get_deg_dl", &overlap_partition_stats_t::get_deg_dl);

    def("move_sweep_overlap", do_move_sweep_overlap);
    def("init_overlap_stats", do_get_overlap_stats);
    def("init_overlap_partition_stats", do_get_overlap_partition_stats);

    def("overlap_parallel_entropy", do_get_overlap_parallel_entropy);

    // def("get_overlap_proj", do_get_overlap_proj);

    def("get_eg_overlap", do_get_eg_overlap);
    def("get_be_overlap", do_get_be_overlap);
    def("get_be_from_b_overlap", do_get_be_from_b_overlap);
    def("get_bv_overlap", do_get_bv_overlap);
    def("get_wr_overlap", do_get_wr_overlap);
    def("get_nodeset_overlap", do_get_nodeset_overlap);
    def("get_augmented_overlap", do_get_augmented_overlap);
    def("get_overlap_split", do_get_overlap_split);
897
    def("get_maj_overlap", do_get_maj_overlap);
898
}