graph_blockmodel.hh 92 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
//
// 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/>.

#ifndef GRAPH_BLOCKMODEL_HH
#define GRAPH_BLOCKMODEL_HH

#include <cmath>
#include <iostream>
23
#include <queue>
24
#include <boost/math/special_functions/zeta.hpp>
25
#include <boost/functional/hash.hpp>
26

27
#include "config.h"
Tiago Peixoto's avatar
Tiago Peixoto committed
28
29
30
#include <unordered_set>
#include <unordered_map>
#include <tuple>
31

32
#ifdef HAVE_SPARSEHASH
33
34
#include SPARSEHASH_INCLUDE(dense_hash_set)
#include SPARSEHASH_INCLUDE(dense_hash_map)
35
#endif
36

37
#include "../generation/sampler.hh"
38
#include "../generation/dynamic_sampler.hh"
39

40
41
42
43
44
45
46
#ifdef USING_OPENMP
#include <omp.h>
#endif


double spence(double);

47
48
49
namespace graph_tool
{

50
#ifdef HAVE_SPARSEHASH
51
using google::dense_hash_set;
52
using google::dense_hash_map;
53
#endif
54
55
56

using namespace boost;

57
58
59
60
61
62
63
64
65
66
67
68
69
70
template <class Key>
class IdentityArrayPropertyMap
    : public boost::put_get_helper<Key, IdentityArrayPropertyMap<Key>>
{
public:
    typedef std::array<Key, 1> value_type;
    typedef value_type reference;
    typedef Key key_type;
    typedef boost::readable_property_map_tag category;

    inline __attribute__((always_inline))
    const value_type operator[](const key_type& c) const { return {c}; }
};

71
72
73
74
// ====================
// Entropy calculation
// ====================

75
76
77
78
79
80
// 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.

81
82
83
84
extern vector<double> __safelog_cache;
extern vector<double> __xlogx_cache;
extern vector<double> __lgamma_cache;

85
86
87
88
89
90
91
92
93
94
template <class Type>
__attribute__((always_inline))
inline double safelog(Type x)
{
    if (x == 0)
        return 0;
    return log(x);
}

__attribute__((always_inline))
95
96
inline double safelog(size_t x)
{
97
98
99
100
101
102
    if (x >= __safelog_cache.size())
    {
        if (x == 0)
            return 0;
        return log(x);
    }
103
104
    return __safelog_cache[x];
}
105
106

__attribute__((always_inline))
107
108
109
inline double xlogx(size_t x)
{
    if (x >= __xlogx_cache.size())
110
        return x * safelog(x);
111
112
    return __xlogx_cache[x];
}
113
114

__attribute__((always_inline))
115
116
117
118
119
120
121
inline double lgamma_fast(size_t x)
{
    if (x >= __lgamma_cache.size())
        return lgamma(x);
    return __lgamma_cache[x];
}

122
// polylogarithm and degree-distribution description length (xi)
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170

template <class Type>
Type polylog(int n, Type z, Type epsilon=1e-6)
{
    if (n == 2)
        return spence(1 - z);

    int k = 1;
    Type S = 0;
    Type delta = epsilon + 1;
    Type zk = z;
    while (delta > epsilon)
    {
        Type dS = zk / pow(k, n);
        k++;
        zk *= z;
        S += dS;
        delta = dS;
    }
    return S;
}

template <class NType, class EType>
void get_mu_l(NType N, EType E, double& mu, double& l,
              double epsilon=1e-8)
{
    mu = sqrt(polylog<double>(2, 1.) / double(E));
    l = 1. - exp(-double(N) * mu);

    double delta = epsilon + 1;
    while (delta > epsilon)
    {
        double nmu = sqrt(polylog<double>(2, l) / double(E));
        double nl = 1. - exp(-double(N) * mu);

        delta = abs(nmu - mu) + abs(nl - l);
        mu = nmu;
        l = nl;
    }

    l = -log(l);
}

template <class NType, class EType>
double get_xi(NType N, EType E, double epsilon=1e-8)
{
    if (E == 0 || N == 0)
        return 0;
171

172
    double mu = 0, l = 0;
173
    get_mu_l(N, E, mu, l, epsilon);
174
175
176
177
178
179
180
181
182
183
184
185
    double S = double(N) * l + 2 * double(E) * mu;
    return S;
}

template <class NType, class EType>
double get_xi_fast(NType N, EType E)
{
    if (E == 0 || N == 0)
        return 0;
    static const double z2 = boost::math::zeta(2.);
    return 2 * sqrt(z2 * E);
}
186

187
188
// Sparse entropy terms
// ====================
189
190

// "edge" term of the entropy
191
template <class Graph>
192
__attribute__((always_inline))
193
inline double eterm(size_t r, size_t s, size_t mrs, const Graph&)
194
{
195
196
    if (!is_directed::apply<Graph>::type::value && r == s)
        mrs *= 2;
197

198
    double val = xlogx(mrs);
199
200
201
202
203
204
205
206

    if (is_directed::apply<Graph>::type::value || r != s)
        return -val;
    else
        return -val / 2;
}

// "vertex" term of the entropy
207
208
template <class Graph>
inline double vterm(size_t mrp, size_t mrm, size_t wr, bool deg_corr,
209
                    Graph&)
210
211
212
213
214
215
216
{
    double one = 0.5;

    if (is_directed::apply<Graph>::type::value)
        one = 1;

    if (deg_corr)
217
        return one * (xlogx(mrm) + xlogx(mrp));
218
    else
219
        return one * (mrm * safelog(wr) + mrp * safelog(wr));
220
221
222
223
224
}

struct entropy
{
    template <class Graph, class Eprop, class Vprop>
225
226
227
228
229
230
231
    void operator()(Eprop& mrs, Vprop& mrp, Vprop& mrm, Vprop& wr,
                    bool deg_corr, Graph& g, double& S) const
    {
        S = 0;
        for (auto e : edges_range(g))
            S += eterm(source(e, g), target(e, g), mrs[e], g);
        for (auto v : vertices_range(g))
232
            S += vterm(mrp[v], mrm[v], wr[v], deg_corr, g);
233
234
235
    }
};

236
237
// Parallel edges
// ==============
238
239

template <class Vertex, class List, class Graph, class GetNode>
240
double get_parallel_neighbours_entropy(Vertex v, List& us, Graph&,
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
                                       const GetNode& get_node)
{
    double S = 0;
    for (auto& uc : us)
    {
        auto& u = uc.first;
        auto& m = uc.second;
        if (m > 1)
        {
            if (get_node(u) == size_t(v) && !is_directed::apply<Graph>::type::value)
            {
                assert(m % 2 == 0);
                S += lgamma_fast(m/2 + 1);
            }
            else
            {
                S += lgamma_fast(m + 1);
            }
        }
    }
    return S;
}

struct entropy_parallel_edges
{
    template <class Graph, class Weight>
    void operator()(Graph& g, Weight weight, double& S) const
268
269
    {
        S = 0;
270
271
272
273
274
275
276
277
278
279
280
281
282
283
        auto get_node = [](size_t i) {return i;};
        for (auto v : vertices_range(g))
        {
            unordered_map<decltype(v), int> us;
            for (auto e : out_edges_range(v, g))
            {
                auto u = target(e, g);
                if (u < v && !is_directed::apply<Graph>::type::value)
                    continue;
                us[u] += weight[e];
            }

            S += get_parallel_neighbours_entropy(v, us, g, get_node);
        }
284
285
286
287
    }
};


288
// Dense entropy
289
// =============
290

291
292
293
// Warning: lgamma(x) is not thread-safe! However, since in the context of this
// program the outputs should _always_ be positive, this can be overlooked.

294
295
__attribute__((always_inline))
inline double lbinom(double N, double k)
296
{
297
298
    if (N == 0 || k == 0 || k > N)
        return 0;
299
    return (lgamma(N + 1) - lgamma(k + 1)) - lgamma(N - k + 1);
300
301
}

302
303
__attribute__((always_inline))
inline double lbinom_fast(int N, int k)
304
{
305
306
    if (N == 0 || k == 0 || k > N)
        return 0;
307
308
    return lgamma_fast(N + 1) - lgamma_fast(N - k + 1) - lgamma_fast(k + 1);
}
309

310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
__attribute__((always_inline))
inline double lbinom_careful(double N, double k)
{
    if (N == 0 || k == 0 || k >= N)
        return 0;
    double lgN = lgamma(N + 1);
    double lgk = lgamma(k + 1);
    if (lgN - lgk > 1e8)
    {
        // We have N >> k. Use Stirling's approximation: ln N! ~ N ln N - N
        // and reorder
        return - N * log1p(-k / N) - k * log1p(-k / N) - k - lgk + k * log(N);
    }
    else
    {
        return lgN - lgamma(N - k + 1) - lgk;
    }
}

329

330
331
332
// "edge" term of the entropy
template <class Graph>
__attribute__((always_inline))
333
inline double eterm_dense(size_t r, size_t s, int ers, double wr_r,
334
                          double wr_s, bool multigraph, const Graph&)
335
{
336
337
    // we should not use integers here, since they may overflow
    double nrns;
338

339
340
    if (ers == 0)
        return 0.;
341

342
343
344
    if (r != s || is_directed::apply<Graph>::type::value)
    {
        nrns = wr_r * wr_s;
345
    }
346
    else
347
    {
348
349
350
351
        if (multigraph)
            nrns = (wr_r * (wr_r + 1)) / 2;
        else
            nrns = (wr_r * (wr_r - 1)) / 2;
352
353
    }

354
355
    double S;
    if (multigraph)
356
        S = lbinom(nrns + ers - 1, ers); // do not use lbinom_fast!
357
    else
358
        S = lbinom(nrns, ers);
359
360
    return S;
}
361

362
363
struct entropy_dense
{
364
    template <class Graph, class Eprop, class Vprop>
365
    void operator()(Eprop mrs, Vprop& wr, bool multigraph, Graph& g, double& S) const
366
    {
367
        S = 0;
368
        for (auto e : edges_range(g))
369
        {
370
371
372
            auto r = source(e, g);
            auto s = target(e, g);
            S += eterm_dense(r, s, mrs[e], wr[r], wr[s], multigraph, g);
373
374
375
376
        }
    }
};

377
// ===============
378
// Partition stats
379
// ===============
380
381
382
383
384
385

class partition_stats_t
{
public:

#ifdef HAVE_SPARSEHASH
386
    typedef dense_hash_map<pair<size_t,size_t>, int, std::hash<pair<size_t,size_t>>> map_t;
387
#else
388
    typedef unordered_map<pair<size_t,size_t>, int> map_t;
389
390
391
392
393
#endif

    partition_stats_t() : _enabled(false) {}

    template <class Graph, class Vprop, class Eprop>
394
395
396
397
    partition_stats_t(Graph& g, Vprop b, Eprop eweight, size_t N, size_t B,
                      bool edges_dl)
        : _enabled(true), _N(N), _E(0), _B(B), _hist(B), _total(B), _ep(B),
          _em(B), _edges_dl(edges_dl)
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    {

#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()));
            _hist[r].set_deleted_key(make_pair(numeric_limits<size_t>::max() - 1,
                                               numeric_limits<size_t>::max() - 1));
        }
#endif

        for (auto v : vertices_range(g))
        {
            auto r = b[v];
413
414
415
            size_t kin = in_degreeS()(v, g, eweight);
            size_t kout = out_degreeS()(v, g, eweight);
            _hist[r][make_pair(kin, kout)]++;
416
            _total[r]++;
417
418
419
            _em[r] += kin;
            _ep[r] += kout;
            _E += kout;
420
        }
421
422
423
424
425
426
427
428

        if (!is_directed::apply<Graph>::type::value)
            _E /= 2;

        _actual_B = 0;
        for (size_t r = 0; r < B; ++r)
            if (_total[r] > 0)
                _actual_B++;
429
430
431
432
433
    }

    double get_partition_dl()
    {
        double S = 0;
434
        S += lbinom(_actual_B + _N - 1, _N);
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
        S += lgamma(_N + 1);
        for (auto nr : _total)
            S -= lgamma(nr + 1);
        return S;
    }

    double get_deg_dl(bool ent, bool dl_alt, bool xi_fast)
    {
        double S = 0;
        for (size_t r = 0; r < _B; ++r)
        {
            if (ent)
            {
                for (auto& k_c : _hist[r])
                {
                    double p = k_c.second / double(_total[r]);
                    S -= p * log(p) * _total[r];
                }
            }
            else
            {
                double S1 = 0;

                if (xi_fast)
                {
                    S1 += get_xi_fast(_total[r], _ep[r]);
                    S1 += get_xi_fast(_total[r], _em[r]);
                }
                else
                {
                    S1 += get_xi(_total[r], _ep[r]);
                    S1 += get_xi(_total[r], _em[r]);
                }

                S1 += lgamma(_total[r] + 1);
                for (auto& k_c : _hist[r])
                    S1 -= lgamma(k_c.second + 1);

                if (dl_alt)
                {
                    double S2 = 0;
                    S2 += lbinom(_total[r] + _ep[r] - 1, _ep[r]);
                    S2 += lbinom(_total[r] + _em[r] - 1, _em[r]);
                    S += min(S1, S2);
                }
                else
                {
                    S += S1;
                }
            }
        }
        return S;
    }

    template <class Graph, class OStats>
490
    double get_delta_dl(size_t, size_t r, size_t nr, OStats&, Graph&)
491
492
493
494
495
496
497
498
    {
        if (r == nr)
            return 0;

        double S_b = 0, S_a = 0;
        S_b += -lgamma_fast(_total[r] + 1) - lgamma_fast(_total[nr] + 1);
        S_a += -lgamma_fast(_total[r]    ) - lgamma_fast(_total[nr] + 2);

499
500
501
502
503
504
505
        int dB = 0;
        if (_total[r] == 1)
            dB--;
        if (_total[nr] == 0)
            dB++;

        if (dB != 0)
506
        {
507
508
            S_b += lbinom(_actual_B + _N - 1, _N);
            S_a += lbinom(_actual_B + dB + _N - 1, _N);
509

510
511
512
            if (_edges_dl)
            {
                auto get_x = [](size_t B) -> size_t
513
                {
514
515
516
517
                    if (is_directed::apply<Graph>::type::value)
                        return B * B;
                    else
                        return (B * (B + 1)) / 2;
518
519
                };

520
521
522
523
                S_b += lbinom(get_x(_actual_B) + _E - 1, _E);
                S_a += lbinom(get_x(_actual_B + dB) + _E - 1, _E);
            }
        }
524

525
526
527
528
529
530
531
532
533
        return S_a - S_b;
    }

    template <class Graph, class EWeight, class OStats>
    double get_delta_deg_dl(size_t v, size_t r, size_t nr, EWeight& eweight,
                            OStats&, Graph& g)
    {
        if (r == nr)
            return 0;
534

535
        double S_b = 0, S_a = 0;
536

537
538
        int kin = in_degreeS()(v, g, eweight);
        int kout = out_degreeS()(v, g, eweight);
539

540
541
542
543
544
545
546
        auto get_Se = [&](size_t s, int delta, int kin, int kout) -> double
            {
                double S = 0;
                S += get_xi_fast(_total[s] + delta, _em[s] + kin);
                S += get_xi_fast(_total[s] + delta, _ep[s] + kout);
                return S;
            };
547

548
549
        S_b += get_Se(r,  0,    0,     0) + get_Se(nr, 0,   0,    0);
        S_a += get_Se(r, -1, -kin, -kout) + get_Se(nr, 1, kin, kout);
550

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
        auto get_Sr = [&](size_t s, int delta) -> double
            {
                return lgamma_fast(_total[s] + delta + 1);
            };

        S_b += get_Sr(r,  0) + get_Sr(nr, 0);
        S_a += get_Sr(r, -1) + get_Sr(nr, 1);


        auto get_Sk = [&](size_t s, pair<size_t, size_t>& deg, int delta) -> double
            {
                size_t nd = 0;
                auto iter = _hist[s].find(deg);
                if (iter != _hist[s].end())
                    nd = iter->second;

                return -lgamma_fast(nd + delta + 1);
            };

        auto deg = make_pair(size_t(kin), size_t(kout));
        S_b += get_Sk(r, deg,  0) + get_Sk(nr, deg, 0);
        S_a += get_Sk(r, deg, -1) + get_Sk(nr, deg, 1);
573
574
575
576

        return S_a - S_b;
    }

577
    template <class Graph, class OStats, class EWeight>
578
    void move_vertex(size_t v, size_t r, size_t nr, bool deg_corr, OStats&,
579
580
                     Graph& g, EWeight& eweight, size_t kin = 0,
                     size_t kout = 0)
581
582
583
584
585
586
587
    {
        if (r == nr)
            return;

        _total[r]--;
        _total[nr]++;

588
589
590
591
592
        if (_total[r] == 0)
            _actual_B--;
        if (_total[nr] == 1)
            _actual_B++;

593
594
        if (deg_corr)
        {
595
596
            if (kin + kout == 0)
            {
597
598
                kin = in_degreeS()(v, g, eweight);
                kout = out_degreeS()(v, g, eweight);
599
600
            }
            auto deg = make_pair(kin, kout);
601
602
603
604
605
606
607
608
609
610
611
612
613
            auto iter = _hist[r].find(deg);
            iter->second--;
            if (iter->second == 0)
                _hist[r].erase(iter);
            _hist[nr][deg]++;
            _em[r] -= deg.first;
            _ep[r] -= deg.second;
            _em[nr] += deg.first;
            _ep[nr] += deg.second;
        }
    }

    bool is_enabled() { return _enabled; }
614
    void set_enabled(bool enabled) { _enabled = enabled; }
615
616
617
618

private:
    bool _enabled;
    size_t _N;
619
    size_t _E;
620
    size_t _B;
621
    size_t _actual_B;
622
623
624
625
    vector<map_t> _hist;
    vector<int> _total;
    vector<int> _ep;
    vector<int> _em;
626
    bool _edges_dl;
627
};
628

629
630
631
632
// ===============================
// Block moves
// ===============================

633
634
// this structure speeds up the access to the edges between given blocks,
// since we're using an adjacency list to store the block structure (the emat_t
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// is simply a corresponding adjacency matrix)
struct get_emat_t
{
    template <class Graph>
    struct apply
    {
        typedef multi_array<pair<typename graph_traits<Graph>::edge_descriptor, bool>, 2> type;
    };
};


struct create_emat
{
    template <class Graph>
649
    void operator()(Graph& g, boost::any& oemap) const
650
651
    {
        typedef typename get_emat_t::apply<Graph>::type emat_t;
652
        size_t B = num_vertices(g);
653
654
655
656
657
        emat_t emat(boost::extents[B][B]);

        for (size_t i = 0; i < B; ++i)
            for (size_t j = 0; j < B; ++j)
                emat[i][j].second = false;
658
        for (auto e : edges_range(g))
659
        {
660
            if (source(e, g) >= B || target(e, g) >= B)
661
                throw GraphException("incorrect number of blocks when creating emat!");
662
            emat[source(e, g)][target(e, g)] = make_pair(e, true);
663
            if (!is_directed::apply<Graph>::type::value)
664
                emat[target(e, g)][source(e, g)] = make_pair(e, true);
665
666
667
668
669
670
        }

        oemap = emat;
    }
};

671
672
673
674
675
template <class Graph>
inline __attribute__((always_inline))
pair<typename graph_traits<Graph>::edge_descriptor, bool>
get_me(typename graph_traits<Graph>::vertex_descriptor r,
       typename graph_traits<Graph>::vertex_descriptor s,
676
       const typename get_emat_t::apply<Graph>::type& emat, const Graph&)
677
678
679
680
681
682
683
684
685
686
{
    return emat[r][s];
}

template <class Graph>
inline __attribute__((always_inline))
void
put_me(typename graph_traits<Graph>::vertex_descriptor r,
       typename graph_traits<Graph>::vertex_descriptor s,
       const typename graph_traits<Graph>::edge_descriptor& e,
687
       typename get_emat_t::apply<Graph>::type& emat, const Graph&)
688
689
690
691
692
693
694
695
696
697
698
{
    emat[r][s] = make_pair(e, true);
    if (!is_directed::apply<Graph>::type::value && r != s)
        emat[s][r] = make_pair(e, true);
}

template <class Graph>
inline __attribute__((always_inline))
void
remove_me(typename graph_traits<Graph>::vertex_descriptor r,
          typename graph_traits<Graph>::vertex_descriptor s,
699
700
          const typename graph_traits<Graph>::edge_descriptor&,
          typename get_emat_t::apply<Graph>::type& emat, Graph&,
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
          bool delete_edge=true)
{
    if (!delete_edge)
    {
        emat[r][s].second = false;
        if (!is_directed::apply<Graph>::type::value && r != s)
            emat[s][r].second = false;
    }
}


// this structure speeds up the access to the edges between given blocks, since
// we're using an adjacency list to store the block structure (this is like
// emat_t above, but takes less space and is slower)
struct get_ehash_t
{
    template <class Graph>
    struct apply
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
        typedef typename graph_traits<Graph>::edge_descriptor edge_t;
#ifdef HAVE_SPARSEHASH
723
        typedef dense_hash_map<vertex_t, edge_t, std::hash<vertex_t>> map_t;
724
725
726
727
728
729
730
731
732
733
734
735
736
#else
        typedef unordered_map<vertex_t, edge_t> map_t;
#endif
        typedef vector<map_t> type;
    };
};


template<class Graph>
inline __attribute__((always_inline))
pair<typename graph_traits<Graph>::edge_descriptor, bool>
get_me(typename graph_traits<Graph>::vertex_descriptor r,
       typename graph_traits<Graph>::vertex_descriptor s,
737
       const typename get_ehash_t::apply<Graph>::type& ehash, const Graph&)
738
{
739
    assert(r < ehash.size());
740
741
    const auto& map = ehash[r];
    auto iter = map.find(s);
742
743
744
745
746
747
748
749
750
751
752
753
    if (iter == map.end())
        return (make_pair(typename graph_traits<Graph>::edge_descriptor(), false));
    return make_pair(iter->second, true);
}

template<class Graph>
inline __attribute__((always_inline))
void
put_me(typename graph_traits<Graph>::vertex_descriptor r,
       typename graph_traits<Graph>::vertex_descriptor s,
       const typename graph_traits<Graph>::edge_descriptor& e,
       typename get_ehash_t::apply<Graph>::type& ehash,
754
       const Graph&)
755
{
756
    assert(r < ehash.size());
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    ehash[r][s] = e;
    if (!is_directed::apply<Graph>::type::value)
        ehash[s][r] = e;
}

template<class Graph>
inline __attribute__((always_inline))
void
remove_me(typename graph_traits<Graph>::vertex_descriptor r,
          typename graph_traits<Graph>::vertex_descriptor s,
          const typename graph_traits<Graph>::edge_descriptor& e,
          typename get_ehash_t::apply<Graph>::type& ehash, Graph& bg,
          bool delete_edge=true)
{
771
    assert(r < ehash.size());
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
    ehash[r].erase(s);
    if (!is_directed::apply<Graph>::type::value)
        ehash[s].erase(r);
    if (delete_edge)
        remove_edge(e, bg);
}

struct create_ehash
{
    template <class Graph>
    void operator()(Graph& g, boost::any& oemap) const
    {
        typedef typename get_ehash_t::apply<Graph>::type emat_t;
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

        emat_t emat(num_vertices(g));

#ifdef HAVE_SPARSEHASH
790
        for (auto v : vertices_range(g))
791
        {
792
            emat[v].set_empty_key(numeric_limits<vertex_t>::max());
793
            emat[v].set_deleted_key(numeric_limits<vertex_t>::max() - 1);
794
795
796
        }
#endif

797
798
        for (auto e : edges_range(g))
            put_me(source(e, g), target(e, g), e, emat, g);
799

800
801
802
803
#ifdef HAVE_SPARSEHASH
        for (auto v : vertices_range(g))
            emat[v].resize(0);
#endif
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
        oemap = emat;
    }
};

template <class Vertex, class Eprop, class Emat, class BGraph>
__attribute__((always_inline))
inline size_t get_mrs(Vertex r, Vertex s, const Eprop& mrs, Emat& emat,
                      BGraph& bg)
{
    const pair<typename graph_traits<BGraph>::edge_descriptor, bool> me =
        get_me(r, s, emat, bg);
    if (me.second)
        return mrs[me.first];
    else
        return 0;
}

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
struct standard_neighbours_policy
{
    template <class Graph, class Vertex>
    IterRange<typename out_edge_iteratorS<Graph>::type>
    get_out_edges(Vertex v, Graph& g) const
    {
        return out_edges_range(v, g);
    }

    template <class Graph, class Vertex>
    IterRange<typename in_edge_iteratorS<Graph>::type>
    get_in_edges(Vertex v, Graph& g) const
    {
        return in_edges_range(v, g);
    }

    template <class Graph, class Vertex, class Weight>
    int get_out_degree(Vertex& v, Graph& g, Weight& eweight) const
    {
        return out_degreeS()(v, g, eweight);
    }

    template <class Graph, class Vertex, class Weight>
    int get_in_degree(Vertex& v, Graph& g, Weight& eweight) const
    {
        return in_degreeS()(v, g, eweight);
    }
};

850
851
// remove a vertex from its current block
template <class Graph, class BGraph, class Eprop, class Vprop, class EWprop,
852
853
          class VWprop, class EMat, class OStats,
          class NPolicy = standard_neighbours_policy>
854
855
void remove_vertex(size_t v, Eprop& mrs, Vprop& mrp, Vprop& mrm, Vprop& wr,
                   Vprop& b, const EWprop& eweight, const VWprop& vweight,
856
                   Graph& g, BGraph& bg, EMat& emat, OStats& overlap_stats,
857
                   const NPolicy& npolicy = NPolicy())
858
859
860
861
{
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
    vertex_t r = b[v];

862
    int self_weight = 0;
863
    for (auto e : npolicy.get_out_edges(v, g))
864
    {
865
        vertex_t u = target(e, g);
866
867
        vertex_t s = b[u];

868
869
870
        // if (!emat[r][s].second)
        //     throw GraphException("no edge? " + lexical_cast<string>(r) +
        //                          " " + lexical_cast<string>(s));
871

872
        auto me = get_me(r, s, emat, bg).first;
873

874
        size_t ew = eweight[e];
875
876
877
878
879
880
881
882
883
884
885
886
        if (u == v && !is_directed::apply<Graph>::type::value)
        {
            self_weight += ew;
        }
        else
        {
            mrs[me] -= ew;

            assert(mrs[me] >= 0);

            mrp[r] -= ew;
            mrm[s] -= ew;
887

888
889
890
891
            if (mrs[me] == 0)
                remove_me(r, s, me, emat, bg);
        }
    }
892

893
894
895
896
897
898
899
900
    if (self_weight > 0)
    {
        assert(self_weight % 2 == 0);
        auto me = get_me(r, r, emat, bg).first;
        mrs[me] -= self_weight / 2;
        mrp[r] -= self_weight / 2;
        mrm[r] -= self_weight / 2;
        assert(mrs[me] >= 0);
901
        if (mrs[me] == 0)
902
            remove_me(r, r, me, emat, bg);
903
904
    }

905
    for (auto e : npolicy.get_in_edges(v, g))
906
    {
907
908
909
910
        vertex_t u = source(e, g);
        if (u == v)
            continue;
        vertex_t s = b[u];
911

912
913
914
        // if (!emat[s][r].second)
        //     throw GraphException("no edge? " + lexical_cast<string>(s) +
        //                          " " + lexical_cast<string>(r));
915

916
917
        typename graph_traits<BGraph>::edge_descriptor me =
            get_me(s, r, emat, bg).first;
918

919
920
        size_t ew = eweight[e];
        mrs[me] -= ew;
921

922
923
        mrp[s] -= ew;
        mrm[r] -= ew;
924

925
926
        if (mrs[me] == 0)
            remove_me(s, r, me, emat, bg);
927
928
    }

929
930
931
932
933
934
    if (!overlap_stats.is_enabled())
    {
        wr[r] -= vweight[v];
    }
    else
    {
935
        overlap_stats.remove_half_edge(v, r, b, g);
936
937
        wr[r] = overlap_stats.get_block_size(r);
    }
938
939
940
941
}

// add a vertex to block rr
template <class Graph, class BGraph, class Eprop, class Vprop, class EWprop,
942
943
          class VWprop, class EMat, class OStats,
          class NPolicy = standard_neighbours_policy>
944
void add_vertex(size_t v, size_t r, Eprop& mrs, Vprop& mrp, Vprop& mrm,
945
                Vprop& wr, Vprop& b, const EWprop& eweight,
946
947
                const VWprop& vweight, Graph& g, BGraph& bg, EMat& emat,
                OStats& overlap_stats, const NPolicy& npolicy = NPolicy())
948
949
950
{
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

951
    int self_weight = 0;
952
    for (auto e : npolicy.get_out_edges(v, g))
953
    {
954
        vertex_t u = target(e, g);
955
956
957
958
959
960
961
962
963
        vertex_t s;

        if (u != v)
            s = b[u];
        else
            s = r;

        typename graph_traits<BGraph>::edge_descriptor me;

964
        auto mep = get_me(r, s, emat, bg);
965
966
967

        if (!mep.second)
        {
968
969
970
            mep = add_edge(r, s, bg);
            put_me(r, s, mep.first, emat, bg);
            mrs[mep.first] = 0;
971
        }
972
        me = mep.first;
973

974
        size_t ew = eweight[e];
975

976
977
978
979
980
981
982
983
984
985
986
        if (u == v && !is_directed::apply<Graph>::type::value)
        {
            self_weight += ew;
        }
        else
        {
            mrs[me] += ew;
            mrp[r] += ew;
            mrm[s] += ew;
        }
    }
987

988
989
990
991
992
993
994
995
    if (self_weight > 0)
    {
        assert(self_weight % 2 == 0);
        auto me = get_me(r, r, emat, bg).first;
        mrs[me] += self_weight / 2;
        mrp[r] += self_weight / 2;
        mrm[r] += self_weight / 2;
        assert(mrs[me] >= 0);
996
997
    }

998
    for (auto e : npolicy.get_in_edges(v, g))
999
    {
1000
        vertex_t u = source(e, g);
1001
1002
1003
1004
1005
1006
        if (u == v)
            continue;

        vertex_t s = b[u];

        typename graph_traits<BGraph>::edge_descriptor me;
1007
1008
1009
        pair<typename graph_traits<BGraph>::edge_descriptor, bool> mep =
                get_me(s, r, emat, bg);

1010
1011
1012

        if (!mep.second)
        {
1013
1014
1015
            mep = add_edge(s, r, bg);
            put_me(s, r, mep.first, emat, bg);
            mrs[mep.first] = 0;
1016
        }
1017
        me = mep.first;
1018

1019
        size_t ew = eweight[e];
1020
1021
1022
1023
1024
1025
1026

        mrs[me] += ew;

        mrp[s] += ew;
        mrm[r] += ew;
    }

1027
1028
1029
1030
1031
1032
    if (!overlap_stats.is_enabled())
    {
        wr[r] += vweight[v];
    }
    else
    {
1033
        overlap_stats.add_half_edge(v, r, b, g);
1034
1035
1036
        wr[r] = overlap_stats.get_block_size(r);
    }

1037
1038
1039
    b[v] = r;
}

1040

1041
1042
// move a vertex from its current block to block nr
template <class Graph, class BGraph, class Eprop, class Vprop, class EWprop,
1043
          class VWprop, class EMat, class OStats, class PStats, class Vec,
1044
          class NPolicy = standard_neighbours_policy>
1045
void move_vertex(const Vec& vs, size_t nr, Eprop& mrs, Vprop& mrp, Vprop& mrm,
1046
                 Vprop& wr, Vprop& b, bool deg_corr, const EWprop& eweight,
1047
1048
1049
                 const VWprop& vweight, Graph& g, BGraph& bg, EMat& emat,
                 OStats& overlap_stats,  PStats& partition_stats,
                 const NPolicy& npolicy = NPolicy())
1050
{
1051
    if (b[vs[0]] == int(nr))
1052
1053
        return;

1054
1055
1056
    size_t kin = 0, kout = 0;
    for (auto v : vs)
    {
1057
1058
        kin += in_degreeS()(v, g, eweight);
        kout += out_degreeS()(v, g, eweight);
1059
1060
    }

1061
    if (partition_stats.is_enabled())
1062
        partition_stats.move_vertex(vs[0], b[vs[0]], nr, deg_corr, overlap_stats,
1063
                                    g, eweight, kin, kout);
1064
1065
1066
1067
1068
1069
1070
1071
1072

    for (auto v : vs)
    {
        remove_vertex(v, mrs, mrp, mrm, wr, b, eweight, vweight, g, bg, emat,
                      overlap_stats, npolicy);
        add_vertex(v, nr, mrs, mrp, mrm, wr, b, eweight, vweight, g, bg, emat,
                   overlap_stats, npolicy);
    }
}
1073

1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
template <class Graph, class BGraph, class Eprop, class Vprop, class EWprop,
          class VWprop, class EMat, class OStats, class PStats,
          class NPolicy = standard_neighbours_policy>
void move_vertex(size_t v, size_t nr, Eprop& mrs, Vprop& mrp, Vprop& mrm,
                 Vprop& wr, Vprop& b, bool deg_corr, const EWprop& eweight,
                 const VWprop& vweight, Graph& g, BGraph& bg, EMat& emat,
                 OStats& overlap_stats, PStats& partition_stats,
                 const NPolicy& npolicy = NPolicy())
{
    std::array<size_t, 1> vs = {v};
    move_vertex(vs, nr, mrs, mrp, mrm, wr, b, deg_corr, eweight, vweight, g, bg,
                emat, overlap_stats, partition_stats, npolicy);
1086
1087
}

1088
1089
1090
1091

template <class Type1, class Type2, class Graph>
__attribute__((always_inline))
inline pair<Type1,Type2> make_ordered_pair(const Type1& v1, const Type2& v2, const Graph&)
1092
{
1093
    if (!is_directed::apply<Graph>::type::value)
1094
    {
1095
1096
1097
1098
        if (v1 < v2)
            return make_pair(v1, v2);
        else
            return make_pair(v2, v1);
1099
    }
1100
    return make_pair(v1, v2);
1101
1102
}

1103
1104
template <class Graph>
class EntrySet
1105
{
1106
public:
1107
    EntrySet() {}
1108
    EntrySet(size_t B)
1109
    {
1110
1111
1112
1113
1114
1115
1116
1117
1118
        _null = numeric_limits<size_t>::max();
        _r_field_t.resize(B, _null);
        _nr_field_t.resize(B, _null);

        if (is_directed::apply<Graph>::type::value)
        {
            _r_field_s.resize(B, _null);
            _nr_field_s.resize(B, _null);
        }
1119
1120
        _entries.reserve(B);
        _delta.reserve(B);
1121
1122
    }

1123
1124
    __attribute__((always_inline))
    void set_move(size_t r, size_t nr)
1125
    {
1126
        _rnr = make_pair(r, nr);
1127
1128
    }

1129
1130
    __attribute__((always_inline))
    void insert_delta(size_t r, size_t s, int delta, bool source)
1131
    {
1132
        if (s == _rnr.first || s == _rnr.second)
1133
        {
1134
1135
1136
1137
            if ((!is_directed::apply<Graph>::type::value && s < r) || source)
                std::swap(r, s);
            if (source)
                source = false;
1138
        }
1139

1140
1141
        if (source && (s == r))
            source = false;
1142

1143
1144
        auto& r_field = (source) ? _r_field_s : _r_field_t;
        auto& nr_field = (source) ? _nr_field_s : _nr_field_t;
1145

1146
        vector<size_t>& field = (_rnr.first == r) ? r_field : nr_field;
1147
1148
1149
        if (field[s] == _null)
        {
            field[s] = _entries.size();
1150
1151
1152
1153
            if ((!is_directed::apply<Graph>::type::value && s < r) || source)
                _entries.emplace_back(s, r);
            else
                _entries.emplace_back(r, s);
1154
1155
1156
1157
1158
1159
1160
1161
            _delta.push_back(delta);
        }
        else
        {
            _delta[field[s]] += delta;
        }
    }

1162
1163
    __attribute__((always_inline))
    int get_delta(size_t t, size_t s)
1164
1165
1166
1167
    {
        if (is_directed::apply<Graph>::type::value)
        {
            if (t == _rnr.first || t == _rnr.second)
1168
                return get_delta_target(t, s);
1169
            if (s == _rnr.first || s == _rnr.second)
1170
                return get_delta_source(t, s);
1171
1172
1173
1174
        }
        else
        {
            if (t == _rnr.first || t == _rnr.second)
1175
                return get_delta_target(t, s);
1176
            if (s == _rnr.first || s == _rnr.second)
1177
                return get_delta_target(s, t);
1178
1179
1180
1181
        }
        return 0;
    }

1182
1183
    __attribute__((always_inline))
    int get_delta_target(size_t r, size_t s)
1184
1185
1186
1187
1188
1189
1190
1191
    {
        vector<size_t>& field = (_rnr.first == r) ? _r_field_t : _nr_field_t;
        if (field[s] == _null)
            return 0;
        else
            return _delta[field[s]];
    }

1192
1193
    __attribute__((always_inline))
    int get_delta_source(size_t s, size_t r)
1194
1195
1196
1197
1198
1199
1200
1201
    {
        vector<size_t>& field = (_rnr.first == r) ? _r_field_s : _nr_field_s;
        if (field[s] == _null)
            return 0;
        else
            return _delta[field[s]];
    }

1202
1203
    __attribute__((always_inline))
    void clear()
1204
1205
1206
    {
        for (size_t i = 0; i < _entries.size(); ++i)
        {
1207
1208
            size_t r = _entries[i].first;
            size_t s = _entries[i].second;
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
            _r_field_t[r] = _nr_field_t[r] = _null;
            _r_field_t[s] = _nr_field_t[s] = _null;
            if (is_directed::apply<Graph>::type::value)
            {
                _r_field_s[r] = _nr_field_s[r] = _null;
                _r_field_s[s] = _nr_field_s[s] = _null;
            }
        }
        _entries.clear();
        _delta.clear();
    }