graph_blockmodel.hh 57.5 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
// 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_HH
#define GRAPH_BLOCKMODEL_HH

#include "config.h"

#include <vector>

#include "graph_state.hh"
#include "graph_blockmodel_util.hh"

namespace graph_tool
{
using namespace boost;
using namespace std;

typedef vprop_map_t<int32_t>::type vmap_t;
typedef eprop_map_t<int32_t>::type emap_t;
typedef UnityPropertyMap<int,GraphInterface::vertex_t> vcmap_t;
typedef UnityPropertyMap<int,GraphInterface::edge_t> ecmap_t;

38
39
40
41
42
43
template <class CMap>
CMap& uncheck(boost::any& amap, CMap*) { return any_cast<CMap&>(amap); }
vmap_t::unchecked_t uncheck(boost::any& amap, vmap_t::unchecked_t*);
emap_t::unchecked_t uncheck(boost::any& amap, emap_t::unchecked_t*);

typedef mpl::vector2<std::true_type, std::false_type> bool_tr;
44
typedef mpl::vector2<simple_degs_t, degs_map_t> degs_tr;
45
46
47
48
49
50
51
52
53
54
55
typedef mpl::vector2<vcmap_t, vmap_t> vweight_tr;
typedef mpl::vector2<ecmap_t, emap_t> eweight_tr;

enum weight_type
{
    NONE,
    POSITIVE,
    SIGNED,
    DELTA_T
};

56
57
58
59

#define BLOCK_STATE_params                                                     \
    ((g, &, all_graph_views, 1))                                               \
    ((degs,, degs_tr, 1))                                                      \
60
61
    ((is_weighted,, bool_tr, 1))                                               \
    ((use_hash,, bool_tr, 1))                                                  \
62
    ((_abg, &, boost::any&, 0))                                                \
63
64
    ((_aeweight, &, boost::any&, 0))                                           \
    ((_avweight, &, boost::any&, 0))                                           \
65
66
67
68
69
    ((mrs,, emap_t, 0))                                                        \
    ((mrp,, vmap_t, 0))                                                        \
    ((mrm,, vmap_t, 0))                                                        \
    ((wr,, vmap_t, 0))                                                         \
    ((b,, vmap_t, 0))                                                          \
70
71
72
73
    ((empty_blocks, & ,std::vector<size_t>&, 0))                               \
    ((empty_pos,, vmap_t, 0))                                                  \
    ((candidate_blocks, &, std::vector<size_t>&, 0))                           \
    ((candidate_pos,, vmap_t, 0))                                              \
74
75
76
77
    ((bclabel,, vmap_t, 0))                                                    \
    ((pclabel,, vmap_t, 0))                                                    \
    ((merge_map,, vmap_t, 0))                                                  \
    ((deg_corr,, bool, 0))                                                     \
78
79
80
81
82
83
84
85
86
87
88
89
    ((rec_type,, int, 0))                                                      \
    ((rec,, eprop_map_t<double>::type, 0))                                     \
    ((drec,, eprop_map_t<double>::type, 0))                                    \
    ((brec,, eprop_map_t<double>::type, 0))                                    \
    ((bdrec,, eprop_map_t<double>::type, 0))                                   \
    ((brecsum,, vprop_map_t<double>::type, 0))                                 \
    ((m0,, double, 0))                                                         \
    ((k0,, double, 0))                                                         \
    ((v0,, double, 0))                                                         \
    ((nu0,, double, 0))                                                        \
    ((alpha,, double, 0))                                                      \
    ((beta,, double, 0))                                                       \
90
91
    ((ignore_degrees,, typename vprop_map_t<uint8_t>::type, 0))                \
    ((allow_empty,, bool, 0))
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

GEN_STATE_BASE(BlockStateBase, BLOCK_STATE_params)

template <class... Ts>
class BlockState
    : public BlockStateBase<Ts...>
{
public:
    GET_PARAMS_USING(BlockStateBase<Ts...>, BLOCK_STATE_params)
    GET_PARAMS_TYPEDEF(Ts, BLOCK_STATE_params)

    template <class RNG, class... ATs,
              typename std::enable_if_t<sizeof...(ATs) == sizeof...(Ts)>* = nullptr>
    BlockState(RNG& rng, ATs&&... args)
        : BlockStateBase<Ts...>(std::forward<ATs>(args)...),
          _bg(boost::any_cast<std::reference_wrapper<bg_t>>(__abg)),
          _c_mrs(_mrs.get_checked()),
109
110
111
112
          _c_brec(_brec.get_checked()),
          _c_bdrec(_bdrec.get_checked()),
          _vweight(uncheck(__avweight, typename std::add_pointer<vweight_t>::type())),
          _eweight(uncheck(__aeweight, typename std::add_pointer<eweight_t>::type())),
113
114
          _emat(_g, _b, _bg, rng),
          _neighbour_sampler(get(vertex_index_t(), _g), num_vertices(_g)),
115
116
          _m_entries(num_vertices(_bg)),
          _coupled_state(nullptr)
117
    {
Tiago Peixoto's avatar
Tiago Peixoto committed
118
        rebuild_neighbour_sampler();
119
120
121
122
123
124
125
126
127
128
129
130
        _empty_blocks.clear();
        _candidate_blocks.clear();
        for (auto r : vertices_range(_bg))
        {
            if (_wr[r] == 0)
                add_element(_empty_blocks, _empty_pos, r);
            else
                add_element(_candidate_blocks, _candidate_pos, r);
        }
        if (!_empty_blocks.empty())
            add_element(_candidate_blocks, _candidate_pos,
                        _empty_blocks.back());
131
132
133
134
135
136
    }

    BlockState(const BlockState& other)
        : BlockStateBase<Ts...>(static_cast<const BlockStateBase<Ts...>&>(other)),
          _bg(boost::any_cast<std::reference_wrapper<bg_t>>(__abg)),
          _c_mrs(_mrs.get_checked()),
137
138
139
140
          _c_brec(_brec.get_checked()),
          _c_bdrec(_bdrec.get_checked()),
          _vweight(uncheck(__avweight, typename std::add_pointer<vweight_t>::type())),
          _eweight(uncheck(__aeweight, typename std::add_pointer<eweight_t>::type())),
141
142
          _emat(other._emat),
          _neighbour_sampler(other._neighbour_sampler),
143
144
          _m_entries(num_vertices(_bg)),
          _coupled_state(nullptr)
145
146
147
148
149
    {
        if (other.is_partition_stats_enabled())
            enable_partition_stats();
    }

150
151
152
153

    template <bool Add, class BEdge, class EFilt, class EOP>
    void modify_vertex(size_t v, size_t r, BEdge&& bedge, EFilt&& efilt,
                       EOP&& eop)
154
155
156
157
158
    {
        typedef typename graph_traits<g_t>::vertex_descriptor vertex_t;

        for (auto e : out_edges_range(v, _g))
        {
159
            if (efilt(e) || _eweight[e] == 0)
160
161
                continue;

162
163
164
            vertex_t u = target(e, _g);
            vertex_t s = _b[u];

165
            auto& me = bedge[e];
166

167
            if (Add)
168
            {
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
                if (me != _emat.get_null_edge())
                {
                    assert(u == v);
                    continue;
                }

                if (u == v)
                    s = r;

                me = _emat.get_me(r, s);
                if (me == _emat.get_null_edge())
                {
                    me = add_edge(r, s, _bg).first;
                    _emat.put_me(r, s, me);
                    _c_mrs[me] = 0;
                    _c_brec[me] = 0;
                    _c_bdrec[me] = 0;
                }

                assert(_emat.get_bedge(e) != _emat.get_null_edge());
189
190
191
            }
            else
            {
192
193
194
195
196
197
                if (me == _emat.get_null_edge())
                {
                    assert(u == v);
                    continue;
                }
            }
198

199
200
201
202
203
204
            assert(me != _emat.get_null_edge());
            assert(me == _emat.get_me(r, s));
            assert(std::min(source(me, _bg), target(me, _bg)) == std::min(r, s));
            assert(std::max(source(me, _bg), target(me, _bg)) == std::max(r, s));

            auto ew = _eweight[e];
205

206
207
208
209
210
211
212
213
214
215
            if (Add)
            {
                _mrs[me] += ew;
                _mrp[r] += ew;
                _mrm[s] += ew;
                eop(e, me);
            }
            else
            {
                _mrs[me] -= ew;
216
217
                _mrp[r] -= ew;
                _mrm[s] -= ew;
218
219
                eop(e, me);
                assert(_mrs[me] >= 0);
220
221
                if (_mrs[me] == 0)
                    _emat.remove_me(r, s, me, _bg);
222
                me = _emat.get_null_edge();
223
224
225
226
227
            }
        }

        for (auto e : in_edges_range(v, _g))
        {
228
229
230
            if (efilt(e))
                continue;

231
232
233
234
235
236
237
            vertex_t u = source(e, _g);
            if (u == v)
                continue;
            vertex_t s = _b[u];

            auto& me = _emat.get_bedge(e);

238
239
240
241
242
243
244
245
246
247
248
249
250
            if (Add)
            {
                me = _emat.get_me(s, r);
                if (me == _emat.get_null_edge())
                {
                    me = add_edge(s, r, _bg).first;
                    _emat.put_me(s, r, me);
                    _c_mrs[me] = 0;
                    _c_brec[me] = 0;
                    _c_bdrec[me] = 0;
                }
                assert(_emat.get_bedge(e) != _emat.get_null_edge());
            }
251

252
253
254
255
            assert(me != _emat.get_null_edge());
            assert(me == _emat.get_me(s, r));
            assert(std::min(source(me, _bg), target(me, _bg)) == std::min(r, s));
            assert(std::max(source(me, _bg), target(me, _bg)) == std::max(r, s));
256

257
            auto ew = _eweight[e];
Tiago Peixoto's avatar
Tiago Peixoto committed
258

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
            if (Add)
            {
                _mrs[me] += ew;
                _mrp[s] += ew;
                _mrm[r] += ew;
                eop(e, me);
            }
            else
            {
                _mrs[me] -= ew;
                _mrp[s] -= ew;
                _mrm[r] -= ew;
                eop(e, me);
                if (_mrs[me] == 0)
                    _emat.remove_me(s, r, me, _bg);
                me = _emat.get_null_edge();
            }
276
277
        }

278
279
280
281
282
283
284
285
        if (Add)
            add_partition_node(v, r);
        else
            remove_partition_node(v, r);
    }

    void remove_partition_node(size_t v, size_t r)
    {
286
287
288
289
290
291
        _wr[r] -= _vweight[v];

        if (!_egroups.empty())
            _egroups.remove_vertex(v, r, _g);

        if (is_partition_stats_enabled())
292
293
294
295
296
            get_partition_stats(v).remove_vertex(v, r, _deg_corr, _g,
                                                 _vweight, _eweight, _degs);

        if (_vweight[v] > 0 && _wr[r] == 0)
        {
297
298
299
300
            // Group became empty: Remove from candidate list, unless it is the
            // only empty group remaining.
            if (!_empty_blocks.empty() &&
                has_element(_candidate_blocks, _candidate_pos, r))
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
                remove_element(_candidate_blocks, _candidate_pos, r);
            add_element(_empty_blocks, _empty_pos, r);
        }
    }

    void add_partition_node(size_t v, size_t r)
    {
        _b[v] = r;
        _wr[r] += _vweight[v];

        if (!_egroups.empty())
            _egroups.add_vertex(v, r, _eweight, _g);

        if (is_partition_stats_enabled())
            get_partition_stats(v).add_vertex(v, r, _deg_corr, _g, _vweight,
                                              _eweight, _degs);
Tiago Peixoto's avatar
Tiago Peixoto committed
317

318
        if (_vweight[v] > 0 && _wr[r] == _vweight[v])
Tiago Peixoto's avatar
Tiago Peixoto committed
319
        {
320
321
            // Previously empty group became occupied: Remove from empty list
            // and add a new empty group to the candidate list (if available).
322
323
            remove_element(_empty_blocks, _empty_pos, r);

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
            if (has_element(_candidate_blocks, _candidate_pos, r))
            {
                if (!_empty_blocks.empty())
                {
                    auto s = _empty_blocks.back();
                    if (!has_element(_candidate_blocks, _candidate_pos, s))
                        add_element(_candidate_blocks, _candidate_pos, s);
                }
            }
            else
            {
                // if r is not a candidate in the first place (i.e. the move as
                // done by hand by the user), we need just to add it to the list
                add_element(_candidate_blocks, _candidate_pos, r);
            }
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
        }
    }

    template <class BEdge, class EFilt>
    void remove_vertex(size_t v, BEdge&& bedge, EFilt&& efilt)
    {
        size_t r = _b[v];
        switch (_rec_type)
        {
        case weight_type::POSITIVE: // positive weights
            modify_vertex<false>(v, r, bedge, efilt,
                                 [&](auto& e, auto& me)
                                 {
                                     this->_brec[me] -=  this->_rec[e];
                                 });
            break;
        case weight_type::SIGNED: // positive and negative weights
            modify_vertex<false>(v, r, bedge, efilt,
                                 [&](auto& e, auto& me)
                                 {
                                     this->_brec[me] -= this->_rec[e];
                                     this->_bdrec[me] -= this->_drec[e];
                                 });
            break;
        case weight_type::DELTA_T: // waiting times
Tiago Peixoto's avatar
Tiago Peixoto committed
364
365
            if (_ignore_degrees[v] > 0)
            {
366
367
368
                double dt = out_degreeS()(v, _g, _rec);
                auto r = _b[v];
                _brecsum[r] -= dt;
Tiago Peixoto's avatar
Tiago Peixoto committed
369
            }
370
371
        case weight_type::NONE: // no weights
            modify_vertex<false>(v, r, bedge, efilt, [](auto&, auto&){});
Tiago Peixoto's avatar
Tiago Peixoto committed
372
        }
373
374
    }

375
376
    void remove_vertex(size_t v)
    {
377
378
        remove_vertex(v, _emat.get_bedge_map(),
                      [](auto&){ return false; });
379
380
    }

381
382
    template <class Vlist, class EOP>
    void remove_vertices(Vlist& vs, EOP&& eop)
383
384
    {
        typedef typename graph_traits<g_t>::vertex_descriptor vertex_t;
385
        typedef typename graph_traits<g_t>::edge_descriptor edges_t;
386
387
388
389
390
391
392
393
394
395
396
397
398
399

        gt_hash_set<vertex_t> vset(vs.begin(), vs.end());

        gt_hash_set<edges_t> eset;
        for (auto v : vset)
        {
            for (auto e : all_edges_range(v, _g))
            {
                auto u = (source(e, _g) == v) ? target(e, _g) : source(e, _g);
                if (vset.find(u) != vset.end())
                    eset.insert(e);
            }
        }

400
        auto& bedge = _emat.get_bedge_map();
401
        for (auto v : vset)
402
403
            remove_vertex(v, bedge,
                          [&](auto& e) { return eset.find(e) != eset.end(); });
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421

        for (auto& e : eset)
        {
            vertex_t v = source(e, _g);
            vertex_t u = target(e, _g);
            vertex_t r = _b[v];
            vertex_t s = _b[u];

            auto& me = _emat.get_bedge(e);

            auto ew = _eweight[e];
            _mrs[me] -= ew;

            assert(_mrs[me] >= 0);

            _mrp[r] -= ew;
            _mrm[s] -= ew;

422
423
            eop(e, me);

424
425
426
427
428
            if (_mrs[me] == 0)
                _emat.remove_me(r, s, me, _bg);
        }
    }

429
430
    template <class Vec>
    void remove_vertices(Vec& vs)
431
    {
432
        switch (_rec_type)
433
        {
434
435
436
437
438
439
440
441
442
443
444
        case weight_type::POSITIVE: // positive weights
            remove_vertices(vs, [&](auto& e, auto& me)
                                { this->_brec[me] -=  this->_rec[e]; });
            break;
        case weight_type::SIGNED: // positive and negative weights
            remove_vertices(vs, [&](auto& e, auto& me)
                                { this->_brec[me] -= this->_rec[e];
                                  this->_bdrec[me] -= this->_drec[e];});
            break;
        case weight_type::DELTA_T: // waiting times
            for (auto v : vs)
445
            {
446
447
448
449
450
451
                if (_ignore_degrees[v] > 0)
                {
                    double dt = out_degreeS()(v, _g, _rec);
                    auto r = _b[v];
                    _brecsum[r] -= dt;
                }
452
            }
453
454
        case weight_type::NONE: // no weights
            remove_vertices(vs, [&](auto&, auto&) {});
455
        }
456
    }
457

458
459
460
461
462
463
    void remove_vertices(python::object ovs)
    {
        multi_array_ref<uint64_t, 1> vs = get_array<uint64_t, 1>(ovs);
        remove_vertices(vs);
    }

464
465
466
467
    template <class BEdge, class Efilt>
    void add_vertex(size_t v, size_t r, BEdge&& bedge, Efilt&& efilt)
    {
        switch (_rec_type)
Tiago Peixoto's avatar
Tiago Peixoto committed
468
        {
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
        case weight_type::POSITIVE: // positive weights
            modify_vertex<true>(v, r, bedge, efilt,
                                [&](auto& e, auto& me)
                                {
                                    this->_brec[me] +=  this->_rec[e];
                                });
            break;
        case weight_type::SIGNED: // positive and negative weights
            modify_vertex<true>(v, r, bedge, efilt,
                                [&](auto& e, auto& me)
                                {
                                    this->_brec[me] += this->_rec[e];
                                    this->_bdrec[me] += this->_drec[e];
                                });
            break;
        case weight_type::DELTA_T: // waiting times
Tiago Peixoto's avatar
Tiago Peixoto committed
485
486
            if (_ignore_degrees[v] > 0)
            {
487
488
                double dt = out_degreeS()(v, _g, _rec);
                _brecsum[r] += dt;
Tiago Peixoto's avatar
Tiago Peixoto committed
489
            }
490
491
        case weight_type::NONE: // no weights
            modify_vertex<true>(v, r, bedge, efilt, [](auto&, auto&){});
Tiago Peixoto's avatar
Tiago Peixoto committed
492
        }
493
494
    }

495
496
    void add_vertex(size_t v, size_t r)
    {
Tiago Peixoto's avatar
Tiago Peixoto committed
497
        add_vertex(v, r, _emat.get_bedge_map(),
498
                   [](auto&){ return false; });
499
500
    }

501
502
    template <class Vlist, class Blist, class EOP>
    void add_vertices(Vlist& vs, Blist& rs, EOP&& eop)
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
    {
        typedef typename graph_traits<g_t>::vertex_descriptor vertex_t;

        gt_hash_map<vertex_t, size_t> vset;
        for (size_t i = 0; i < vs.size(); ++i)
            vset[vs[i]] = rs[i];

        typedef typename graph_traits<g_t>::edge_descriptor edges_t;

        gt_hash_set<edges_t> eset;
        for (auto vr : vset)
        {
            auto v = vr.first;
            for (auto e : all_edges_range(v, _g))
            {
                auto u = (source(e, _g) == v) ? target(e, _g) : source(e, _g);
                if (vset.find(u) != vset.end())
                    eset.insert(e);
            }
        }

524
525
        auto bedge = _emat.get_bedge_map().get_checked();

526
        for (auto vr : vset)
527
            add_vertex(vr.first, vr.second, bedge,
528
                       [&](auto& e){ return eset.find(e) != eset.end(); });
529
530
531
532
533
534
535
536
537
538

        for (auto e : eset)
        {
            vertex_t v = source(e, _g);
            vertex_t u = target(e, _g);
            vertex_t r = vset[v];
            vertex_t s = vset[u];

            auto me = _emat.get_me(r, s);

539
            if (me == _emat.get_null_edge())
540
541
542
543
            {
                me = add_edge(r, s, _bg).first;
                _emat.put_me(r, s, me);
                _c_mrs[me] = 0;
544
545
                _c_brec[me] = 0;
                _c_bdrec[me] = 0;
546
547
            }

548
            bedge[e] = me;
549

550
            assert(_emat.get_bedge(e) != _emat.get_null_edge());
551
552
553
554
555
556
557
            assert(me == _emat.get_me(r, s));

            auto ew = _eweight[e];

            _mrs[me] += ew;
            _mrp[r] += ew;
            _mrm[s] += ew;
558
559

            eop(e, me);
560
561
562
        }
    }

563
564
    template <class Vs, class Rs>
    void add_vertices(Vs& vs, Rs& rs)
565
    {
566
567
        if (vs.size() != rs.size())
            throw ValueException("vertex and group lists do not have the same size");
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
        switch (_rec_type)
        {
        case weight_type::POSITIVE: // positive weights
            add_vertices(vs, rs, [&](auto& e, auto& me)
                                 { this->_brec[me] +=  this->_rec[e]; });
            break;
        case weight_type::SIGNED: // positive and negative weights
            add_vertices(vs, rs, [&](auto& e, auto& me)
                                 { this->_brec[me] += this->_rec[e];
                                   this->_bdrec[me] += this->_drec[e];});
            break;
        case weight_type::DELTA_T: // waiting times
            for (size_t i = 0; i < rs.size(); ++i)
            {
                auto v = vs[i];
                if (_ignore_degrees[v] > 0)
                {
                    double dt = out_degreeS()(v, _g, _rec);
                    auto r = rs[i];
                    _brecsum[r] += dt;
                }
            }
        case weight_type::NONE: // no weights
            add_vertices(vs, rs, [&](auto&, auto&) {});
        }
    }

595
    void add_vertices(python::object ovs, python::object ors)
596
    {
597
598
599
600
601
602
603
604
605
606
607
        multi_array_ref<uint64_t, 1> vs = get_array<uint64_t, 1>(ovs);
        multi_array_ref<uint64_t, 1> rs = get_array<uint64_t, 1>(ors);
        add_vertices(vs, rs);
    }

    bool allow_move(size_t r, size_t nr, bool allow_empty = true)
    {
        if (allow_empty)
            return ((_bclabel[r] == _bclabel[nr]) || (_wr[nr] == 0));
        else
            return ((_bclabel[r] == _bclabel[nr]));
608
609
    }

610
611
612
613
    // move a vertex from its current block to block nr
    void move_vertex(size_t v, size_t nr)
    {
        size_t r = _b[v];
614

615
616
        if (r == nr)
            return;
617
618

        if (!allow_move(r, nr))
619
            throw ValueException("cannot move vertex across clabel barriers");
620

621
622
        remove_vertex(v);
        add_vertex(v, nr);
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

        if (_coupled_state != nullptr && _vweight[v] > 0)
        {
            if (_wr[r] == 0)
            {
                _coupled_state->remove_partition_node(r, _bclabel[r]);
                _coupled_state->set_vertex_weight(r, 0);
            }

            if (_wr[nr] == _vweight[v])
            {
                _coupled_state->set_vertex_weight(nr, 1);
                _coupled_state->add_partition_node(nr, _bclabel[r]);
                _bclabel[nr] = _bclabel[r];
            }
        }
    }

    void set_vertex_weight(size_t v, int w)
    {
        set_vertex_weight(v, w, _vweight);
    }

    void set_vertex_weight(size_t, int, vcmap_t&)
    {
        throw ValueException("Cannot set the weight of an unweighted state");
    }

    template <class VMap>
    void set_vertex_weight(size_t v, int w, VMap&& vweight)
    {
        vweight[v] = w;
655
656
    }

657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
    template <class Vec>
    void move_vertices(Vec& v, Vec& nr)
    {
        for (size_t i = 0; i < std::min(v.size(), nr.size()); ++i)
            move_vertex(v[i], nr[i]);
    }

    void move_vertices(python::object ovs, python::object ors)
    {
        multi_array_ref<uint64_t, 1> vs = get_array<uint64_t, 1>(ovs);
        multi_array_ref<uint64_t, 1> rs = get_array<uint64_t, 1>(ors);
        if (vs.size() != rs.size())
            throw ValueException("vertex and group lists do not have the same size");
        move_vertices(vs, rs);
    }

673
674
675
676
677
678
679
680
681
682
683
684
685
    template <class VMap>
    void set_partition(VMap&& b)
    {
        for (auto v : vertices_range(_g))
            move_vertex(v, b[v]);
    }

    void set_partition(boost::any& ab)
    {
        vmap_t& b = boost::any_cast<vmap_t&>(ab);
        set_partition<typename vmap_t::unchecked_t>(b.get_unchecked());
    }

686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
    size_t virtual_remove_size(size_t v)
    {
        return _wr[_b[v]] - _vweight[v];
    }

    // merge vertex u into v
    void merge_vertices(size_t u, size_t v)
    {
        typedef typename graph_traits<g_t>::edge_descriptor edge_t;
        UnityPropertyMap<int, edge_t> dummy;
        merge_vertices(u, v, dummy);
    }

    template <class Emap>
    void merge_vertices(size_t u, size_t v, Emap& ec)
    {
        if (u == v)
            return;
704
        merge_vertices(u, v, ec, _is_weighted);
705
706
    }

707
708
    template <class Emap>
    void merge_vertices(size_t, size_t, Emap&, std::false_type)
709
710
711
712
713
    {
        throw ValueException("cannot merge vertices of unweighted graph");
    }

    template <class Emap>
714
    void merge_vertices(size_t u, size_t v, Emap& ec, std::true_type)
715
716
717
    {
        auto eweight_c = _eweight.get_checked();
        auto bedge_c = _emat.get_bedge_map().get_checked();
718
719
        auto rec_c = _rec.get_checked();
        auto drec_c = _drec.get_checked();
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736

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

        gt_hash_map<std::tuple<vertex_t, int>, vector<edge_t>> ns_u, ns_v;
        for(auto e : out_edges_range(u, _g))
            ns_u[std::make_tuple(target(e, _g), ec[e])].push_back(e);
        for(auto e : out_edges_range(v, _g))
            ns_v[std::make_tuple(target(e, _g), ec[e])].push_back(e);

        for(auto& kv : ns_u)
        {
            vertex_t t = get<0>(kv.first);
            int l = get<1>(kv.first);
            auto& es = kv.second;

            size_t w = 0;
737
            double ecc = 0, decc = 0;
738
            for (auto& e : es)
739
            {
740
                w += _eweight[e];
741
742
743
                ecc += _rec[e];
                decc += _drec[e];
            }
744
745
746
747
748
749
750
751

            if (t == u)
            {
                t = v;
                if (!is_directed::apply<g_t>::type::value)
                {
                    assert(w % 2 == 0);
                    w /= 2;
752
753
                    ecc /= 2;
                    decc /= 2;
754
755
756
757
758
759
760
761
                }
            }

            auto iter = ns_v.find(std::make_tuple(t, l));
            if (iter != ns_v.end())
            {
                auto& e = iter->second.front();
                _eweight[e] += w;
762
763
                _rec[e] += ecc;
                _drec[e] += decc;
764
765
766
767
768
769
            }
            else
            {
                auto e = add_edge(v, t, _g).first;
                ns_v[std::make_tuple(t, l)].push_back(e);
                eweight_c[e] = w;
770
771
                rec_c[e] = ecc;
                drec_c[e] = decc;
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
                bedge_c[e] = bedge_c[es.front()];
                set_prop(ec, e, l);
            }
        }

        if (is_directed::apply<g_t>::type::value)
        {
            ns_u.clear();
            ns_v.clear();

            for(auto e : in_edges_range(v, _g))
                ns_v[std::make_tuple(source(e, _g), ec[e])].push_back(e);
            for(auto e : in_edges_range(u, _g))
                ns_u[std::make_tuple(source(e, _g), ec[e])].push_back(e);

            for(auto& kv : ns_u)
            {
                vertex_t s = get<0>(kv.first);
                int l = get<1>(kv.first);
                auto& es = kv.second;

                if (s == u)
                    continue;

                size_t w = 0;
797
                double ecc = 0, decc = 0;
798
                for (auto& e : es)
799
                {
800
                    w += _eweight[e];
801
802
803
                    ecc += _rec[e];
                    decc += _drec[e];
                }
804
805
806
807
808
809

                auto iter = ns_v.find(std::make_tuple(s, l));
                if (iter != ns_v.end())
                {
                    auto& e = iter->second.front();
                    _eweight[e] += w;
810
811
                    _rec[e] += ecc;
                    _drec[e] += decc;
812
813
814
815
816
817
                }
                else
                {
                    auto e = add_edge(s, v, _g).first;
                    ns_v[std::make_tuple(s, l)].push_back(e);
                    eweight_c[e] = w;
818
819
                    rec_c[e] = ecc;
                    drec_c[e] = decc;
820
821
822
823
824
825
826
827
828
                    bedge_c[e] = bedge_c[es.front()];
                    set_prop(ec, e, l);
                }
            }
        }

        _vweight[v] +=_vweight[u];
        _vweight[u] = 0;
        for (auto e : all_edges_range(u, _g))
829
        {
830
            _eweight[e] = 0;
831
832
833
            _rec[e] = 0;
            _drec[e] = 0;
        }
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
864
865
866
        clear_vertex(u, _g);
        _merge_map[u] = v;
        merge_degs(u, v, _degs);
    }

    template <class EMap, class Edge, class Val>
    void set_prop(EMap& ec, Edge& e, Val& val)
    {
        ec[e] = val;
    }

    template <class Edge, class Val>
    void set_prop(UnityPropertyMap<Val, Edge>&, Edge&, Val&)
    {
    }

    void merge_degs(size_t, size_t, const simple_degs_t&) {}

    void merge_degs(size_t u, size_t v, typename degs_map_t::unchecked_t& degs)
    {
        gt_hash_map<std::tuple<size_t, size_t>, size_t> hist;
        for (auto& kn : degs[u])
            hist[make_tuple(get<0>(kn), get<1>(kn))] += get<2>(kn);
        for (auto& kn : degs[v])
            hist[make_tuple(get<0>(kn), get<1>(kn))] += get<2>(kn);
        degs[u].clear();
        degs[v].clear();
        auto& d = degs[v];
        for (auto& kn : hist)
            d.emplace_back(get<0>(kn.first), get<1>(kn.first), kn.second);
    }

    template <class MEntries>
867
    void get_move_entries(size_t v, size_t r, size_t nr, MEntries& m_entries)
868
    {
869
870
871
872
873
        auto mv_entries = [&](auto&&... args)
            {
                move_entries(v, r, nr, _b, _emat.get_bedge_map(), _g, _bg,
                             m_entries, is_loop_nop(), _eweight, args...);
            };
874

875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
        switch (_rec_type)
        {
        case weight_type::POSITIVE: // positive weights
            mv_entries(_rec);
            break;
        case weight_type::SIGNED: // positive and negative weights
            mv_entries(_rec, _drec);
            break;
        default: // no weights
            mv_entries();
        }
    }

    // compute the entropy difference of a virtual move of vertex from block r
    // to nr
    template <bool exact, class MEntries>
    double virtual_move_sparse(size_t v, size_t r, size_t nr,
                               MEntries& m_entries)
    {
894
895
896
897
        if (r == nr)
            return 0.;

        m_entries.clear();
898
899
        get_move_entries(v, r, nr, m_entries);
        double dS = entries_dS<exact>(m_entries, _mrs, _emat, _bg);
900
901
902
903
904
905
906
907
908

        size_t kout = out_degreeS()(v, _g, _eweight);
        size_t kin = kout;
        if (is_directed::apply<g_t>::type::value)
            kin = in_degreeS()(v, _g, _eweight);

        int dwr = _vweight[v];
        int dwnr = dwr;

909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
        if (r == null_group && dwnr == 0)
            dwnr = 1;

        auto vt = [&](auto mrp, auto mrm, auto nr)
            {
                if (exact)
                    return vterm_exact(mrp, mrm, nr, _deg_corr, _bg);
                else
                    return vterm(mrp, mrm, nr, _deg_corr, _bg);
            };

        if (r != null_group)
        {
            dS += vt(_mrp[r]  - kout, _mrm[r]  - kin, _wr[r]  - dwr );
            dS -= vt(_mrp[r]        , _mrm[r]       , _wr[r]        );
        }

        if (nr != null_group)
        {
            dS += vt(_mrp[nr] + kout, _mrm[nr] + kin, _wr[nr] + dwnr);
            dS -= vt(_mrp[nr]       , _mrm[nr]      , _wr[nr]       );
        }
931
932
933
934

        return dS;
    }

935
936
    template <bool exact>
    double virtual_move_sparse(size_t v, size_t r, size_t nr)
937
    {
938
        return virtual_move_sparse<exact>(v, r, nr, _m_entries);
939
940
941
    }

    template <class MEntries>
942
    double virtual_move_dense(size_t v, size_t r, size_t nr, bool multigraph,
943
944
945
946
947
948
949
950
951
952
953
954
                              MEntries& m_entries)
    {
        if (_deg_corr)
            throw GraphException("Dense entropy for degree corrected model not implemented!");

        typedef typename graph_traits<g_t>::vertex_descriptor vertex_t;

        if (r == nr)
            return 0;

        // m_entries is not used in the computation below, but it is expected afterwards
        m_entries.clear();
955
956
        get_move_entries(v, r, nr, m_entries);

957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
        int kin = 0, kout = 0;
        kout += out_degreeS()(v, _g, _eweight);
        if (is_directed::apply<g_t>::type::value)
            kin += in_degreeS()(v, _g, _eweight);

        vector<int> deltap(num_vertices(_bg), 0);
        int deltal = 0;
        for (auto e : out_edges_range(v, _g))
        {
            vertex_t u = target(e, _g);
            vertex_t s = _b[u];
            if (u == v)
                deltal += _eweight[e];
            else
                deltap[s] += _eweight[e];
        }
        if (!is_directed::apply<g_t>::type::value)
            deltal /= 2;

        vector<int> deltam(num_vertices(_bg), 0);
        for (auto e : in_edges_range(v, _g))
        {
            vertex_t u = source(e, _g);
            if (u == v)
                continue;
            vertex_t s = _b[u];
            deltam[s] += _eweight[e];
        }

        double dS = 0;
        int dwr = _vweight[v];
        int dwnr = dwr;

990
991
992
993
994
995
996
997
998
999
        if (r == null_group && dwnr == 0)
            dwnr = 1;

        if (nr == null_group)
        {
            std::fill(deltap.begin(), deltap.end(), 0);
            std::fill(deltam.begin(), deltam.end(), 0);
            deltal = 0;
        }

1000
        double Si = 0, Sf = 0;