nested_blockmodel.py 45.8 KB
Newer Older
1
2
3
4
5
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2014 Tiago de Paula Peixoto <tiago@skewed.de>
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
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
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
#
# 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/>.

from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
    range = xrange

from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, PropertyMap
from .. stats import label_self_loops
import random
from numpy import *
import numpy
from scipy.optimize import fsolve, fminbound
import scipy.special
from collections import defaultdict
import copy
import heapq

from . blockmodel import *


class NestedBlockState(object):
    r"""This class encapsulates the nested block state of a given graph.

    This must be instantiated and used by functions such as :func:`nested_mcmc_sweep`.

    The instances of this class contain a data member called ``levels``, which
    is a list of :class:`~graph_tool.community.BlockState` instances, containing
    the entire nested hierarchy.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    eweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Edge weights (i.e. multiplicity).
    vweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex weights (i.e. multiplicity).
    bs : list of :class:`~graph_tool.PropertyMap` or :class:`~numpy.ndarray` instances (optional, default: ``None``)
        Initial block labels on the vertices, for each hierarchy level.
    Bs : list of ``int`` (optional, default: ``None``)
        Number of blocks for each hierarchy level.
    deg_corr : ``bool`` (optional, default: ``True``)
        If ``True``, the degree-corrected version of the blockmodel ensemble will
        be used in the bottom level, otherwise the traditional variant will be used.
    max_BE : ``int`` (optional, default: ``1000``)
        If the number of blocks exceeds this number, a sparse representation of
        the block graph is used, which is slightly less efficient, but uses less
        memory,
    """

    def __init__(self, g, eweight=None, vweight=None, bs=None,
                 Bs=None, deg_corr=True, max_BE=1000):
        L = len(Bs) if Bs is not None else len(bs)
        cg = g
        vcount = vweight
        ecount = eweight

        self.levels = []

        for i in range(L):
            Bl = Bs[i] if Bs is not None else None
            bl = None
            if bs is not None:
                if isinstance(bs[i], PropertyMap):
                    bl = cg.own_property(bs[i])
                else:
                    bl = cg.new_vertex_property("int")
                    bl.fa = bs[i]
            state = BlockState(cg, B=Bl, b=bl, eweight=ecount,
                               vweight=vcount,
                               deg_corr=deg_corr and i == 0,
                               max_BE=max_BE)
            self.levels.append(state)

            cg = state.bg
            vcount = None # no vweight for upper levels!
            ecount = state.mrs

    def __rebuild_level(self, l, bl=None, bmap=None):
        if bl is None:
            if l > 0:
                cg = self.levels[l - 1].bg
                ecount = self.levels[l - 1].mrs
                if bmap is not None: # translate b values
                    bl = cg.new_vertex_property("int")
                    bl.fa = bmap
                else:
                    bl = self.levels[l].b
                bl = cg.own_property(bl)
                state = BlockState(cg, b=bl, eweight=ecount,
                                   deg_corr=False, max_BE=self.levels[0].max_BE)
                if l < len(self.levels):
                    self.levels[l] = state
                else:
                    self.levels.append(state)
        else:
            cg = self.levels[l].g
            ecount = self.levels[l].eweight
            vcount = self.levels[l].vweight
            if isinstance(bl, PropertyMap):
                bl = cg.own_property(bl)
            else:
                b = cg.new_vertex_property("int")
                b.fa = bl
                bl = b
            state = BlockState(cg, b=bl, eweight=ecount, vweight=vcount,
                               deg_corr=self.levels[l].deg_corr,
                               max_BE=self.levels[0].max_BE)
            self.levels[l] = state
            if l == len(self.levels) - 1 and state.B > 1:
                self._NestedBlockState__rebuild_level(l + 1, bmap=zeros(state.B, dtype="int"))

    def __delete_level(self, l):
        if l == 0:
            raise ValueError("cannot delete level l=0")
        clabel = self.levels[l].b.copy()
        b = self.levels[l - 1].b.copy()
        assert(self.levels[l - 1].B == self.levels[l].N)
        libcommunity.vector_map(b.a, clabel.a)
        del self.levels[l]
        self._NestedBlockState__rebuild_level(l - 1, bl=b)
        assert(self.levels[l - 1].B == self.levels[l].N)

    def __duplicate_level(self, l):
        cg = self.levels[l].bg
        ecount = self.levels[l].mrs

        bstate = BlockState(cg,
                            B=cg.num_vertices(),
                            #b=cg.vertex_index.copy("int"),
                            eweight=ecount,
                            deg_corr=False,
                            max_BE=self.levels[l].max_BE)

        self.levels.insert(l + 1, bstate)
        assert(self.levels[l].B == self.levels[l + 1].N)


    def level_entropy(self, l, complete=False, random=False, dense=False,
                      multigraph=False):
        r"""Compute the description length of hierarchy level l.

        Parameters
        ----------
        l : ``int``
            Hierarchy level.
        complete : ``bool`` (optional, default: ``False``)
            If ``True``, the complete entropy will be returned, including constant
            terms not relevant to the block partition.
        random : ``bool`` (optional, default: ``False``)
            If ``True``, the entropy entropy corresponding to an equivalent random
            graph (i.e. no block partition) will be returned.
        dense : ``bool`` (optional, default: ``False``)
            If ``True``, the "dense" variant of the entropy will be computed.
        multigraph : ``bool`` (optional, default: ``False``)
            If ``True``, the multigraph entropy will be used. Only has an effect
            if ``dense == True``.
        """

        bstate = self.levels[l]
        B = bstate.B
        N = bstate.N
        nr = bstate.wr.a

        S = bstate.entropy(dl=False, dense=dense or l > 0,
                           multigraph=multigraph or l > 0,
                           complete=complete) + \
            partition_entropy(B=B, N=N, nr=nr) / bstate.E

        return S

    def entropy(self, complete=False, random=False, dense=False,
                multigraph=False):
        r"""Compute the description length of the entire hierarchy.

        Parameters
        ----------
        complete : ``bool`` (optional, default: ``False``)
            If ``True``, the complete entropy will be returned, including constant
            terms not relevant to the block partition.
        random : ``bool`` (optional, default: ``False``)
            If ``True``, the entropy entropy corresponding to an equivalent random
            graph (i.e. no block partition) will be returned.
        dense : ``bool`` (optional, default: ``False``)
            If ``True``, the "dense" variant of the entropy will be computed.
        multigraph : ``bool`` (optional, default: ``False``)
            If ``True``, the multigraph entropy will be used. Only has an effect
            if ``dense == True``.
        """

        S = 0
        for l in range(len(self.levels)):
            S += self.level_entropy(l, complete, random, dense, multigraph)
        if complete:
            if self.levels[0].deg_corr:
                g = self.levels[0].g
                S_seq = 0
                hist = defaultdict(int)
                for v in g.vertices():
                    hist[(v.in_degree(), v.out_degree())] += 1
                for k, v in hist.items():
                    p = v / float(g.num_vertices())
                    S_seq -= p * log(p)
                S_seq *= g.num_vertices()
                S += S_seq / self.levels[0].E
        return S

    def get_bstack(self):
        r"""Return the nested levels as individual graphs.

        This returns a list of :class:`~graph_tool.Graph` instances
        representing the inferred hierarchy at each level. Each graph has two
        internal vertex and edge property maps named "count" which correspond to
        the vertex and edge counts at the lower level, respectively. Additionally,
        an internal vertex property map named "b" specifies the block partition.
        """

        bstack = []
        for l, bstate in enumerate(self.levels):
            cg = bstate.g
            if l == 0:
                cg = GraphView(cg, skip_properties=True)
            cg.vp["b"] = bstate.b.copy()
            cg.ep["count"] = bstate.eweight
            bstack.append(cg)
            if bstate.N == 1:
                break
        if bstack[-1].num_vertices() > 1:
            cg = Graph(directed=bstack[-1].is_directed())
            cg.add_vertex()
            cg.vp["b"] = cg.new_vertex_property("int")
            e = cg.add_edge(0, 0)
            ew = cg.new_edge_property("int")
            ew[e] = self.levels[-1].E
            cg.ep["count"] = ew
            bstack.append(cg)
        return bstack


    def project_level(self, l):
        r"""Project the partition at level ``l`` onto the lowest level, and
        return the corresponding property map.
        """
        clabel = b = self.levels[l].b.copy()
        while l - 1 >= 0:
            clabel = b
            b = self.levels[l - 1].b.copy()
            libcommunity.vector_map(b.a, clabel.a)
            l -= 1
        return b


def nested_mcmc_sweep(state, beta=1., random_move=False, c=1., sequential=True,
                      verbose=False):
    r"""Performs a Markov chain Monte Carlo sweep on all levels of the hierarchy.

    Parameters
    ----------
    state : :class:`~graph_tool.community.NestedBlockState`
        The nested block state.
    beta : `float` (optional, default: `1.0`)
        The inverse temperature parameter :math:`\beta`.
    random_move : ``bool`` (optional, default: ``False``)
        If ``True``, the proposed moves will attempt to place the vertices in
        fully randomly-chosen blocks. If ``False``, the proposed moves will be
        chosen with a probability depending on the membership of the neighbours
        and the currently-inferred block structure.
    c : ``float`` (optional, default: ``1.0``)
        This parameter specifies how often fully random moves are attempted,
        instead of more likely moves based on the inferred block partition.
        For ``c == 0``, no fully random moves are attempted, and for ``c == inf``
        they are always attempted.
    sequential : ``bool`` (optional, default: ``True``)
        If ``True``, the move attempts on the vertices are done in sequential
        random order. Otherwise a total of `N` moves attempts are made, where
        `N` is the number of vertices, where each vertex can be selected with
        equal probability.
    verbose : ``bool`` (optional, default: ``False``)
        If ``True``, verbose information is displayed.

    Returns
    -------

    dS_moves : list of (``float``, ``int``) tuples
       The entropy difference (per edge) and number of accepted block membership
       moves after a full sweep for each level.


    Notes
    -----

    This algorithm performs a Markov chain Monte Carlo sweep on each level of the
    network, via the function :func:`~graph_tool.community.mcmc_sweep`.

    This algorithm has a worse-case complexity of :math:`O(E \times L)`, where
    :math:`E` is the number of edges in the network, and :math:`L` is the depth
    of the hierarchy.

    Examples
    --------
    .. testsetup:: nested_mcmc

       gt.seed_rng(42)
       np.random.seed(42)

    .. doctest:: nested_mcmc

       >>> g = gt.collection.data["polbooks"]
       >>> state = gt.NestedBlockState(g, Bs=[10, 5, 3, 2, 1], deg_corr=True)
       >>> ret = gt.nested_mcmc_sweep(state)
       >>> print(ret)
Tiago Peixoto's avatar
Tiago Peixoto committed
331
       [(-0.11881394061738723, 58), (0.0, 0), (0.0, 0), (-0.00108916046910437, 1), (0.0, 0)]
332
333
334
335

    References
    ----------

Tiago Peixoto's avatar
Tiago Peixoto committed
336
    .. [peixoto-efficient-2013] Tiago P. Peixoto, "Efficient Monte Carlo and greedy
337
       heuristic for the inference of stochastic block models", :arxiv:`1310.4378`.
Tiago Peixoto's avatar
Tiago Peixoto committed
338
    .. [peixoto-hierarchical-2013] Tiago P. Peixoto, "Hierarchical block structures and high-resolution
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
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
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
       model selection in large networks ", :arxiv:`1310.4377`.
    """

    rets = []
    for l, bstate in enumerate(state.levels):
        if verbose:
            print("Level:", l, "N:", bstate.N, "B:", bstate.B)
        ret = mcmc_sweep(bstate, beta=beta, c=c, dense = l > 0,
                         multigraph = l > 0,
                         sequential=sequential,
                         random_move=random_move, verbose=verbose)
        if l + 1 < len(state.levels):
            state._NestedBlockState__rebuild_level(l + 1)
        rets.append(ret)
    return rets


def replace_level(l, state, nsweeps=10, nmerge_sweeps=10, r=2,
                  c=0, epsilon=0., sequential=True, random_move=False,
                  dense=False, sparse_thresh=100, verbose=False,
                  checkpoint=None, minimize_state=None):
    bstate = state.levels[l]
    g = bstate.g

    if l + 1 < len(state.levels):
        min_B = state.levels[l + 1].B
    else:
        min_B = 1
    max_B = bstate.N

    if l + 1 < len(state.levels):
        clabel = bstate.b.copy()
        b_upper = state.levels[l + 1].b
        libcommunity.vector_map(clabel.a, b_upper.a)
    else:
        clabel = None

    nested_dl = l < len(state.levels) - 1

    Sb = get_state_dl(state.levels[l], dense=l > 0 or dense,
                      nested_dl=nested_dl, clabel=clabel)

    res = minimize_blockmodel_dl(g, eweight=bstate.eweight,
                                 deg_corr=bstate.deg_corr, nsweeps=nsweeps,
                                 c=c, random_move=random_move,
                                 sequential=sequential,
                                 r=r,
                                 adaptive_sweeps=True, greedy_cooling=True,
                                 epsilon=epsilon, nmerge_sweeps=nmerge_sweeps,
                                 max_B=max_B, min_B=min_B,
                                 clabel=clabel,
                                 max_BE=bstate.max_BE,
                                 dense=l > 0 or dense,
                                 sparse_heuristic=g.num_vertices() > sparse_thresh,
                                 nested_dl=nested_dl,
                                 verbose=False,
                                 ##exaustive=g.num_vertices() <= 100,
                                 minimize_state=minimize_state.minimize_state,
                                 checkpoint=checkpoint)
    b = res[0]

    # rebuild current level
    state._NestedBlockState__rebuild_level(l, bl=b.copy())

    Sf = res[1]

    kept = False
    if Sf - Sb >= -1e-10:
        kept = True
    if Sf - Sb == 0 and bstate.B != state.levels[l].B:
        kept = False

    if kept:
        state.levels[l] = bstate
        Sf = Sb
    else:
        # rebuild upper level
        if l + 1 < len(state.levels):
            if clabel is None:
                clabel = state.levels[l].b.copy()
                b_upper = state.levels[l + 1].b
                libcommunity.vector_map(clabel.a, b_upper.a)
            bmap = arange(b.fa.max() + 1, dtype=b.fa.dtype)
            libcommunity.vector_rmap(b.fa, bmap)
            libcommunity.vector_map(bmap, clabel.fa)

            state._NestedBlockState__rebuild_level(l + 1, bmap=bmap)

    if verbose:
        print("level", l, ": resizing", bstate.B, "->", state.levels[l].B, ", dS:", Sf - Sb,
              "[kept]" if kept else "" )

    dS = Sf - Sb
    return dS, kept


class NestedMinimizeState(object):
    r"""This object stores information regarding the current entropy minimization
    state, so that the algorithms can resume previously started runs.
    This object can be saved to disk via the :mod:`pickle` interface."""

    def __init__(self):
        self.minimize_state = MinimizeState()
        self.l = -1
        self.bs = []
        self.done = []

    def clear(self):
        self.minimize_state.clear()
        self.l = -1
        self.bs.clear()
        self.done.clear()

    def sync(self, state):
        if len(self.bs) == 0:
            for s in state.levels:
                self.bs.append(array(s.b.a))
        while len(self.done) < len(state.levels):
            self.done.append(False)
        if self.l == -1:
            self.l = len(state.levels) - 1

    def delete(self, l):
        del self.done[l]
        del self.bs[l]

    def insert(self, l, state):
        self.done.insert(l + 1, False)
        ba = state.levels[l].b.fa
        self.bs.insert(l + 1, array(ba))

    def mark_level(self, l, done, state):
        while len(state.levels) > len(self.bs):
            ba = state.levels[len(self.bs)].b.fa
            self.bs.append(array(ba))
            self.done.append(False)

        self.done[l] = done
        if done:
            self.bs[l] = array(state.levels[l].b.fa)

    def clear_mstate(self):
        self.minimize_state = MinimizeState()

def nested_tree_sweep(state, nsweeps=10, epsilon=0., r=2.,
                      nmerge_sweeps=10, random_move=False,
                      c=0, dense=False, sequential=True,
                      sparse_thresh=100, checkpoint=None,
                      minimize_state=None, verbose=False):
    r"""Performs one greedy sweep in the entire hierarchy tree, attempting to
    decrease its description length.

    Parameters
    ----------
    state : :class:`~graph_tool.community.NestedBlockState`
        The nested block state.
    nsweeps : ``int`` (optional, default: ``10``)
        The number of sweeps done after each merge step to reach the local
        minimum.
    epsilon : ``float`` (optional, default: ``0``)
        Converge criterion for ``adaptive_sweeps``.
    r : ``float`` (optional, default: ``2.``)
        Agglomeration ratio for the merging steps. Each merge step will attempt
        to find the best partition into :math:`B_{i-1} / r` blocks, where
        :math:`B_{i-1}` is the number of blocks in the last step.
    nmerge_sweeps : `int` (optional, default: `10`)
        The number of merge sweeps done, where in each sweep a better merge
        candidate is searched for every block.
    random_move : ``bool`` (optional, default: ``False``)
        If ``True``, the proposed moves will attempt to place the vertices in
        fully randomly-chosen blocks. If ``False``, the proposed moves will be
        chosen with a probability depending on the membership of the neighbours
        and the currently-inferred block structure.
    c : ``float`` (optional, default: ``1.0``)
        This parameter specifies how often fully random moves are attempted,
        instead of more likely moves based on the inferred block partition.
        For ``c == 0``, no fully random moves are attempted, and for ``c == inf``
        they are always attempted.
    dense : ``bool`` (optional, default: ``False``)
        If ``True``, the "dense" variant of the entropy will be computed.
    sequential : ``bool`` (optional, default: ``True``)
        If ``True``, the move attempts on the vertices are done in sequential
        random order. Otherwise a total of `N` moves attempts are made, where
        `N` is the number of vertices, where each vertex can be selected with
        equal probability.
    sparse_thresh : ``int`` (optional, default: ``100``)
        If the number of nodes in the higher level multigraphs exceeds this
        number, the sparse entropy will be used to find the best partition,
        but the dense entropy will be used to compare different partitions.
    checkpoint : function (optional, default: ``None``)
        If provided, this function will be called after each call to
        :func:`mcmc_sweep`. This can be used to store the current state, so it
        can be continued later. The function must have the following signature:

        .. code-block:: python

            def checkpoint(state, S, delta, nmoves, minimize_state):
                ...

        where `state` is either a :class:`~graph_tool.community.NestedBlockState`
        instance or ``None``, `S` is the current entropy value, `delta` is
        the entropy difference in the last MCMC sweep, and `nmoves` is the
        number of accepted block membership moves. The ``minimize_state``
        argument is a :class:`NestedMinimizeState` instance which specifies
        the current state of the algorithm, which can be stored via :mod:`pickle`,
        and supplied via the ``minimize_state`` option below to continue from an
        interrupted run.

        This function will also be called when the MCMC has finished for the
        current value of :math:`B`, in which case ``state == None``, and the
        remaining parameters will be zero, except the last.
    minimize_state : :class:`NestedMinimizeState` (optional, default: ``None``)
        If provided, this will specify an exact point of execution from which
        the algorithm will continue. The expected object is a
        :class:`NestedMinimizeState` instance which will be passed to the
        callback of the ``checkpoint`` option above, and  can be stored by
        :mod:`pickle`.
    verbose : ``bool`` (optional, default: ``False``)
        If ``True``, verbose information is displayed.

    Returns
    -------

    dS : ``float``
       The description length difference (per edge) after the move.


    Notes
    -----

    This algorithm performs a constrained agglomerative heuristic on each level
    of the network, via the function :func:`~graph_tool.community.multilevel_minimize`.

    This algorithm has worst-case complexity of :math:`O(N\ln^2 N \times L)`,
    where  :math:`N` is the number of nodes in the network, and :math:`L` is
    the depth of the hierarchy.

    References
    ----------

Tiago Peixoto's avatar
Tiago Peixoto committed
579
    .. [peixoto-efficient-2013] Tiago P. Peixoto, "Efficient Monte Carlo and greedy
580
       heuristic for the inference of stochastic block models", :arxiv:`1310.4378`.
Tiago Peixoto's avatar
Tiago Peixoto committed
581
    .. [peixoto-hierarchical-2013] Tiago P. Peixoto, "Hierarchical block structures
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
       and high-resolution model selection in large networks ", :arxiv:`1310.4377`.
    """

    if minimize_state is None:
        minimize_state = NestedMinimizeState()
    mstate = minimize_state
    mstate.sync(state)

    args = dict(state=state, nsweeps=nsweeps, nmerge_sweeps=nmerge_sweeps, r=r,
                c=c, epsilon=epsilon, sequential=sequential, random_move=random_move,
                dense=dense, sparse_thresh=sparse_thresh,
                checkpoint=checkpoint, minimize_state=minimize_state)

    #_Si = state.entropy(dense=dense, multigraph=dense)
    dS = 0

    while mstate.l >= 0:
        l = mstate.l
        if mstate.done[l]:
            if verbose:
                print("level", l, ": skipping", state.levels[l].B)


            mstate.l -= 1
            continue

        ddS, kept = replace_level(l, verbose=verbose, **args)
        dS += ddS
        mstate.clear_mstate()

        if l > 0:
            assert(state.levels[l - 1].B == state.levels[l].N)

        if l + 1 < len(state.levels):
            assert(state.levels[l].B == state.levels[l + 1].N)

        # delete level
        if kept and l > 0 and l < len(state.levels) - 1:
            Si = state.entropy()

            bstates = [state.levels[l-1], state.levels[l]]

            state._NestedBlockState__delete_level(l)
            replace_level(l, **args)

            assert(state.levels[l-1].B == state.levels[l].N)
            if l + 1 < len(state.levels):
                assert(state.levels[l].B == state.levels[l + 1].N)

            Sf = state.entropy()

            mstate.clear_mstate()
            if Sf > Si:
                state.levels[l - 1] = bstates[0]
                state.levels.insert(l, bstates[1])
            else:
                kept = False
                dS += Sf - Si

                mstate.delete(l)

                if verbose:
                    print("level", l, ": deleted", bstates[1].B, ", dS:", Sf - Si, len(state.levels))

        # insert new level
        if kept:
            Si = state.entropy()

            bstate = state.levels[l]

            state._NestedBlockState__duplicate_level(l)

            replace_level(l, verbose=False, **args)

            assert(state.levels[l].B == state.levels[l+1].N)
            if l > 0:
                assert(state.levels[l - 1].B == state.levels[l].N)

            Sf = state.entropy()

            mstate.clear_mstate()
            if Sf >= Si:
                del state.levels[l + 1]
                state.levels[l] = bstate
            else:
                kept = False
                dS += Sf - Si

                mstate.insert(l, state)

                l += 1

                if verbose:
                    print("level", l, ": inserted", state.levels[l].B, ", dS:", Sf - Si)


        if not kept:
            mstate.mark_level(l, done=True, state=state)
            if l + 1 < len(state.levels):
                mstate.mark_level(l + 1, done=False, state=state)
            if l > 0:
                mstate.mark_level(l - 1, done=False, state=state)

            l += 1
        else:
            l -= 1

        if l >= len(state.levels):
            l = len(state.levels) - 1

        if l == len(state.levels) - 1 and state.levels[l].B > 1:
            state._NestedBlockState__rebuild_level(l + 1, bmap=zeros(state.levels[l].B))
            mstate.mark_level(l + 1, done=False, state=state)
            l += 1

        mstate.l = l
        if checkpoint is not None:
            checkpoint(None, 0, 0, 0, mstate)

    # _Sf = state.entropy(dense=dense, multigraph=dense)

    return dS



def init_nested_state(g, Bs, deg_corr=True, dense=False,
                      eweight=None, vweight=None,
                      nsweeps=10, epsilon=0., r=2,
                      nmerge_sweeps=10, random_move=False,
                      c=0, sequential=True,
                      sparse_thresh=100, checkpoint=None,
                      minimize_state=None, max_BE=1000,
                      verbose=False):
    r"""Initializes a nested block hierarchy with sizes given by ``Bs``.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        The graph being modelled.
    Bs : list of ``int`` (optional, default: ``None``)
        Number of blocks for each hierarchy level.
    deg_corr : ``bool`` (optional, default: ``True``)
        If ``True``, the degree-corrected version of the blockmodel ensemble will
        be used in the bottom level, otherwise the traditional variant will be used.
    dense : ``bool`` (optional, default: ``False``)
        If ``True``, the "dense" variant of the entropy will be computed.
    eweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Edge weights (i.e. multiplicity).
    vweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex weights (i.e. multiplicity).
    nsweeps : ``int`` (optional, default: ``10``)
        The number of sweeps done after each merge step to reach the local
        minimum.
    epsilon : ``float`` (optional, default: ``0``)
        Converge criterion for ``adaptive_sweeps``.
    r : ``float`` (optional, default: ``2.``)
        Agglomeration ratio for the merging steps. Each merge step will attempt
        to find the best partition into :math:`B_{i-1} / r` blocks, where
        :math:`B_{i-1}` is the number of blocks in the last step.
    nmerge_sweeps : `int` (optional, default: `10`)
        The number of merge sweeps done, where in each sweep a better merge
        candidate is searched for every block.
    random_move : ``bool`` (optional, default: ``False``)
        If ``True``, the proposed moves will attempt to place the vertices in
        fully randomly-chosen blocks. If ``False``, the proposed moves will be
        chosen with a probability depending on the membership of the neighbours
        and the currently-inferred block structure.
    c : ``float`` (optional, default: ``0.``)
        This parameter specifies how often fully random moves are attempted,
        instead of more likely moves based on the inferred block partition.
        For ``c == 0``, no fully random moves are attempted, and for ``c == inf``
        they are always attempted.
    sequential : ``bool`` (optional, default: ``True``)
        If ``True``, the move attempts on the vertices are done in sequential
        random order. Otherwise a total of `N` moves attempts are made, where
        `N` is the number of vertices, where each vertex can be selected with
        equal probability.
    sparse_thresh : ``int`` (optional, default: ``100``)
        If the number of nodes in the higher level multigraphs exceeds this
        number, the sparse entropy will be used to find the best partition,
        but the dense entropy will be used to compare different partitions.
    checkpoint : function (optional, default: ``None``)
        If provided, this function will be called after each call to
        :func:`mcmc_sweep`. This can be used to store the current state, so it
        can be continued later. The function must have the following signature:

        .. code-block:: python

            def checkpoint(state, S, delta, nmoves, minimize_state):
                ...

        where `state` is either a :class:`~graph_tool.community.NestedBlockState`
        instance or ``None``, `S` is the current entropy value, `delta` is
        the entropy difference in the last MCMC sweep, and `nmoves` is the
        number of accepted block membership moves. The ``minimize_state``
        argument is a :class:`NestedMinimizeState` instance which specifies
        the current state of the algorithm, which can be stored via :mod:`pickle`,
        and supplied via the ``minimize_state`` option below to continue from an
        interrupted run.

        This function will also be called when the MCMC has finished for the
        current value of :math:`B`, in which case ``state == None``, and the
        remaining parameters will be zero, except the last.
    minimize_state : :class:`NestedMinimizeState` (optional, default: ``None``)
        If provided, this will specify an exact point of execution from which
        the algorithm will continue. The expected object is a
        :class:`NestedMinimizeState` instance which will be passed to the
        callback of the ``checkpoint`` option above, and  can be stored by
        :mod:`pickle`.
    verbose : ``bool`` (optional, default: ``False``)
        If ``True``, verbose information is displayed.

    Returns
    -------

    state : :class:`~graph_tool.community.NestedBlockState`
       The initialized nested state.


    Notes
    -----

    This algorithm performs an agglomerative heuristic on each level  of the
    network, via the function :func:`~graph_tool.community.multilevel_minimize`.

    This algorithm has worst-case complexity of :math:`O(N\ln^2 N \times L)`,
    where  :math:`N` is the number of nodes in the network, and :math:`L` is
    the depth of the hierarchy.

    References
    ----------

Tiago Peixoto's avatar
Tiago Peixoto committed
814
    .. [peixoto-efficient-2013] Tiago P. Peixoto, "Efficient Monte Carlo and greedy
815
       heuristic for the inference of stochastic block models", :arxiv:`1310.4378`.
Tiago Peixoto's avatar
Tiago Peixoto committed
816
    .. [peixoto-hierarchical-2013] Tiago P. Peixoto, "Hierarchical block structures
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
843
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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
       and high-resolution model selection in large networks ", :arxiv:`1310.4377`.
    """

    if minimize_state is None:
        minimize_state = NestedMinimizeState()
    mstate = minimize_state

    state = NestedBlockState(g, eweight=eweight, vweight=vweight, Bs=[1],
                             deg_corr=deg_corr)

    if checkpoint is not None:
        def check_wrap(bstate, S, delta, nmoves, ms):
            if bstate is None:
                checkpoint(None, S, delta, nmoves, minimize_state)
            else:
                checkpoint(state, S, delta, nmoves, minimize_state)
        chkp = check_wrap
    else:
        chkp = None

    bg = g
    ecount = eweight

    for l, B in enumerate(Bs):
        if l < len(mstate.bs):
            ba = mstate.bs[l]
        else:
            bstate = BlockState(bg, B=bg.num_vertices(), #b=bg.vertex_index.copy("int"),
                                vweight=vweight if l == 0 else None,
                                eweight=ecount,
                                deg_corr=deg_corr and l == 0, max_BE=max_BE)

            bstate = multilevel_minimize(bstate, B, nsweeps=nsweeps, epsilon=epsilon,
                                         r=r, nmerge_sweeps=nmerge_sweeps,
                                         greedy=True, c=c,
                                         dense=(l > 0 and g.num_vertices() < sparse_thresh) or dense,
                                         multigraph=l > 0 or dense,
                                         random_move=random_move,
                                         sequential=sequential, verbose=verbose,
                                         checkpoint=chkp,
                                         minimize_state=minimize_state.minimize_state)
            ba = array(bstate.b.fa)
            mstate.bs.append(ba)
            minimize_state.minimize_state.clear()

        state._NestedBlockState__rebuild_level(len(state.levels) - 1, bl=ba)
        bg = state.levels[l].bg
        ecount = state.levels[l].mrs

    minimize_state.clear()
    mstate.sync(state)
    if checkpoint is not None:
        checkpoint(None, 0, 0, 0, mstate)

    return state

def minimize_nested_blockmodel_dl(g, Bs=None, bs=None, deg_corr=True,
                                  dense=False, eweight=None, vweight=None,
                                  nsweeps=10, epsilon=0., random_move=False, c=0,
                                  nmerge_sweeps=10, r=2, sparse_thresh=100,
                                  sequential=True, verbose=False,
                                  checkpoint=None, minimize_state=None):
    r"""Find the block hierarchy of an unspecified size which minimizes the description
    length of the network, according to the nested stochastic blockmodel ensemble which
    best describes it.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph being used.
    Bs : list of ``int`` (optional, default: ``None``)
        Initial number of blocks for each hierarchy level.
    bs : list of :class:`~graph_tool.PropertyMap` or :class:`~numpy.ndarray` instances (optional, default: ``None``)
        Initial block labels on the vertices, for each hierarchy level.
    deg_corr : ``bool`` (optional, default: ``True``)
        If ``True``, the degree-corrected version of the blockmodel ensemble will
        be used in the bottom level, otherwise the traditional variant will be used.
    dense : ``bool`` (optional, default: ``False``)
        If ``True``, the "dense" variant of the entropy will be computed.
    eweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Edge weights (i.e. multiplicity).
    vweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex weights (i.e. multiplicity).
    nsweeps : ``int`` (optional, default: ``10``)
        The number of sweeps done after each merge step to reach the local
        minimum.
    epsilon : ``float`` (optional, default: ``0``)
        The number of sweeps necessary for the local minimum will
        be estimated to be enough so that no more than ``epsilon * N`` nodes
        changes their states in the last ``nsweeps`` sweeps.
    random_move : ``bool`` (optional, default: ``False``)
        If ``True``, the proposed moves will attempt to place the vertices in
        fully randomly-chosen blocks. If ``False``, the proposed moves will be
        chosen with a probability depending on the membership of the neighbours
        and the currently-inferred block structure.
    c : ``float`` (optional, default: ``0.``)
        This parameter specifies how often fully random moves are attempted,
        instead of more likely moves based on the inferred block partition.
        For ``c == 0``, no fully random moves are attempted, and for ``c == inf``
        they are always attempted.
    nmerge_sweeps : `int` (optional, default: `10`)
        The number of merge sweeps done, where in each sweep a better merge
        candidate is searched for every block.
    r : ``float`` (optional, default: ``2.``)
        Agglomeration ratio for the merging steps. Each merge step will attempt
        to find the best partition into :math:`B_{i-1} / r` blocks, where
        :math:`B_{i-1}` is the number of blocks in the last step.
    sparse_thresh : ``int`` (optional, default: ``100``)
        If the number of blocks at some level is larger than this value, the
        sparse entropy will be used to find the best partition, but the dense
        entropy will be used to compare different partitions.
    sequential : ``bool`` (optional, default: ``True``)
        If ``True``, the move attempts on the vertices are done in sequential
        random order. Otherwise a total of `N` moves attempts are made, where
        `N` is the number of vertices, where each vertex can be selected with
        equal probability.
    checkpoint : function (optional, default: ``None``)
        If provided, this function will be called after each call to
        :func:`mcmc_sweep`. This can be used to store the current state, so it
        can be continued later. The function must have the following signature:

        .. code-block:: python

            def checkpoint(state, L, delta, nmoves, minimize_state):
                ...

        where `state` is either a :class:`~graph_tool.community.NestedBlockState`
        instance or ``None``, `L` is the current description length, `delta` is
        the entropy difference in the last MCMC sweep, and `nmoves` is the
        number of accepted block membership moves. The ``minimize_state``
        argument is a :class:`~graph_tool.community.NestedMinimizeState`
        instance which specifies the current state of the algorithm, which can
        be stored via :mod:`pickle`, and supplied via the ``minimize_state``
        option below to continue from an interrupted run.

        This function will also be called when the MCMC has finished for the
        current value of :math:`B`, in which case ``state == None``, and the
        remaining parameters will be zero, except the last.
    minimize_state : :class:`MinimizeState` (optional, default: ``None``)
        If provided, this will specify an exact point of execution from which
        the algorithm will continue. The expected object is a
        :class:`~graph_tool.community.NestedMinimizeState`
        instance which will be passed to the callback of the ``checkpoint``
        option above, and  can be stored by :mod:`pickle`.
    verbose : ``bool`` (optional, default: ``False``)
        If ``True``, verbose information is displayed.

    Returns
    -------
    bstack : list of :class:`~graph_tool.Graph` instances
        This is a list of :class:`~graph_tool.Graph` instances representing the
        inferred hierarchy at each level. Each graph has two internal vertex and
        edge property maps named "count" which correspond to the vertex and edge
        counts at the lower level, respectively. Additionally, an internal
        vertex property map named "b" specifies the block partition.
    min_dl : ``float``
       Minimum value of the description length (in `nats <http://en.wikipedia.org/wiki/Nat_%28information%29>`_ per edge).

    Notes
    -----

    This algorithm attempts to find a block partition hierarchy of an unspecified size
    which minimizes the description length of the network,

    .. math::

       \Sigma = \mathcal{L}_{t/c} + \mathcal{S}_n,

    where :math:`\mathcal{S}_{n}` is the nested blockmodel entropy given by

    .. math::

       \mathcal{S}_n  = \mathcal{S}_{t/c}(\{e^0_{rs}\}, \{n^0_r\}) + \sum_{l=1}^LS_m(\{e^l_{rs}\}, \{n^l_r\}).

    with :math:`\mathcal{S}_{t/c}` and :math:`\mathcal{S}_{m}` described in the docstring of
    :meth:`~graph_tool.community.BlockState.entropy`, and :math:`\{e^l_{rs}\}`
    and :math:`\{n^l_r\}` are the edge and node counts at hierarchical level :math:`l`.
    Additionally :math:`\mathcal{L}_{t/c}` is the information necessary to
    describe the block partitions, i.e. :math:`\mathcal{L}_t=\sum_{l=0}^L\mathcal{L}^l_t`, with

    .. math::

        \mathcal{L}^l_t = \ln\left(\!\!{B_l\choose B_{l-1}}\!\!\right) + \ln B_{l-1}! - \sum_r \ln n_r^l!.


Tiago Peixoto's avatar
Tiago Peixoto committed
1002
    See [peixoto-hierarchical-2013]_ for details on the algorithm.
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015

    This algorithm has a complexity of :math:`O(N \ln^2 N)`, where :math:`N`
    is the number of nodes in the network.

    Examples
    --------
    .. testsetup:: nested_mdl

       gt.seed_rng(42)
       np.random.seed(42)

    .. doctest:: nested_mdl

Tiago Peixoto's avatar
Tiago Peixoto committed
1016
1017
       >>> g = gt.collection.data["power"]
       >>> bstack, mdl = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
1018
1019
1020
1021
1022
1023
       >>> t = gt.get_hierarchy_tree(bstack)[0]
       >>> tpos = pos = gt.radial_tree_layout(t, t.vertex(t.num_vertices() - 1), weighted=True)
       >>> cts = gt.get_hierarchy_control_points(g, t, tpos)
       >>> pos = g.own_property(tpos)
       >>> b = bstack[0].vp["b"]
       >>> gt.graph_draw(g, pos=pos, vertex_fill_color=b, vertex_shape=b, edge_control_points=cts,
Tiago Peixoto's avatar
Tiago Peixoto committed
1024
       ...               edge_color=[0, 0, 0, 0.3], vertex_anchor=0, output="power_nested_mdl.pdf")
1025
1026
1027
1028
       <...>

    .. testcleanup:: nested_mdl

Tiago Peixoto's avatar
Tiago Peixoto committed
1029
       gt.graph_draw(g, pos=pos, vertex_fill_color=b, vertex_shape=b, edge_control_points=cts, edge_color=[0, 0, 0, 0.3], vertex_anchor=0, output="power_nested_mdl.png")
1030

Tiago Peixoto's avatar
Tiago Peixoto committed
1031
    .. figure:: power_nested_mdl.*
1032
1033
       :align: center

Tiago Peixoto's avatar
Tiago Peixoto committed
1034
       Block partition of a power-grid network, which minimizes the description
1035
1036
1037
1038
1039
       length of the network according to the nested (degree-corrected) stochastic blockmodel.

    References
    ----------

Tiago Peixoto's avatar
Tiago Peixoto committed
1040
    .. [peixoto-hierarchical-2013] Tiago P. Peixoto, "Hierarchical block structures and high-resolution
1041
       model selection in large networks ", :arxiv:`1310.4377`.
Tiago Peixoto's avatar
Tiago Peixoto committed
1042
    .. [peixoto-efficient-2013] Tiago P. Peixoto, "Efficient Monte Carlo and greedy
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
       heuristic for the inference of stochastic block models", :arxiv:`1310.4378`.
    """


    if Bs is None:
        Bs = [1]

        if minimize_state is not None:
            Bs = [ba.max() + 1 for ba in minimize_state.bs]

    if bs is not None:
        Bs = [ba.max() + 1 for ba in bs]

    if Bs[-1] > 1:
        Bs += [1]

    if minimize_state is None:
        minimize_state = NestedMinimizeState()

    if bs is None:
        state = init_nested_state(g, Bs=Bs, deg_corr=deg_corr,
                                  eweight=eweight, vweight=vweight,
                                  verbose=verbose, nsweeps=nsweeps,
                                  nmerge_sweeps=nmerge_sweeps,
                                  dense=dense,
                                  epsilon=epsilon,
                                  sparse_thresh=sparse_thresh,
                                  checkpoint=checkpoint,
                                  minimize_state=minimize_state)
    else:
        state = NestedBlockState(g, bs=bs, deg_corr=deg_corr, eweight=eweight,
                                 vweight=vweight)

    if checkpoint is not None:
        def check_wrap(bstate, S, delta, nmoves, ms):
            if bstate is not None:
                checkpoint(state, S, delta, nmoves, minimize_state)
            else:
                checkpoint(None, S, delta, nmoves, minimize_state)
        chkp = check_wrap
    else:
        chkp = None


    dS = nested_tree_sweep(state, verbose=verbose,
                            nsweeps=nsweeps,
                            nmerge_sweeps=nmerge_sweeps,
                            r=r,
                            epsilon=epsilon,
                            sparse_thresh=sparse_thresh,
                            checkpoint=chkp,
                            minimize_state=minimize_state)

    bstack = state.get_bstack()

    return bstack, state.entropy()


def get_hierarchy_tree(bstack):
    r"""Obtain the nested hierarchical levels as a tree.

    This transforms a list of :class:`~graph_tool.Graph` instances, given by the
    ``bstack`` parameter, representing the inferred hierarchy at each level, into
    a single :class:`~graph_tool.Graph` containing the hierarchy tree.

    It is expected for each graph in ``bstack`` to contain an internal vertex
    property map named "b" which contains the node partition at the
    corresponding level.

    Returns
    -------

    tree : :class:`~graph_tool.Graph`
       A directed graph, where vertices are blocks, and a directed edge points
       to an upper to a lower level in the hierarchy.
    label : :class:`~graph_tool.PropertyMap`
       A vertex property map containing the block label for each node.
    """

    g = bstack[0]
    b = g.vp["b"]
    bstack = bstack[1:]

    t = Graph()

    t.add_vertex(g.num_vertices())
    label = t.vertex_index.copy("int")

    last_pos = 0
    for l, s in enumerate(bstack):
        pos = t.num_vertices()
        t.add_vertex(s.num_vertices())
        label.a[-s.num_vertices():] = arange(s.num_vertices())

        for v in g.vertices():
            w = t.vertex(int(v) + last_pos)
            u = t.vertex(b[v] + pos)
            t.add_edge(u, w)

        last_pos = pos
        g = s
        if g.num_vertices() == 1:
            break
        b = g.vp["b"]
    return t, label