graph_blockmodel_partition.hh 19.4 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-2018 Tiago de Paula Peixoto <tiago@skewed.de>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
// 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_PARTITION_HH
#define GRAPH_BLOCKMODEL_PARTITION_HH

#include "../support/util.hh"
#include "../support/int_part.hh"

namespace graph_tool
{

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

constexpr size_t null_group = std::numeric_limits<size_t>::max();

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, class F>
39
__attribute__((always_inline)) __attribute__((flatten)) inline
40
41
42
43
44
45
46
void degs_op(size_t v, Vprop& vweight, Eprop& eweight, const simple_degs_t&,
             Graph& g, F&& f)
{
    f(in_degreeS()(v, g, eweight), out_degreeS()(v, g, eweight), vweight[v]);
}

template <class Graph, class Vprop, class Eprop, class F>
47
__attribute__((always_inline)) __attribute__((flatten)) inline
48
void degs_op(size_t v, Vprop& vweight, Eprop& eweight,
49
             const typename degs_map_t::unchecked_t& degs, Graph& g, F&& f)
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
129
130
131
132
133
134
135
136
137
138
139
{
    auto& ks = degs[v];
    if (ks.empty())
    {
        degs_op(v, vweight, eweight, simple_degs_t(), g, std::forward<F>(f));
    }
    else
    {
        for (auto& k : ks)
            f(get<0>(k), get<1>(k), get<2>(k));
    }
}

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,
                      bool allow_empty)
        : _bmap(bmap), _N(0), _E(E), _total_B(B), _allow_empty(allow_empty)
    {
        for (auto v : vlist)
        {
            if (vweight[v] == 0)
                continue;

            auto r = get_r(b[v]);
            if (v >= _ignore_degree.size())
                _ignore_degree.resize(v + 1, 0);
            _ignore_degree[v] = ignore_degree[v];

            degs_op(v, vweight, eweight, degs, g,
                    [&](auto kin, auto kout, auto n)
                    {
                        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;
        if (_allow_empty)
            S += lbinom(_total_B + _N - 1, _N);
        else
            S += lbinom(_N - 1, _actual_B - 1);
        S += lgamma_fast(_N + 1);
        for (auto nr : _total)
            S -= lgamma_fast(nr + 1);
140
        S += safelog_fast(_N);
141
142
143
        return S;
    }

144
    double get_deg_dl_ent(auto&& rs, auto&& ks)
145
146
    {
        double S = 0;
147
        for (auto r : rs)
148
        {
149
            r = get_r(r);
150
            size_t total = 0;
151
            if (ks.empty())
152
            {
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
                for (auto& k_c : _hist[r])
                {
                    S -= xlogx_fast(k_c.second);
                    total += k_c.second;
                }
            }
            else
            {
                auto& h = _hist[r];
                for (auto& k : ks)
                {
                    auto iter = h.find(k);
                    auto k_c = (iter != h.end()) ? iter->second : 0;
                    S -= xlogx(k_c);
                }
                total = _total[r];
169
            }
170
            S += xlogx_fast(total);
171
172
173
174
        }
        return S;
    }

175
    double get_deg_dl_uniform(auto&& rs, auto&&)
176
177
    {
        double S = 0;
178
        for (auto r : rs)
179
        {
180
            r = get_r(r);
181
182
183
184
185
186
            S += lbinom(_total[r] + _ep[r] - 1, _ep[r]);
            S += lbinom(_total[r] + _em[r] - 1, _em[r]);
        }
        return S;
    }

187
    double get_deg_dl_dist(auto&& rs, auto&& ks)
188
189
    {
        double S = 0;
190
        for (auto r : rs)
191
        {
192
            r = get_r(r);
193
194
195
196
            S += log_q(_ep[r], _total[r]);
            S += log_q(_em[r], _total[r]);

            size_t total = 0;
197
            if (ks.empty())
198
            {
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
                for (auto& k_c : _hist[r])
                {
                    S -= lgamma_fast(k_c.second + 1);
                    total += k_c.second;
                }
            }
            else
            {
                auto& h = _hist[r];
                for (auto& k : ks)
                {
                    auto iter = h.find(k);
                    auto k_c = (iter != h.end()) ? iter->second : 0;
                    S -= lgamma_fast(k_c + 1);
                }
                total = _total[r];
215
216
217
218
219
220
            }
            S += lgamma_fast(total + 1);
        }
        return S;
    }

221
    double get_deg_dl(int kind, auto&& rs, auto&& ks)
222
223
224
225
    {
        switch (kind)
        {
        case deg_dl_kind::ENT:
226
            return get_deg_dl_ent(rs, ks);
227
        case deg_dl_kind::UNIFORM:
228
            return get_deg_dl_uniform(rs, ks);
229
        case deg_dl_kind::DIST:
230
            return get_deg_dl_dist(rs, ks);
231
232
233
234
235
        default:
            return numeric_limits<double>::quiet_NaN();
        }
    }

236
237
238
239
240
241
242
243
244
245
246
247
248
    double get_deg_dl(int kind)
    {
        return get_deg_dl(kind, boost::counting_range(size_t(0), _total_B),
                          std::array<std::pair<size_t,size_t>,0>());
    }

    template <class Graph>
    double get_edges_dl(size_t B, Graph& g)
    {
        size_t BB = (graph_tool::is_directed(g)) ? B * B : (B * (B + 1)) / 2;
        return lbinom(BB + _E - 1, _E);
    }

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
    template <class VProp>
    double get_delta_partition_dl(size_t v, size_t r, size_t nr, VProp& vweight)
    {
        if (r == nr)
            return 0;

        if (r != null_group)
            r = get_r(r);

        if (nr != null_group)
            nr = get_r(nr);

        int n = vweight[v];
        if (n == 0)
        {
            if (r == null_group)
                n = 1;
            else
                return 0;
        }

        double S_b = 0, S_a = 0;

        if (r != null_group)
        {
            S_b += -lgamma_fast(_total[r] + 1);
            S_a += -lgamma_fast(_total[r] - n + 1);
        }

        if (nr != null_group)
        {
            S_b += -lgamma_fast(_total[nr] + 1);
            S_a += -lgamma_fast(_total[nr] + n + 1);
        }

        int dN = 0;
        if (r == null_group)
            dN += n;
        if (nr == null_group)
            dN -= n;

        S_b += lgamma_fast(_N + 1);
        S_a += lgamma_fast(_N + dN + 1);

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

        if ((dN != 0 || dB != 0) && !_allow_empty)
        {
            S_b += lbinom_fast(_N - 1, _actual_B - 1);
            S_a += lbinom_fast(_N - 1 + dN, _actual_B + dB - 1);
        }

        if (dN != 0)
        {
307
308
            S_b += safelog_fast(_N);
            S_a += safelog_fast(_N + dN);
309
310
311
312
313
314
315
        }

        return S_a - S_b;
    }

    template <class VProp, class Graph>
    double get_delta_edges_dl(size_t v, size_t r, size_t nr, VProp& vweight,
316
                              size_t actual_B, Graph& g)
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
    {
        if (r == nr || _allow_empty)
            return 0;

        if (r != null_group)
            r = get_r(r);
        if (nr != null_group)
            nr = get_r(nr);

        double S_b = 0, S_a = 0;

        int n = vweight[v];

        if (n == 0)
        {
            if (r == null_group)
                n = 1;
            else
                return 0;
        }

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

        if (dB != 0)
        {
346
347
            S_b += get_edges_dl(actual_B, g);
            S_a += get_edges_dl(actual_B + dB, g);
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
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
        }

        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, int kind)
    {
        if (r == nr || _ignore_degree[v] == 1 || vweight[v] == 0)
            return 0;
        if (r != null_group)
            r = get_r(r);
        if (nr != null_group)
            nr = get_r(nr);

        auto dop =
            [&](auto&& f)
            {
                if (_ignore_degree[v] == 2)
                {
                    degs_op(v, vweight, eweight, degs, g,
                            [&](auto kin, auto, auto n)
                            {
                                f(kin, 0, n);
                            });
                }
                else
                {
                    degs_op(v, vweight, eweight, degs, g,
                            [&](auto... k) { f(k...); });
                }
            };

        double dS = 0;
        switch (kind)
        {
        case deg_dl_kind::ENT:
            if (r != null_group)
                dS += get_delta_deg_dl_ent_change(r,  dop, -1);
            if (nr != null_group)
                dS += get_delta_deg_dl_ent_change(nr, dop, +1);
            break;
        case deg_dl_kind::UNIFORM:
            if (r != null_group)
                dS += get_delta_deg_dl_uniform_change(v, r,  dop, -1);
            if (nr != null_group)
                dS += get_delta_deg_dl_uniform_change(v, nr, dop, +1);
            break;
        case deg_dl_kind::DIST:
            if (r != null_group)
                dS += get_delta_deg_dl_dist_change(v, r,  dop, -1);
            if (nr != null_group)
                dS += get_delta_deg_dl_dist_change(v, nr, dop, +1);
            break;
        default:
            dS = numeric_limits<double>::quiet_NaN();
        }
        return dS;
    }

    template <class DegOP>
    double get_delta_deg_dl_ent_change(size_t r, DegOP&& dop, int diff)
    {
        int nr = _total[r];
        auto 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);
420
                return -xlogx_fast(nd + delta);
421
422
423
424
425
426
427
428
429
430
431
432
433
            };

        double S_b = 0, S_a = 0;
        int dn = 0;

        dop([&](size_t kin, size_t kout, int nk)
            {
                dn += diff * nk;
                auto deg = make_pair(kin, kout);
                S_b += get_Sk(r, deg,         0);
                S_a += get_Sk(r, deg, diff * nk);
            });

434
435
        S_b += xlogx_fast(nr);
        S_a += xlogx_fast(nr + dn);
436
437
438
439
440
441
442
443
444
445
446

        return S_a - S_b;
    }

    template <class DegOP>
    double get_delta_deg_dl_uniform_change(size_t v, size_t r, DegOP&& dop,
                                           int diff)
    {
        auto get_Se = [&](int dn, int dkin, int dkout)
            {
                double S = 0;
447
448
                S += lbinom_fast(_total[r] + dn + _ep[r] - 1 + dkout, _ep[r] + dkout);
                S += lbinom_fast(_total[r] + dn + _em[r] - 1 + dkin,  _em[r] + dkin);
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
                return S;
            };

        double S_b = 0, S_a = 0;
        int tkin = 0, tkout = 0, n = 0;
        dop([&](auto kin, auto kout, int nk)
            {
                tkin += kin * nk;
                if (_ignore_degree[v] != 2)
                    tkout += kout * nk;
                n += nk;
            });

        S_b += get_Se(       0,           0,            0);
        S_a += get_Se(diff * n, diff * tkin, diff * tkout);
        return S_a - S_b;
    }

    template <class DegOP>
    double get_delta_deg_dl_dist_change(size_t v, size_t r, DegOP&& dop,
                                        int diff)
    {
        auto get_Se = [&](int delta, int kin, int kout)
            {
                double S = 0;
                assert(_total[r] + delta >= 0);
                assert(_em[r] + kin >= 0);
                assert(_ep[r] + kout >= 0);
                S += log_q(_em[r] + kin, _total[r] + delta);
                S += log_q(_ep[r] + kout, _total[r] + delta);
                return S;
            };

        auto get_Sr = [&](int delta)
            {
                assert(_total[r] + delta + 1 >= 0);
                return lgamma_fast(_total[r] + delta + 1);
            };

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

        double S_b = 0, S_a = 0;
        int tkin = 0, tkout = 0, n = 0;
        dop([&](size_t kin, size_t kout, int nk)
            {
                tkin += kin * nk;
                if (_ignore_degree[v] != 2)
                    tkout += kout * nk;
                n += nk;

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

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

        S_b += get_Sr(       0);
        S_a += get_Sr(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)
    {
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
        int vw = vweight[v];
        int dv = vw * diff;

        if (_total[r] == 0 && dv > 0)
            _actual_B++;

        if (_total[r] == vw && dv < 0)
            _actual_B--;

        _total[r] += dv;
        _N += dv;

        assert(_total[r] >= 0);

        if (deg_corr && _ignore_degree[v] != 1)
        {
            degs_op(v, vweight, eweight, degs, g,
                    [&](auto kin, auto kout, auto n)
                    {
                        int dk = diff * n;
                        if (_ignore_degree[v] == 2)
                            kout = 0;
                        auto& h = _hist[r];
                        auto deg = make_pair(kin, kout);
                        auto iter = h.insert({deg, 0}).first;
                        iter->second += dk;
                        if (iter->second == 0)
                            h.erase(iter);
                        _em[r] += dk * deg.first;
                        _ep[r] += dk * deg.second;
                    });
        }
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
    }

    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)
    {
        if (r == null_group || vweight[v] == 0)
            return;
        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)
    {
        if (nr == null_group || vweight[v] == 0)
            return;
        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++;

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

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

        assert(_total[r] >= 0);

        if (deg_corr && _ignore_degree[v] != 1)
        {
            if (_ignore_degree[v] == 2)
                kout = 0;
            auto deg = make_pair(kin, kout);
599
600
601
602
            auto iter = _hist[r].insert({deg, 0}).first;
            iter->second += diff * vweight;
            if (iter->second == 0)
                _hist[r].erase(iter);
603
604
605
606
607
            _em[r] += diff * deg.first * vweight;
            _ep[r] += diff * deg.second * vweight;
        }
    }

608
609
610
611
612
    void change_E(int dE)
    {
        _E += dE;
    }

613
614
615
616
617
    size_t get_N()
    {
        return _N;
    }

618
619
620
621
622
    size_t get_E()
    {
        return _E;
    }

623
624
625
626
627
628
629
630
631
632
    size_t get_actual_B()
    {
        return _actual_B;
    }

    void add_block()
    {
        _total_B++;
    }

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
    template <class Graph, class VProp, class VWeight, class EWeight, class Degs>
    bool check_degs(Graph& g, VProp& b, VWeight& vweight, EWeight& eweight, Degs& degs)
    {
        vector<map_t> dhist;
        for (auto v : vertices_range(g))
        {
            degs_op(v, vweight, eweight, degs, g,
                    [&](auto kin, auto kout, auto n)
                    {
                        auto r = get_r(b[v]);
                        if (r >= dhist.size())
                            dhist.resize(r + 1);
                        dhist[r][{kin, kout}] += n;
                    });
        }

        for (size_t r = 0; r < dhist.size(); ++r)
        {
            for (auto& kn : dhist[r])
            {
                auto count = (r >= _hist.size()) ? 0 : _hist[r][kn.first];
                if (kn.second != count)
                {
                    assert(false);
                    return false;
                }
            }
        }

        for (size_t r = 0; r < _hist.size(); ++r)
        {
            for (auto& kn : _hist[r])
            {
                auto count = (r >= dhist.size()) ? 0 : dhist[r][kn.first];
                if (kn.second != count)
                {
                    assert(false);
                    return false;
                }
            }
        }

        return true;
    }
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

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

} //namespace graph_tool
#endif // GRAPH_BLOCKMODEL_PARTITION_HH