graph_blockmodel_overlap.cc 33.5 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 53 54 55 56 57 58

#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,
                                VEprop etgtpos, Vprop label, vector<int>& vlist,
                                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, size_t max_edge_index,
59
                                size_t nmerges, size_t niter, Vprop merge_map,
60 61 62 63 64 65 66 67 68 69 70
                                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),
          etgtpos(etgtpos), label(label), vlist(vlist),
          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),
71 72
          max_edge_index(max_edge_index), nmerges(nmerges),
          niter(niter), merge_map(merge_map), overlap_stats(overlap_stats),
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
          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;
    vector<int>& vlist;
    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;
    size_t max_edge_index;
    size_t nmerges;
97
    size_t niter;
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    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,
                     bgi.GetGraph(), weighted);
        }
        else
        {
            UndirectedAdaptor<GraphInterface::multigraph_t> ug(bgi.GetGraph());
            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, cavity_sampler, ug,
                     weighted);
        }
    }

    template <class Graph, class BGraph>
125 126 127
    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
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    {
        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>
148 149 150
    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
151
    {
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        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);
        }
    }
170

171 172 173 174 175 176
    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;
177 178 179 180 181 182 183 184 185 186

        size_t eidx = random_move ? 1 : max_edge_index;

        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);

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        ConstantPropertyMap<int, typename graph_traits<Graph>::edge_descriptor> ce(0);
        ConstantPropertyMap<std::array<int, 1>, typename graph_traits<Graph>::vertex_descriptor> cv({-1});
        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,
                                      eweight.get_unchecked(max_edge_index),
                                      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);

        if (nmerges == 0)
213
        {
214
            if (!node_coherent)
215
            {
216 217 218 219 220 221 222 223 224
                move_sweep_overlap(states, m_entries, overlap_stats,
                                   wr.get_unchecked(num_vertices(bg)),
                                   b.get_unchecked(num_vertices(g)), ce, cv,
                                   vmap, label.get_unchecked(num_vertices(bg)),
                                   vlist, deg_corr, dense, multigraph, beta,
                                   eweight.get_unchecked(max_edge_index),
                                   vweight.get_unchecked(num_vertices(g)), g,
                                   sequential, parallel, random_move, c, niter,
                                   num_vertices(bg), verbose, rng, S, nmoves);
225 226 227
            }
            else
            {
228 229 230 231 232 233 234 235 236 237 238
                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)), ce, cv,
                                            vmap, label.get_unchecked(num_vertices(bg)),
                                            vlist, deg_corr, dense, multigraph, beta,
                                            eweight.get_unchecked(max_edge_index),
                                            vweight.get_unchecked(num_vertices(g)), g,
                                            sequential, parallel, random_move, c,
                                            false, niter,
                                            num_vertices(bg), verbose, rng, S, nmoves);
239 240
            }
        }
241
        else
242
        {
243 244 245 246 247 248 249 250 251 252 253
            merge_sweep_overlap(states, m_entries, overlap_stats,
                                wr.get_unchecked(num_vertices(bg)),
                                b.get_unchecked(num_vertices(g)), ce, cv,
                                vmap, label.get_unchecked(num_vertices(bg)),
                                vlist, deg_corr, dense, multigraph, beta,
                                eweight.get_unchecked(max_edge_index),
                                vweight.get_unchecked(num_vertices(g)), g,
                                sequential, parallel, random_move, c, false,
                                nmerges, niter,
                                merge_map.get_unchecked(num_vertices(g)),
                                num_vertices(bg), verbose, rng, S, nmoves);
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        }
    }
};


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,
                      vector<int>& vlist, bool deg_corr, bool dense,
                      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,
270
                      size_t nmerges, boost::any omerge_map, size_t niter,
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
                      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,
                        label, vlist, deg_corr, dense, multigraph, parallel_edges,
                        beta, sequential, parallel, random_move, c, node_coherent,
306 307 308
                        verbose, gi.GetMaxEdgeIndex(), nmerges,
                        niter, merge_map, overlap_stats, partition_stats, rng, S,
                        nmoves, bgi),
309 310 311 312 313 314 315
                       mrs, mrp, mrm, wr, b, placeholders::_1,
                       std::ref(emat), sampler, cavity_sampler, weighted))();
    return boost::python::make_tuple(S, nmoves);
}

struct get_overlap_stats
{
316 317
    template <class Graph, class Vprop, class VIprop, class VVprop>
    void operator()(Graph& g, Vprop b, VVprop half_edges, VIprop node_index,
318 319
                    size_t B, overlap_stats_t& overlap_stats) const
    {
320 321 322
        overlap_stats = overlap_stats_t(g, b.get_unchecked(num_vertices(g)),
                                        half_edges,
                                        node_index.get_unchecked(num_vertices(g)), B);
323 324 325 326 327 328
    }
};

overlap_stats_t
do_get_overlap_stats(GraphInterface& gi, boost::any ob,
                     boost::any ohalf_edges, boost::any onode_index,
329
                     size_t NN, size_t B)
330 331 332 333
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
334 335 336 337
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
    typedef property_map_type::apply<vector<int64_t>,
338 339 340 341 342 343 344
                                     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);
345
    vimap_t node_index = any_cast<vimap_t>(onode_index);
346 347

    run_action<>()(gi, std::bind(get_overlap_stats(), placeholders::_1, b,
348
                                 half_edges.get_unchecked(NN), node_index, B,
349 350 351 352 353 354 355 356
                                 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,
357
                    bool edges_dl, overlap_stats_t& overlap_stats,
358 359 360
                    overlap_partition_stats_t& partition_stats) const
    {
        partition_stats = overlap_partition_stats_t(g, b, overlap_stats,
361
                                                    eweight, N, B, edges_dl);
362 363 364 365 366 367
    }
};

overlap_partition_stats_t
do_get_overlap_partition_stats(GraphInterface& gi, boost::any ob,
                               boost::any aeweight, size_t N, size_t B,
368
                               bool edges_dl, overlap_stats_t& overlap_stats)
369 370 371 372 373 374 375 376 377 378 379 380 381 382
{
    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(),
383
                                 placeholders::_1, b, eweight, N, B, edges_dl,
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
                                 std::ref(overlap_stats),
                                 std::ref(partition_stats)))();

    return partition_stats;
}

double do_get_overlap_parallel_entropy(GraphInterface& gi, boost::any ob,
                                       overlap_stats_t& overlap_stats)
{
    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(entropy_parallel_edges_overlap(),
                       placeholders::_1, b, std::ref(overlap_stats),
                       std::ref(S)))();
    return S;
}


struct get_eg_overlap
{
    template <class Graph, class EGraph, class EVprop, class VProp,
411 412 413
              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
414
    {
415
        auto eindex = get(edge_index, g);
416 417 418 419 420 421 422
        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);
423 424
            auto ne = add_edge(u, v, eg).first;
            egindex[ne] = eindex[e];
425 426
            if (be[e].size() != 2)
                throw GraphException("Edge block property map must have two values per edge");
427 428 429 430 431 432 433 434 435 436 437 438
            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,
439
                       boost::any ohalf_edges, boost::any oeindex)
440 441 442 443
{
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
444 445 446 447
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
    typedef property_map_type::apply<vector<int64_t>,
448 449 450 451 452
                                     GraphInterface::vertex_index_map_t>::type
        vvmap_t;
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::edge_index_map_t>::type
        evmap_t;
453 454 455
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;
456 457 458

    vmap_t b = any_cast<vmap_t>(ob);
    evmap_t be = any_cast<evmap_t>(obe);
459
    vimap_t node_index = any_cast<vimap_t>(onode_index);
460
    vvmap_t half_edges = any_cast<vvmap_t>(ohalf_edges);
461
    emap_t eindex = any_cast<emap_t>(oeindex);
462 463 464

    run_action<>()(gi, std::bind(get_eg_overlap(), placeholders::_1,
                                 std::ref(egi.GetGraph()), be, b, node_index,
465
                                 half_edges, eindex))();
466 467 468 469
}

struct get_be_overlap
{
470 471
    template <class Graph, class EGraph, class EVprop, class VProp, class VIProp>
    void operator()(Graph& g, EGraph& eg, EVprop be, VProp b, VIProp node_index)
472 473 474 475
        const
    {
        for (auto ei : edges_range(eg))
        {
476 477
            auto u = source(ei, eg);
            auto v = target(ei, eg);
478

479 480
            auto s = vertex(node_index[u], g);
            auto t = vertex(node_index[v], g);
481 482 483 484 485 486 487 488 489

            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]};
490
                break;
491 492 493 494 495 496 497
            }

            for (auto e : in_edges_range(t, g))
            {
                if (!be[e].empty() || source(e, g) != s)
                    continue;
                be[e] = {b[u], b[v]};
498
                break;
499 500 501 502 503 504 505 506 507 508 509
            }
        }
    }
};

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;
510 511 512
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
513 514 515 516 517 518 519 520 521
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::edge_index_map_t>::type
        evmap_t;
    typedef property_map_type::apply<int32_t,
                                     GraphInterface::edge_index_map_t>::type
        emap_t;

    vmap_t b = any_cast<vmap_t>(ob);
    evmap_t be = any_cast<evmap_t>(obe);
522
    vimap_t node_index = any_cast<vimap_t>(onode_index);
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 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

    run_action<>()(gi, std::bind(get_be_overlap(), placeholders::_1,
                                 std::ref(egi.GetGraph()), be, b,
                                 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);

    run_action<>()(gi, std::bind(get_be_from_b_overlap(), placeholders::_1,
                                 be, b))();
}


struct get_bv_overlap
{
566 567 568
    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
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 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
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

        typedef unordered_map<int, int> map_t;
        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)
{
636 637 638
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
639 640 641 642 643 644 645 646 647 648 649
    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;
    typedef property_map_type::apply<vector<int32_t>,
                                     GraphInterface::edge_index_map_t>::type
        evmap_t;

    vmap_t b = any_cast<vmap_t>(ob);
650
    vimap_t node_index = any_cast<vimap_t>(onode_index);
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 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 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    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);

    run_action<>()(gi, std::bind(get_bv_overlap(), placeholders::_1, b,
                                 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
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

        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);

    run_action<>()(gi, std::bind(get_wr_overlap(), placeholders::_1, bv, wr))();
}

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)
{
711
    typedef property_map_type::apply<int64_t,
712 713
                                     GraphInterface::vertex_index_map_t>::type
        vmap_t;
714
    typedef property_map_type::apply<vector<int64_t>,
715 716 717 718 719 720 721 722 723 724 725 726
                                     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);

    run_action<>()(gi, std::bind(get_nodeset_overlap(), placeholders::_1,
                                 node_index, half_edges))();
}

struct get_augmented_overlap
{
727 728
    template <class Graph, class VProp, class VIProp>
    void operator()(Graph& g, VProp b, VIProp node_index, VProp br_map,
729 730 731 732 733
                    vector<int32_t>& br_b, vector<int32_t>& br_ni) const
    {

        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

734
        unordered_map<std::tuple<int, int>, size_t> idx_map;
735 736 737 738 739 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
        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;
773 774 775
    typedef property_map_type::apply<int64_t,
                                     GraphInterface::vertex_index_map_t>::type
        vimap_t;
776 777

    vmap_t b = any_cast<vmap_t>(ob);
778
    vimap_t node_index = any_cast<vimap_t>(onode_index);
779 780 781 782 783 784 785 786 787 788 789 790 791
    vmap_t br_map = any_cast<vmap_t>(obr_map);

    run_action<>()(gi, std::bind(get_augmented_overlap(), placeholders::_1,
                                 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
    {
792
        unordered_map<vector<int>, size_t> bvset;
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820

        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(),
                                 placeholders::_1, bv, b))();
}

821 822 823 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 862 863

struct get_maj_overlap
{
    template <class Graph, class VProp, class VVProp>
    void operator()(Graph& g, VVProp bv, VVProp bc_total, VProp b) const
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

        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);

    run_action<>()(gi, std::bind(get_maj_overlap(), placeholders::_1, bv,
                                 bc_total, b))();
}


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 893
} // 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);
894
    def("get_maj_overlap", do_get_maj_overlap);
895
}