graph_blockmodel_util.hh 36.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
125
126
127
128
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2016 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 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_UTIL_HH
#define GRAPH_BLOCKMODEL_UTIL_HH

#include "config.h"

#include <tuple>

#include "hash_map_wrap.hh"

#include "../generation/sampler.hh"
#include "../generation/dynamic_sampler.hh"

#include "util.hh"
#include "cache.hh"

#include <boost/multi_array.hpp>

#ifdef USING_OPENMP
#include <omp.h>
#endif

namespace graph_tool
{

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


// Sparse entropy terms
// ====================

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

    double val = xlogx(mrs);

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

// "vertex" term of the entropy
template <class Graph>
inline double vterm(size_t mrp, size_t mrm, size_t wr, bool deg_corr,
                    Graph&)
{
    double one = 0.5;

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

    if (deg_corr)
        return one * (xlogx(mrm) + xlogx(mrp));
    else
        return one * (mrm * safelog(wr) + mrp * safelog(wr));
}

// Dense entropy
// =============

// "edge" term of the entropy
template <class Graph>
inline double eterm_dense(size_t r, size_t s, int ers, double wr_r,
                          double wr_s, bool multigraph, const Graph&)
{
    // we should not use integers here, since they may overflow
    double nrns;

    if (ers == 0)
        return 0.;

    if (r != s || is_directed::apply<Graph>::type::value)
    {
        nrns = wr_r * wr_s;
    }
    else
    {
        if (multigraph)
            nrns = (wr_r * (wr_r + 1)) / 2;
        else
            nrns = (wr_r * (wr_r - 1)) / 2;
    }

    double S;
    if (multigraph)
        S = lbinom(nrns + ers - 1, ers); // do not use lbinom_fast!
    else
        S = lbinom(nrns, ers);
    return S;
}

// ===============
// Partition stats
// ===============

typedef vprop_map_t<std::vector<std::tuple<size_t, size_t, size_t>>>::type
    degs_map_t;

struct simple_degs_t {};

template <class Graph, class Vprop, class Eprop>
auto get_degs(size_t v, Vprop& vweight, Eprop& eweight, const simple_degs_t&,
              Graph& g)
{
    std::array<std::tuple<size_t, size_t, size_t>, 1>
129
130
131
        degs {{make_tuple(size_t(in_degreeS()(v, g, eweight)),
                          size_t(out_degreeS()(v, g, eweight)),
                          size_t(vweight[v]))}};
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    return degs;
}

template <class Graph, class Vprop, class Eprop>
auto& get_degs(size_t v, Vprop&, Eprop&, typename degs_map_t::unchecked_t& degs,
               Graph&)
{
    return degs[v];
}

class partition_stats_t
{
public:

    typedef gt_hash_map<pair<size_t,size_t>, int> map_t;

    template <class Graph, class Vprop, class VWprop, class Eprop, class Degs,
              class Mprop, class Vlist>
    partition_stats_t(Graph& g, Vprop& b, Vlist& vlist, size_t E, size_t B,
                      VWprop& vweight, Eprop& eweight, Degs& degs,
                      const Mprop& ignore_degree, std::vector<size_t>& bmap)
        : _bmap(bmap)
    {
        _N = 0;
        _E = E;
        _total_B = B;

        for (auto v : vlist)
        {
            auto r = get_r(b[v]);

            auto&& ks = get_degs(v, vweight, eweight, degs, g);
            if (v >= _ignore_degree.size())
                _ignore_degree.resize(v + 1, 0);
            _ignore_degree[v] = ignore_degree[v];
            for (auto& k : ks)
            {
                size_t kin = get<0>(k);
                size_t kout = get<1>(k);
                size_t n = get<2>(k);
                if (_ignore_degree[v] == 2)
                    kout = 0;
                if (_ignore_degree[v] != 1)
                {
                    _hist[r][make_pair(kin, kout)] += n;
                    _em[r] += kin * n;
                    _ep[r] += kout * n;
                }
                _total[r] += n;
                _N += n;
            }
        }

        _actual_B = 0;
        for (auto n : _total)
        {
            if (n > 0)
                _actual_B++;
        }
    }

    size_t get_r(size_t r)
    {
        constexpr size_t null =
            std::numeric_limits<size_t>::max();
        if (r >= _bmap.size())
            _bmap.resize(r + 1, null);
        size_t nr = _bmap[r];
        if (nr == null)
            nr = _bmap[r] = _hist.size();
        if (nr >= _hist.size())
        {
            _hist.resize(nr + 1);
            _total.resize(nr + 1);
            _ep.resize(nr + 1);
            _em.resize(nr + 1);
        }
        return nr;
    }

    double get_partition_dl()
    {
        double S = 0;
        S += lbinom(_actual_B + _N - 1, _N);
        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 < _ep.size(); ++r)
        {
            if (_ep[r] + _em[r] == 0)
                continue;

            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 VProp>
    double get_delta_dl(size_t v, size_t r, size_t nr, VProp& vweight)
    {
        if (r == nr)
            return 0;
        r = get_r(r);
        nr = get_r(nr);
        int n = vweight[v];

        if (n == 0)
            return 0;

        double S_b = 0, S_a = 0;

        S_b += -lgamma_fast(_total[r] + 1);
        S_a += -lgamma_fast(_total[r] - n + 1);
        S_b += -lgamma_fast(_total[nr] + 1);
        S_a += -lgamma_fast(_total[nr] + n + 1);

        int dB = 0;
        if (_total[r] == n)
            dB--;
        if (_total[nr] == 0)
            dB++;

        if (dB != 0)
        {
            S_b += lbinom(_actual_B + _N - 1, _N);
            S_a += lbinom(_actual_B + dB + _N - 1, _N);
        }

        return S_a - S_b;
    }

    template <class Graph, class VProp>
    double get_delta_edges_dl(size_t v, size_t r, size_t nr, VProp& vweight,
                              Graph&)
    {
        if (r == nr)
            return 0;

        r = get_r(r);
        nr = get_r(nr);

        double S_b = 0, S_a = 0;

        int n = vweight[v];

        if (n == 0)
            return 0;

        int dB = 0;
        if (_total[r] == n)
            dB--;
        if (_total[nr] == 0)
            dB++;

        if (dB != 0)
        {
            auto get_x = [](size_t B)
                {
                    if (is_directed::apply<Graph>::type::value)
                        return B * B;
                    else
                        return (B * (B + 1)) / 2;
                };

            S_b += lbinom(get_x(_total_B) + _E - 1, _E);
            S_a += lbinom(get_x(_total_B + dB) + _E - 1, _E);
        }

        return S_a - S_b;
    }

    template <class Graph, class VProp, class EProp, class Degs>
    double get_delta_deg_dl(size_t v, size_t r, size_t nr, VProp& vweight,
                            EProp& eweight, Degs& degs, Graph& g)
    {
        if (r == nr || _ignore_degree[v] == 1)
            return 0;
        r = get_r(r);
        nr = get_r(nr);
        auto&& ks = get_degs(v, vweight, eweight, degs, g);
356
357
358
359
360
361
362
363
364
        auto* _ks = &ks;
        typename std::remove_reference<decltype(ks)>::type nks;
        if (_ignore_degree[v] == 2)
        {
            nks = ks;
            for (auto& k : nks)
                get<1>(k) = 0;
            _ks = &nks;
        }
365
        double dS = 0;
366
367
        dS += get_delta_deg_dl_change(v, r,  *_ks, -1);
        dS += get_delta_deg_dl_change(v, nr, *_ks, +1);
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
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
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
711
712
713
714
715
716
717
        return dS;
    }

    double get_Se (size_t s, int delta, int kin, int kout)
    {
        double S = 0;
        assert(_total[s] + delta >= 0);
        assert(_em[s] + kin >= 0);
        assert(_ep[s] + kout >= 0);
        S += get_xi_fast(_total[s] + delta, _em[s] + kin);
        S += get_xi_fast(_total[s] + delta, _ep[s] + kout);
        return S;
    };

    double get_Sr(size_t s, int delta)
    {
        assert(_total[s] + delta + 1 >= 0);
        return lgamma_fast(_total[s] + delta + 1);
    };

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


    template <class Ks>
    double get_delta_deg_dl_change(size_t v, size_t r, Ks& ks, int diff)
    {
        double S_b = 0, S_a = 0;
        int tkin = 0, tkout = 0, n = 0;
        for (auto& k : ks)
        {
            size_t kin = get<0>(k);
            size_t kout = get<1>(k);
            int nk = get<2>(k);
            tkin += kin * nk;
            if (_ignore_degree[v] != 2)
                tkout += kout * nk;
            n += nk;

            auto deg = make_pair(kin, kout);
            S_b += get_Sk(r, deg,         0);
            S_a += get_Sk(r, deg, diff * nk);
        }

        S_b += get_Se(r,        0,           0,            0);
        S_a += get_Se(r, diff * n, diff * tkin, diff * tkout);

        S_b += get_Sr(r,        0);
        S_a += get_Sr(r, diff * n);

        return S_a - S_b;
    }

    template <class Graph, class VWeight, class EWeight, class Degs>
    void change_vertex(size_t v, size_t r, bool deg_corr, Graph& g,
                       VWeight& vweight, EWeight& eweight, Degs& degs,
                       int diff)
    {
        auto&& ks = get_degs(v, vweight, eweight, degs, g);
        for (auto& k : ks)
        {
            auto kin = get<0>(k);
            auto kout = get<1>(k);
            auto n = get<2>(k);
            change_k(v, r, deg_corr, n, kin, kout, diff);
        }
    }

    template <class Graph, class VWeight, class EWeight, class Degs>
    void remove_vertex(size_t v, size_t r, bool deg_corr, Graph& g,
                       VWeight& vweight, EWeight& eweight, Degs& degs)
    {
        r = get_r(r);
        change_vertex(v, r, deg_corr, g, vweight, eweight, degs, -1);
    }

    template <class Graph, class VWeight, class EWeight, class Degs>
    void add_vertex(size_t v, size_t nr, bool deg_corr, Graph& g,
                    VWeight& vweight, EWeight& eweight, Degs& degs)
    {
        nr = get_r(nr);
        change_vertex(v, nr, deg_corr, g, vweight, eweight, degs, 1);
    }

    void change_k(size_t v, size_t r, bool deg_corr, int vweight,
                  int kin, int kout, int diff)
    {
        if (_total[r] == 0 && diff * vweight > 0)
        {
            _actual_B++;
            _total_B++;
        }

        if (_total[r] == vweight && diff * vweight < 0)
        {
            _actual_B--;
            _total_B--;
        }

        _total[r] += diff * vweight;
        _N += diff * vweight;

        if (deg_corr && _ignore_degree[v] != 1)
        {
            if (_ignore_degree[v] == 2)
                kout = 0;
            auto deg = make_pair(kin, kout);
            _hist[r][deg] += diff * vweight;
            _em[r] += diff * deg.first * vweight;
            _ep[r] += diff * deg.second * vweight;
        }
    }

private:
    vector<size_t>& _bmap;
    size_t _N;
    size_t _E;
    size_t _actual_B;
    size_t _total_B;
    vector<map_t> _hist;
    vector<int> _total;
    vector<int> _ep;
    vector<int> _em;
    vector<uint8_t> _ignore_degree;
};

// ===============================
// Block moves
// ===============================

// this structure speeds up the access to the edges between given blocks, since
// we're using an adjacency list to store the block structure (it is simply an
// adjacency matrix)

template <class Graph, class BGraph>
class EMat
{
public:
    template <class Vprop, class RNG>
    EMat(Graph& g, Vprop b, BGraph& bg, RNG&)
        : _bedge(get(edge_index_t(), g), 0)
    {
        size_t B = num_vertices(bg);
        _mat.resize(boost::extents[B][B]);
        for (auto e : edges_range(bg))
        {
            _mat[source(e, bg)][target(e, bg)] = e;
            if (!is_directed::apply<BGraph>::type::value)
                _mat[target(e, bg)][source(e, bg)] = e;
        }

        auto bedge_c = _bedge.get_checked();
        for (auto e : edges_range(g))
        {
            auto r = b[source(e, g)];
            auto s = b[target(e, g)];
            bedge_c[e] = _mat[r][s];
        }
    }

    typedef typename graph_traits<BGraph>::vertex_descriptor vertex_t;
    typedef typename graph_traits<BGraph>::edge_descriptor edge_t;

    const auto& get_me(vertex_t r, vertex_t s) const
    {
        return _mat[r][s];
    }

    void put_me(vertex_t r, vertex_t s, const edge_t& e)
    {
        _mat[r][s] = e;
        if (!is_directed::apply<BGraph>::type::value && r != s)
            _mat[s][r] = e;
    }

    void remove_me(vertex_t r, vertex_t s, const edge_t& me, BGraph& bg,
                   bool delete_edge=false)
    {
        if (delete_edge)
        {
            _mat[r][s] = edge_t();
            if (!is_directed::apply<Graph>::type::value)
                _mat[s][r] = edge_t();
            remove_edge(me, bg);
        }
    }

    template <class Edge>
    auto& get_bedge(const Edge& e) { return _bedge[e]; }
    auto& get_bedge_map() { return _bedge; }
    const auto& get_bedge_map() const { return _bedge; }
    const auto& get_null_edge() const { return _null_edge; }

private:
    multi_array<edge_t, 2> _mat;
    typedef typename property_map_type::apply
        <edge_t,
         typename property_map<Graph,
                               edge_index_t>::type>::type bedge_t;
    typename bedge_t::unchecked_t _bedge;
    static const edge_t _null_edge;
};

template <class Graph, class BGraph>
const typename EMat<Graph, BGraph>::edge_t EMat<Graph, BGraph>::_null_edge;


template <class Key>
class perfect_hash_t
{
public:
    template <class RNG>
    perfect_hash_t(size_t N, RNG& rng)
        : _index(std::make_shared<std::vector<size_t>>())
    {
        auto& index = *_index;
        index.reserve(N);
        for (size_t i = 0; i < N; ++i)
            index.push_back(i);
        std::shuffle(index.begin(), index.end(), rng);
    }
    perfect_hash_t() {}
    size_t operator()(const Key& k) const {return (*_index)[k];}
private:
    std::shared_ptr<std::vector<size_t>> _index;
};

// 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 above, but takes less space and is slower)

template <class Graph, class BGraph>
class EHash
{
public:

    template <class Vprop, class RNG>
    EHash(Graph& g, Vprop b, BGraph& bg, RNG& rng)
        : _hash_function(num_vertices(bg), rng),
          _hash(num_vertices(bg), ehash_t(0, _hash_function)),
          _bedge(get(edge_index_t(), g), 0)
    {

        for (auto e : edges_range(bg))
            put_me(source(e, bg), target(e, bg), e);

        auto bedge_c = _bedge.get_checked();
        for (auto e : edges_range(g))
        {
            auto r = b[source(e, g)];
            auto s = b[target(e, g)];
            bedge_c[e] = get_me(r, s);
        }
    }

    typedef typename graph_traits<BGraph>::vertex_descriptor vertex_t;
    typedef typename graph_traits<BGraph>::edge_descriptor edge_t;

    const auto& get_me(vertex_t r, vertex_t s) const
    {
        auto& map = _hash[r];
        const auto& iter = map.find(s);
        if (iter == map.end())
            return _null_edge;
        return iter->second;
    }

    void put_me(vertex_t r, vertex_t s, const edge_t& e)
    {
        assert(r < _hash.size());
        _hash[r][s] = e;
        if (!is_directed::apply<Graph>::type::value)
            _hash[s][r] = e;
    }

    void remove_me(vertex_t r, vertex_t s, const edge_t& me, BGraph& bg,
                   bool delete_edge = true)
    {
        if (delete_edge)
        {
            assert(r < _hash.size());
            _hash[r].erase(s);
            if (!is_directed::apply<Graph>::type::value)
                _hash[s].erase(r);
            remove_edge(me, bg);
        }
    }

    template <class Edge>
    auto& get_bedge(const Edge& e) { return _bedge[e]; }
    auto& get_bedge_map() { return _bedge; }
    const auto& get_bedge_map() const { return _bedge; }
    const auto& get_null_edge() const { return _null_edge; }

private:
    perfect_hash_t<vertex_t> _hash_function;
    typedef gt_hash_map<vertex_t, edge_t, perfect_hash_t<vertex_t>> ehash_t;
    std::vector<ehash_t> _hash;
    typedef typename property_map_type::apply
        <edge_t,
         typename property_map<Graph,
                               edge_index_t>::type>::type bedge_t;
    typename bedge_t::unchecked_t _bedge;
    static const edge_t _null_edge;
};

template <class Graph, class BGraph>
const typename EHash<Graph, BGraph>::edge_t EHash<Graph, BGraph>::_null_edge;

template <class Vertex, class Eprop, class Emat>
inline size_t get_mrs(Vertex r, Vertex s, const Eprop& mrs, const Emat& emat)
{
    const auto& me = emat.get_me(r, s);
    if (me != emat.get_null_edge())
        return mrs[me];
    return 0;
}


// Manage a set of block pairs and corresponding edge counts that will be
// updated

template <class Graph>
class EntrySet
{
public:
    EntrySet(size_t B)
    {
        _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);
        }
    }

    void set_move(size_t r, size_t nr)
    {
        _rnr = make_pair(r, nr);
    }

718
    void insert_delta(size_t t, size_t s, int delta,
719
720
                      size_t mrs = numeric_limits<size_t>::max())
    {
721
722
723
724
725
726
727
728
        insert_delta(t, s, delta, mrs,
                     typename is_directed::apply<Graph>::type());
    }

    void insert_delta(size_t t, size_t s, int delta, size_t mrs, std::true_type)
    {
        bool src = false;
        if (t != _rnr.first && t != _rnr.second)
729
        {
730
731
            std::swap(t, s);
            src = true;
732
733
        }

734
        assert(t == _rnr.first || t == _rnr.second);
735

736
737
        auto& r_field = (src) ? _r_field_s : _r_field_t;
        auto& nr_field = (src) ? _nr_field_s : _nr_field_t;
738

739
        auto& field = (_rnr.first == t) ? r_field : nr_field;
740
741
742
        if (field[s] == _null)
        {
            field[s] = _entries.size();
743
744
            if (src)
                _entries.emplace_back(s, t);
745
            else
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
                _entries.emplace_back(t, s);
            _delta.push_back(delta);
            _mrs.push_back(mrs);
        }
        else
        {
            _delta[field[s]] += delta;
        }
    }

    void insert_delta(size_t t, size_t s, int delta, size_t mrs, std::false_type)
    {
        if (t > s)
            std::swap(t, s);
        if (t != _rnr.first && t != _rnr.second)
            std::swap(t, s);

        assert(t == _rnr.first || t == _rnr.second);

        auto& r_field = _r_field_t;
        auto& nr_field = _nr_field_t;

        auto& field = (_rnr.first == t) ? r_field : nr_field;
        if (field[s] == _null)
        {
            field[s] = _entries.size();
            _entries.emplace_back(t, s);
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
            _delta.push_back(delta);
            _mrs.push_back(mrs);
        }
        else
        {
            _delta[field[s]] += delta;
        }
    }

    int get_delta(size_t t, size_t s)
    {
        if (is_directed::apply<Graph>::type::value)
        {
            if (t == _rnr.first || t == _rnr.second)
                return get_delta_target(t, s);
            if (s == _rnr.first || s == _rnr.second)
                return get_delta_source(t, s);
790
            return 0;
791
792
793
        }
        else
        {
794
795
796
797
            if (t > s)
                std::swap(t, s);
            if (t != _rnr.first && t != _rnr.second)
                std::swap(t, s);
798
799
            if (t == _rnr.first || t == _rnr.second)
                return get_delta_target(t, s);
800
            return 0;
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
        }
    }

    int get_delta_target(size_t r, size_t s)
    {
        vector<size_t>& field = (_rnr.first == r) ? _r_field_t : _nr_field_t;
        if (field[s] == _null)
            return 0;
        else
            return _delta[field[s]];
    }

    int get_delta_source(size_t s, size_t r)
    {
        vector<size_t>& field = (_rnr.first == r) ? _r_field_s : _nr_field_s;
        if (field[s] == _null)
            return 0;
        else
            return _delta[field[s]];
    }

    void clear()
    {
        for (const auto& rs : _entries)
        {
            size_t r = rs.first;
            size_t s = rs.second;
            _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();
        _mrs.clear();
    }

    const vector<pair<size_t, size_t> >& get_entries() { return _entries; }
    const vector<int>& get_delta() { return _delta; }
843
    const vector<size_t>& get_mrs() { return _mrs; }
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932

private:
    static constexpr size_t _null = numeric_limits<size_t>::max();

    pair<size_t, size_t> _rnr;
    vector<size_t> _r_field_t;
    vector<size_t> _nr_field_t;
    vector<size_t> _r_field_s;
    vector<size_t> _nr_field_s;
    vector<pair<size_t, size_t> > _entries;
    vector<int> _delta;
    vector<size_t> _mrs;
};

template <class Graph>
constexpr size_t EntrySet<Graph>::_null;

struct is_loop_nop
{
    bool operator()(size_t) const { return false; }
};


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

// obtain the necessary entries in the e_rs matrix which need to be modified
// after the move
template <class Graph, class BGraph, class Vertex, class Vprop, class Eprop,
          class CEprop, class EBedge, class MEntries,
          class NPolicy = standard_neighbours_policy, class IL = is_loop_nop>
void move_entries(Vertex v, Vertex nr, Vprop& b, Eprop& eweights, CEprop& mrs,
                  EBedge& bedge, Graph& g, BGraph& bg, MEntries& m_entries,
                  const NPolicy& npolicy = NPolicy(), IL is_loop = IL())
{
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
    vertex_t r = b[v];

    m_entries.set_move(r, nr);

    remove_entries(v, r, b, eweights, mrs, bedge, g, bg, m_entries, npolicy,
                   is_loop);
    add_entries(v, nr, b, eweights, g, bg, m_entries, npolicy, is_loop);
}

template <class Graph, class BGraph, class Vertex, class Vprop, class Eprop,
          class CEprop, class EBedge, class MEntries,
          class NPolicy = standard_neighbours_policy, class IL = is_loop_nop>
void remove_entries(Vertex v, Vertex r, Vprop& b, Eprop& eweights, CEprop& mrs,
                    EBedge& bedge, Graph& g, BGraph&, MEntries& m_entries,
                    const NPolicy& npolicy = NPolicy(), IL is_loop = IL())
{
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
    int self_weight = 0;
    for (auto e : npolicy.get_out_edges(v, g))
    {
        vertex_t u = target(e, g);
        vertex_t s = b[u];
        int ew = eweights[e];
        //assert(ew > 0);

        const auto& me = bedge[e];

933
        m_entries.insert_delta(r, s, -ew, mrs[me]);
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954

        if (u == v || is_loop(v))
        {
            if (!is_directed::apply<Graph>::type::value)
                self_weight += ew;
        }
    }

    if (self_weight > 0 && self_weight % 2 == 0)
        m_entries.insert_delta(r, r, self_weight / 2, false);

    for (auto e : npolicy.get_in_edges(v, g))
    {
        vertex_t u = source(e, g);
        if (u == v)
            continue;
        vertex_t s = b[u];
        int ew = eweights[e];

        const auto& me = bedge[e];

955
        m_entries.insert_delta(s, r, -ew, mrs[me]);
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
    }
}

template <class Graph, class BGraph, class Vertex, class Vprop, class Eprop,
          class MEntries,  class NPolicy = standard_neighbours_policy,
          class IL = is_loop_nop>
void add_entries(Vertex v, Vertex nr, Vprop& b, Eprop& eweights, Graph& g,
                 BGraph&, MEntries& m_entries,
                 const NPolicy& npolicy = NPolicy(), IL is_loop = IL())
{
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
    int self_weight = 0;
    for (auto e : npolicy.get_out_edges(v, g))
    {
        vertex_t u = target(e, g);
        vertex_t s = b[u];
        int ew = eweights[e];
        //assert(ew > 0);

        if (u == v || is_loop(v))
        {
            s = nr;
            if (!is_directed::apply<Graph>::type::value)
                self_weight += ew;
        }
981
        m_entries.insert_delta(nr, s, +ew);
982
983
984
985
986
987
988
989
990
991
992
993
    }

    if (self_weight > 0 && self_weight % 2 == 0)
        m_entries.insert_delta(nr, nr, -self_weight / 2, false);

    for (auto e : npolicy.get_in_edges(v, g))
    {
        vertex_t u = source(e, g);
        if (u == v)
            continue;
        vertex_t s = b[u];
        int ew = eweights[e];
994
        m_entries.insert_delta(s, nr, +ew);
995
996
997
998
999
1000
    }
}


// obtain the entropy difference given a set of entries in the e_rs matrix
template <class MEntries, class Eprop, class EMat, class BGraph>