nested_blockmodel.py 33.9 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-2022 Tiago de Paula Peixoto <tiago@skewed.de>
7
#
8
9
10
11
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
12
#
13
14
15
16
# 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 Lesser General Public License for more
# details.
17
#
18
19
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
20

Alex Henrie's avatar
Alex Henrie committed
21
from .. import _prop, Graph, GraphView
22
23
24
25

from . base_states import _bm_test
from . base_states import *

26
27
28
29
30
31
32
33
34
35
36
37
38
39
from . blockmodel import *
from . overlap_blockmodel import *
from . layered_blockmodel import *

from numpy import *
import numpy
import copy

class NestedBlockState(object):
    r"""The nested stochastic block model state of a given graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
Tiago Peixoto's avatar
Tiago Peixoto committed
40
        Graph to be modeled.
Tiago Peixoto's avatar
Tiago Peixoto committed
41
42
43
    bs : ``list`` of :class:`~graph_tool.VertexPropertyMap` or :class:`numpy.ndarray` (optional, default: ``None``)
        Hierarchical node partition. If not provided it will correspond to a
        single-group hierarchy of length :math:`\lceil\log_2(N)\rceil`.
44
    base_type : ``type`` (optional, default: :class:`~graph_tool.inference.BlockState`)
Tiago Peixoto's avatar
Tiago Peixoto committed
45
        State type for lowermost level
46
47
48
        (e.g. :class:`~graph_tool.inference.BlockState`,
        :class:`~graph_tool.inference.OverlapBlockState` or
        :class:`~graph_tool.inference.LayeredBlockState`)
49
50
51
52
53
54
    hstate_args : ``dict`` (optional, default: `{}`)
        Keyword arguments to be passed to the constructor of the higher-level
        states.
    hentropy_args : ``dict`` (optional, default: `{}`)
        Keyword arguments to be passed to the ``entropy()`` method of the
        higher-level states.
55
    state_args : ``dict`` (optional, default: ``{}``)
56
        Keyword arguments to be passed to base type constructor.
57
58
59
    **kwargs :  keyword arguments
        Keyword arguments to be passed to base type constructor. The
        ``state_args`` parameter overrides this.
Tiago Peixoto's avatar
Tiago Peixoto committed
60

61
    """
62

Tiago Peixoto's avatar
Tiago Peixoto committed
63
    def __init__(self, g, bs=None, base_type=BlockState, state_args={},
64
                 hstate_args={}, hentropy_args={}, **kwargs):
65
        self.g = g
Tiago Peixoto's avatar
Tiago Peixoto committed
66

67
68
69
70
71
        self.base_type = base_type
        if base_type is LayeredBlockState:
            self.Lrecdx = []
        else:
            self.Lrecdx = libcore.Vector_double()
72
        self.state_args = dict(kwargs, **state_args)
73
        self.state_args["Lrecdx"] = self.Lrecdx
74
75
76
77
        if "rec_params" not in self.state_args:
            recs = self.state_args.get("recs", None)
            if recs is not None:
                self.state_args["rec_params"] = ["microcanonical"] * len(recs)
78
        self.hstate_args = dict(dict(deg_corr=False, vweight="nonempty"),
79
                                **hstate_args)
80
        self.hstate_args["Lrecdx"] = self.Lrecdx
81
        self.hstate_args["copy_bg"] = False
82
83
84
85
86
87
88
89
        self.hentropy_args = dict(hentropy_args,
                                  adjacency=True,
                                  dense=True,
                                  multigraph=True,
                                  dl=True,
                                  partition_dl=True,
                                  degree_dl=True,
                                  degree_dl_kind="distributed",
90
                                  edges_dl=False,
91
                                  exact=True,
92
                                  recs=True,
93
                                  recs_dl=False,
94
                                  beta_dl=1.)
95

96
97
        self.levels = [base_type(g, b=bs[0] if bs is not None else None,
                                 **self.state_args)]
98

99
100
101
102
103
104
105
        if bs is None:
            if base_type is OverlapBlockState:
                N = 2 * self.levels[0].get_N()
            else:
                N = self.levels[0].get_N()
            L = int(numpy.ceil(numpy.log2(N)))
            bs = [None] * (L + 1)
106

107
        for i, b in enumerate(bs[1:]):
108
            state = self.levels[-1]
109
110
111
112
            args = self.hstate_args
            if i == len(bs[1:]) - 1:
                args = dict(args, clabel=None, pclabel=None)
            bstate = state.get_block_state(b=b, **args)
113
114
            self.levels.append(bstate)

115
116
        self._regen_Lrecdx()

117
        self._couple_levels(self.hentropy_args, None)
118

119
120
121
        if _bm_test():
            self._consistency_check()

122
    def _regen_Lrecdx(self, lstate=None):
Tiago Peixoto's avatar
Tiago Peixoto committed
123
124
125
        if not hasattr(self.levels[0], "recdx"):
            return

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
        if lstate is None:
            levels = self.levels
            Lrecdx = self.Lrecdx
        else:
            levels = [s for s in self.levels]
            l, s = lstate
            levels[l] = s
            s = s.get_block_state(**dict(self.hstate_args,
                                         b=s.get_bclabel(),
                                         copy_bg=False))
            if l < len(levels) - 1:
                levels[l+1] = s
            else:
                levels.append(s)
            if self.base_type is LayeredBlockState:
                Lrecdx = [x.copy() for x in self.Lrecdx]
            else:
                Lrecdx = self.Lrecdx.copy()

        if self.base_type is not LayeredBlockState:
            Lrecdx.a = 0
            Lrecdx[0] = len([s for s in levels if s._state.get_B_E_D() > 0])
            for s in levels:
                Lrecdx.a[1:] += s.recdx.a * s._state.get_B_E_D()
                s.epsilon.a = levels[0].epsilon.a
            for s in levels:
                s.Lrecdx.a = Lrecdx.a
        else:
            Lrecdx[0].a = 0
            Lrecdx[0][0] = len([s for s in levels if s._state.get_B_E_D() > 0])
            for j in range(levels[0].C):
                Lrecdx[j+1].a = 0
                Lrecdx[j+1][0] = len([s for s in levels if s._state.get_layer(j).get_B_E_D() > 0])
            for s in levels:
                Lrecdx[0].a[1:] += s.recdx.a * s._state.get_B_E_D()
                s.epsilon.a = levels[0].epsilon.a
                for j in range(levels[0].C):
                    Lrecdx[j+1].a[1:] += s.layer_states[j].recdx.a * s._state.get_layer(j).get_B_E_D()
                    s.layer_states[j].epsilon.a = levels[0].epsilon.a

            for s in self.levels:
                for x, y in zip(s.Lrecdx, Lrecdx):
                    x.a = y.a

        if lstate is not None:
            return Lrecdx

173

174
175
176
    def _regen_levels(self):
        for l in range(1, len(self.levels)):
            state = self.levels[l]
177
178
            nstate = self.levels[l-1].get_block_state(b=state.b,
                                                      **self.hstate_args)
179
            self.levels[l] = nstate
180
        self._regen_Lrecdx()
181

182
183
184
    def __repr__(self):
        return "<NestedBlockState object, with base %s, and %d levels of sizes %s at 0x%x>" % \
            (repr(self.levels[0]), len(self.levels),
185
             str([(s.get_N(), s.get_nonempty_B()) for s in self.levels]), id(self))
186
187
188
189

    def __copy__(self):
        return self.copy()

190
    def copy(self, **kwargs):
191
192
        r"""Copies the block state. The parameters override the state properties,
        and have the same meaning as in the constructor."""
193
194
        state = dict(self.__getstate__(), **kwargs)
        return NestedBlockState(**state)
195
196

    def __getstate__(self):
197
        base_state = self.levels[0].__getstate__()
198
199
200
        base_state.pop("Lrecdx", None)
        base_state.pop("epsilon", None)
        base_state.pop("drec", None)
Tiago Peixoto's avatar
Tiago Peixoto committed
201
        state_args = dict(self.state_args, **base_state)
202
203
204
205
        state_args.pop("g", None)
        state_args.pop("b", None)
        state = dict(g=self.g, bs=self.get_bs(),
                     base_type=type(self.levels[0]),
206
                     hstate_args=self.hstate_args,
207
                     hentropy_args=self.hentropy_args,
208
                     state_args=state_args)
209
210
211
        return state

    def __setstate__(self, state):
212
        self.__init__(**state)
213

214
215
216
217
    def get_bs(self):
        """Get hierarchy levels as a list of :class:`numpy.ndarray` objects with the
        group memberships at each level.
        """
218
        return [s.b.fa.copy() for s in self.levels]
219

220
221
222
223
    def get_state(self):
        """Alias to :meth:`~NestedBlockState.get_bs`."""
        return self.get_bs()

224
225
226
227
228
    def set_state(self, bs):
        r"""Sets the internal nested partition of the state."""
        for i in range(len(bs)):
            self.levels[i].set_state(bs[i])

229
    def get_levels(self):
230
        """Get hierarchy levels as a list of :class:`~graph_tool.inference.BlockState`
231
232
233
        instances."""
        return self.levels

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
    def project_partition(self, j, l):
        """Project partition of level ``j`` onto level ``l``, and return it."""
        b = self.levels[l].b.copy()
        for i in range(l + 1, j + 1):
            clabel = self.levels[i].b.copy()
            pmap(b, clabel)
        return b

    def propagate_clabel(self, l):
        """Project base clabel to level ``l``."""
        clabel = self.levels[0].clabel.copy()
        for j in range(l):
            bg = self.levels[j].bg
            bclabel = bg.new_vertex_property("int")
            reverse_map(self.levels[j].b, bclabel)
            pmap(bclabel, clabel)
            clabel = bclabel
        return clabel

    def get_clabel(self, l):
        """Get clabel for level ``l``."""
        clabel = self.propagate_clabel(l)
        if l < len(self.levels) - 1:
            b = self.project_partition(l + 1, l)
            clabel.fa += (clabel.fa.max() + 1) * b.fa
        return clabel

    def _consistency_check(self):
        for l in range(1, len(self.levels)):
            b = self.levels[l].b.fa.copy()
            state = self.levels[l-1]
265
266
267
268
            args = self.hstate_args
            if l == len(self.levels) - 1:
                args = dict(args, clabel=None, pclabel=None)
            bstate = state.get_block_state(b=b, **args)
269
            b2 = bstate.b.fa.copy()
270
271
            b = contiguous_map(b)
            b2 = contiguous_map(b2)
272
            assert ((b == b2).all() and
273
274
275
                    math.isclose(bstate.entropy(dl=False),
                                 self.levels[l].entropy(dl=False),
                                 abs_tol=1e-8)), \
276
277
278
                "inconsistent level %d (%s %g,  %s %g): %s" % \
                (l, str(bstate), bstate.entropy(), str(self.levels[l]),
                 self.levels[l].entropy(), str(self))
279
280
            assert (bstate.get_N() >= bstate.get_nonempty_B()), \
                (l, bstate.get_N(), bstate.get_nonempty_B(), str(self))
281

282
    def level_entropy(self, l, bstate=None, **kwargs):
283
284
285
286
287
        """Compute the entropy of level ``l``."""

        if bstate is None:
            bstate = self.levels[l]

288
289
290
291
292
293
294
        kwargs = kwargs.copy()
        hentropy_args = dict(self.hentropy_args,
                             **kwargs.pop("hentropy_args", {}))
        hentropy_args_top = dict(dict(hentropy_args, edges_dl=True,
                                      recs_dl=True),
                                 **kwargs.pop("hentropy_args_top", {}))

295
        if l > 0:
296
297
298
299
            if l == (len(self.levels) - 1):
                eargs = hentropy_args_top
            else:
                eargs = hentropy_args
300
        else:
301
            eargs = dict(kwargs, edges_dl=False)
302

303
        S = bstate.entropy(**eargs)
304
305
306
307

        if l > 0:
            S *= kwargs.get("beta_dl", 1.)

308
309
        return S

310
    def _Lrecdx_entropy(self, Lrecdx=None):
Tiago Peixoto's avatar
Tiago Peixoto committed
311
312
313
        if not hasattr(self.levels[0], "recdx"):
            return 0

314
315
        if self.base_type is not LayeredBlockState:
            S_D = 0
316

317
318
319
320
321
322
            if Lrecdx is None:
                Lrecdx = self.Lrecdx
                for s in self.levels:
                    B_E_D = s._state.get_B_E_D()
                    if B_E_D > 0:
                        S_D -= log(B_E_D)
323

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
            S = 0
            for i in range(len(self.levels[0].rec)):
                if self.levels[0].rec_types[i] != libinference.rec_type.real_normal:
                    continue
                assert not _bm_test() or Lrecdx[i+1] >= 0, (i, Lrecdx[i+1])
                S += -libinference.positive_w_log_P(Lrecdx[0], Lrecdx[i+1],
                                                    numpy.nan, numpy.nan,
                                                    self.levels[0].epsilon[i])
                S += S_D
            return S
        else:
            S_D = [0 for j in range(self.levels[0].C)]
            if Lrecdx is None:
                Lrecdx = self.Lrecdx
                for s in self.levels:
                    for j in range(self.levels[0].C):
                        B_E_D = s._state.get_layer(j).get_B_E_D()
                        if B_E_D > 0:
                            S_D[j] -= log(B_E_D)

            S = 0
            for i in range(len(self.levels[0].rec)):
                if self.levels[0].rec_types[i] != libinference.rec_type.real_normal:
                    continue
                for j in range(self.levels[0].C):
                    assert not _bm_test() or Lrecdx[j+1][i+1] >= 0, (i, j, Lrecdx[j+1][i+1])
                    S += -libinference.positive_w_log_P(Lrecdx[j+1][0],
                                                        Lrecdx[j+1][i+1],
                                                        numpy.nan, numpy.nan,
                                                        self.levels[0].epsilon[i])
                    S += S_D[j]
            return S
356

357
    @copy_state_wrap
358
    def entropy(self, **kwargs):
Tiago Peixoto's avatar
Tiago Peixoto committed
359
360
        """Compute the entropy of whole hierarchy.

361
362
        The keyword arguments are passed to the ``entropy()`` method of the
        underlying state objects
363
364
365
        (e.g. :class:`graph_tool.inference.BlockState.entropy`,
        :class:`graph_tool.inference.OverlapBlockState.entropy`, or
        :class:`graph_tool.inference.LayeredBlockState.entropy`).  """
366
367
        S = 0
        for l in range(len(self.levels)):
368
            S += self.level_entropy(l, **dict(kwargs, test=False))
369

370
        S += kwargs.get("beta_dl", 1.) * self._Lrecdx_entropy()
371

372
373
        return S

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
    def move_vertex(self, v, s):
        r"""Move vertex ``v`` to block ``s``."""
        self.levels[0].move_vertex(v, s)
        self._regen_levels()

    def remove_vertex(self, v):
        r"""Remove vertex ``v`` from its current group.

        This optionally accepts a list of vertices to remove.

        .. warning::

           This will leave the state in an inconsistent state before the vertex
           is returned to some other group, or if the same vertex is removed
           twice.
        """
        self.levels[0].remove_vertex(v)
        self._regen_levels()

    def add_vertex(self, v, r):
        r"""Add vertex ``v`` to block ``r``.

        This optionally accepts a list of vertices and blocks to add.

        .. warning::

           This can leave the state in an inconsistent state if a vertex is
           added twice to the same group.
        """
        self.levels[0].add_vertex(v, r)
        self._regen_levels()

406
    def get_edges_prob(self, missing, spurious=[], entropy_args={}):
407
        r"""Compute the joint log-probability of the missing and spurious edges given by
408
409
410
411
412
413
414
415
        ``missing`` and ``spurious`` (a list of ``(source, target)``
        tuples, or :meth:`~graph_tool.Edge` instances), together with the
        observed edges.

        More precisely, the log-likelihood returned is

        .. math::

416
            \ln \frac{P(\boldsymbol G + \delta \boldsymbol G | \boldsymbol b)}{P(\boldsymbol G| \boldsymbol b)}
417
418
419
420
421

        where :math:`\boldsymbol G + \delta \boldsymbol G` is the modified graph
        (with missing edges added and spurious edges deleted).

        The values in ``entropy_args`` are passed to
422
        :meth:`graph_tool.inference.BlockState.entropy()` to calculate the
423
424
        log-probability.
        """
425

426
427
428
429
430
431
432
        entropy_args = entropy_args.copy()
        hentropy_args = dict(self.hentropy_args,
                             **entropy_args.pop("hentropy_args", {}))
        hentropy_args_top = dict(dict(hentropy_args, edges_dl=True,
                                      recs_dl=True),
                                 **entropy_args.pop("hentropy_args_top", {}))

433
        L = 0
434
        for l, lstate in enumerate(self.levels):
435
            if l > 0:
436
437
438
439
                if l == (len(self.levels) - 1):
                    eargs = hentropy_args_top
                else:
                    eargs = hentropy_args
440
441
442
            else:
                eargs = entropy_args

443
444
445
446
            lstate._couple_state(None, None)
            if l > 0:
                lstate._state.sync_emat()
                lstate._state.clear_egroups()
447

448
            L += lstate.get_edges_prob(missing, spurious, entropy_args=eargs)
449
            if isinstance(self.levels[0], LayeredBlockState):
450
451
                missing = [(lstate.b[u], lstate.b[v], l_) for u, v, l_ in missing]
                spurious = [(lstate.b[u], lstate.b[v], l_) for u, v, l_ in spurious]
452
            else:
453
454
455
                missing = [(lstate.b[u], lstate.b[v]) for u, v in missing]
                spurious = [(lstate.b[u], lstate.b[v]) for u, v in spurious]

456
457
        return L

458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
    def get_bstack(self):
        """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()
474
475
476
            if bstate.is_weighted:
                cg.ep["count"] = cg.own_property(bstate.eweight.copy())
                cg.vp["count"] = cg.own_property(bstate.vweight.copy())
477
478
479
480
            else:
                cg.ep["count"] = cg.new_ep("int", 1)

            bstack.append(cg)
481
            if bstate.get_N() == 1:
482
483
484
485
486
487
488
                break
        return bstack

    def project_level(self, l):
        """Project the partition at level ``l`` onto the lowest level, and return the
        corresponding state."""
        b = self.project_partition(l, 0)
489
        return self.levels[0].copy(b=b)
490
491
492
493

    def print_summary(self):
        """Print a hierarchy summary."""
        for l, state in enumerate(self.levels):
494
495
            print("l: %d, N: %d, B: %d" % (l, state.get_N(),
                                           state.get_nonempty_B()))
Tiago Peixoto's avatar
Tiago Peixoto committed
496
497
            if state.get_N() == 1:
                break
498

499
500
501
    def _couple_levels(self, hentropy_args, hentropy_args_top):
        if hentropy_args_top is None:
            hentropy_args_top = dict(hentropy_args, edges_dl=True, recs_dl=True)
502
        for l in range(len(self.levels) - 1):
503
504
505
506
            if l + 1 == len(self.levels) - 1:
                eargs = hentropy_args_top
            else:
                eargs = hentropy_args
507
508
            self.levels[l]._couple_state(self.levels[l + 1], eargs)

509
510
511
512
    def _clear_egroups(self):
        for lstate in self.levels:
            lstate._clear_egroups()

513
    def _h_sweep_gen(self, **kwargs):
514

515
        verbose = kwargs.get("verbose", False)
516
517
518
519
520
521
        entropy_args = dict(kwargs.get("entropy_args", {}), edges_dl=False)
        hentropy_args = dict(self.hentropy_args,
                             **entropy_args.pop("hentropy_args", {}))
        hentropy_args_top = dict(dict(hentropy_args, edges_dl=True,
                                      recs_dl=True),
                                 **entropy_args.pop("hentropy_args_top", {}))
522

523
        self._couple_levels(hentropy_args, hentropy_args_top)
524

525
526
        c = kwargs.get("c", None)

527
        lrange = list(kwargs.pop("ls", range(len(self.levels))))
528
529
        if kwargs.pop("ls_shuffle", True):
            numpy.random.shuffle(lrange)
530
        for l in lrange:
531
532
533
            if check_verbose(verbose):
                print(verbose_pad(verbose) + "level:", l)
            if l > 0:
534
535
536
537
                if l == len(self.levels) - 1:
                    eargs = hentropy_args_top
                else:
                    eargs = hentropy_args
538
539
540
            else:
                eargs = entropy_args

541
            if c is None:
542
                args = dict(kwargs, entropy_args=eargs)
543
            else:
544
                args = dict(kwargs, entropy_args=eargs, c=c[l])
545

546
547
548
549
550
            if l > 0:
                if "beta_dl" in entropy_args:
                    args = dict(args, beta=args.get("beta", 1.) * entropy_args["beta_dl"])
                for p in ["B_max", "B_min", "b_max", "b_min"]:
                    args.pop(p, None)
551

552
553
554
555
556
557
558
559
560
            yield l, self.levels[l], args

    def _h_sweep(self, algo, **kwargs):
        entropy_args = kwargs.get("entropy_args", {})

        dS = 0
        nattempts = 0
        nmoves = 0

561
        for l, lstate, args in self._h_sweep_gen(**kwargs):
562

563
            ret = algo(self.levels[l], **dict(args, test=False))
564

565
566
567
568
569
570
            if l > 0 and "beta_dl" in entropy_args:
                dS += ret[0] * entropy_args["beta_dl"]
            else:
                dS += ret[0]
            nattempts += ret[1]
            nmoves += ret[2]
571

572
        return dS, nattempts, nmoves
573

574
575
576
    def _h_sweep_states(self, algo, **kwargs):
        entropy_args = kwargs.get("entropy_args", {})
        for l, lstate, args in self._h_sweep_gen(**kwargs):
577
578
            beta_dl = entropy_args.get("beta_dl", 1) if l > 0 else 1
            yield l, lstate, algo(self.levels[l], dispatch=False, **args), beta_dl
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595

    def _h_sweep_parallel_dispatch(states, sweeps, algo):
        ret = None
        for lsweep in zip(*sweeps):
            ls = [x[0] for x in lsweep]
            lstates = [x[1] for x in lsweep]
            lsweep_states = [x[2] for x in lsweep]
            beta_dl = [x[3] for x in lsweep]
            lret = algo(type(lstates[0]), lstates, lsweep_states)
            if ret is None:
                ret = lret
            else:
                ret = [(ret[i][0] + lret[i][0] * beta_dl[i],
                        ret[i][1] + lret[i][1],
                        ret[i][2] + lret[i][2]) for i in range(len(lret))]
        return ret

596
    @mcmc_sweep_wrap
597
598
    def mcmc_sweep(self, **kwargs):
        r"""Perform ``niter`` sweeps of a Metropolis-Hastings acceptance-rejection
Tiago Peixoto's avatar
Tiago Peixoto committed
599
        MCMC to sample hierarchical network partitions.
600
601

        The arguments accepted are the same as in
602
        :meth:`graph_tool.inference.BlockState.mcmc_sweep`.
603
604
605
606
607

        If the parameter ``c`` is a scalar, the values used at each level are
        ``c * 2 ** l`` for ``l`` in the range ``[0, L-1]``. Optionally, a list
        of values may be passed instead, which specifies the value of ``c[l]``
        to be used at each level.
Tiago Peixoto's avatar
Tiago Peixoto committed
608
609
610
611
612
613
614
615

        .. warning::

           This function performs ``niter`` sweeps at each hierarchical level
           once. This means that in order for the chain to equilibrate, we need
           to call this function several times, i.e. it is not enough to call
           it once with a large value of ``niter``.

616
        """
617

618
        c = kwargs.pop("c", 1)
619
        if not isinstance(c, collections.abc.Iterable):
620
            c = [c * 2 ** l for l in range(0, len(self.levels))]
Tiago Peixoto's avatar
Tiago Peixoto committed
621

622
        if kwargs.pop("dispatch", True):
623
624
            return self._h_sweep(lambda s, **a: s.mcmc_sweep(**a), c=c,
                                 **kwargs)
625
626
627
628
629
630
631
        else:
            return self._h_sweep_states(lambda s, **a: s.mcmc_sweep(**a),
                                        c=c, **kwargs)

    def _mcmc_sweep_parallel_dispatch(states, sweeps):
        algo = lambda s, lstates, lsweep_states: s._mcmc_sweep_parallel_dispatch(lstates, lsweep_states)
        return NestedBlockState._h_sweep_parallel_dispatch(states, sweeps, algo)
632

633
    @mcmc_sweep_wrap
634
635
636
637
638
    def multiflip_mcmc_sweep(self, **kwargs):
        r"""Perform ``niter`` sweeps of a Metropolis-Hastings acceptance-rejection MCMC
        with multiple moves to sample hierarchical network partitions.

        The arguments accepted are the same as in
639
        :meth:`graph_tool.inference.BlockState.multiflip_mcmc_sweep`.
640
641
642
643
644
645

        If the parameter ``c`` is a scalar, the values used at each level are
        ``c * 2 ** l`` for ``l`` in the range ``[0, L-1]``. Optionally, a list
        of values may be passed instead, which specifies the value of ``c[l]``
        to be used at each level.

Tiago Peixoto's avatar
Tiago Peixoto committed
646
647
648
649
650
651
652
        .. warning::

           This function performs ``niter`` sweeps at each hierarchical level
           once. This means that in order for the chain to equilibrate, we need
           to call this function several times, i.e. it is not enough to call
           it once with a large value of ``niter``.

653
654
        """

655
        kwargs["psingle"] = kwargs.get("psingle", self.levels[0].get_N())
656

657
        c = kwargs.pop("c", 1)
658
        if not isinstance(c, collections.abc.Iterable):
659
            c = [c * 2 ** l for l in range(0, len(self.levels))]
660

661
        if kwargs.pop("dispatch", True):
662
663
664
665
666
667
668
669
670
671
            def dispatch_level(s, **a):
                if s is not self.levels[0]:
                    a = dict(**a)
                    a.pop("B_min", None)
                    a.pop("B_max", None)
                    a.pop("b_min", None)
                    a.pop("b_max", None)
                return s.multiflip_mcmc_sweep(**a)

            return self._h_sweep(dispatch_level, c=c, **kwargs)
672
673
674
675
676
677
        else:
            return self._h_sweep_states(lambda s, **a: s.multiflip_mcmc_sweep(**a),
                                        c=c, **kwargs)

    def _multiflip_mcmc_sweep_parallel_dispatch(states, sweeps):
        algo = lambda s, lstates, lsweep_states: s._multiflip_mcmc_sweep_parallel_dispatch(lstates, lsweep_states)
678
679
        return NestedBlockState._h_sweep_parallel_dispatch(states, sweeps, algo)

680
    @mcmc_sweep_wrap
681
    def multilevel_mcmc_sweep(self, **kwargs):
Tiago Peixoto's avatar
Tiago Peixoto committed
682
683
684
685
        r"""Perform ``niter`` sweeps of a Metropolis-Hastings acceptance-rejection MCMC
        with multilevel moves to sample hierarchical network partitions.

        The arguments accepted are the same as in
686
        :meth:`graph_tool.inference.BlockState.multilevel_mcmc_sweep`.
Tiago Peixoto's avatar
Tiago Peixoto committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701

        If the parameter ``c`` is a scalar, the values used at each level are
        ``c * 2 ** l`` for ``l`` in the range ``[0, L-1]``. Optionally, a list
        of values may be passed instead, which specifies the value of ``c[l]``
        to be used at each level.

        .. warning::

           This function performs ``niter`` sweeps at each hierarchical level
           once. This means that in order for the chain to equilibrate, we need
           to call this function several times, i.e. it is not enough to call
           it once with a large value of ``niter``.

        """

702
703
704
705
706
707
708
        kwargs["psingle"] = kwargs.get("psingle", self.g.num_vertices())

        c = kwargs.pop("c", 1)
        if not isinstance(c, collections.abc.Iterable):
            c = [c * 2 ** l for l in range(0, len(self.levels))]

        if kwargs.pop("dispatch", True):
709
710
            return self._h_sweep(lambda s, **a: s.multilevel_mcmc_sweep(**a),
                                 c=c, **kwargs)
711
712
713
714
715
716
        else:
            return self._h_sweep_states(lambda s, **a: s.multilevel_mcmc_sweep(**a),
                                        c=c, **kwargs)

    def _multilevel_mcmc_sweep_parallel_dispatch(states, sweeps):
        algo = lambda s, lstates, lsweep_states: s._multilevel_mcmc_sweep_parallel_dispatch(lstates, lsweep_states)
717
        return NestedBlockState._h_sweep_parallel_dispatch(states, sweeps, algo)
718

719
    @mcmc_sweep_wrap
720
721
722
723
724
    def gibbs_sweep(self, **kwargs):
        r"""Perform ``niter`` sweeps of a rejection-free Gibbs sampling MCMC
        to sample network partitions.

        The arguments accepted are the same as in
725
        :meth:`graph_tool.inference.BlockState.gibbs_sweep`.
Tiago Peixoto's avatar
Tiago Peixoto committed
726
727
728
729
730
731
732
733

        .. warning::

           This function performs ``niter`` sweeps at each hierarchical level
           once. This means that in order for the chain to equilibrate, we need
           to call this function several times, i.e. it is not enough to call
           it once with a large value of ``niter``.

734
        """
735
736
        return self._h_sweep(lambda s, **a: s.gibbs_sweep(**a),
                             **kwargs)
737
738
739
740
741

    def _gibbs_sweep_parallel_dispatch(states, sweeps):
        algo = lambda s, lstates, lsweep_states: s._gibbs_sweep_parallel_dispatch(lstates, lsweep_states)
        return NestedBlockState._h_sweep_parallel_dispatch(states, sweeps, algo)

742
    @mcmc_sweep_wrap
743
    def multicanonical_sweep(self, m_state, **kwargs):
744
745
746
747
        r"""Perform ``niter`` sweeps of a non-Markovian multicanonical sampling using the
        Wang-Landau algorithm.

        The arguments accepted are the same as in
748
        :meth:`graph_tool.inference.BlockState.multicanonical_sweep`.
749
        """
750
751
752
753
754
755
756
757
758
759

        def sweep(s, **kwargs):
            S = 0
            for l, state in enumerate(self.levels):
                if s is state:
                    continue
                S += self.level_entropy(l)
            return s.multicanonical_sweep(m_state, entropy_offset=S, **kwargs)

        return self._h_sweep(sweep)
760

761
762
763
764
    def collect_partition_histogram(self, h=None, update=1):
        r"""Collect a histogram of partitions.

        This should be called multiple times, e.g. after repeated runs of the
765
        :meth:`graph_tool.inference.NestedBlockState.mcmc_sweep` function.
766
767
768

        Parameters
        ----------
769
        h : :class:`~graph_tool.inference.PartitionHist` (optional, default: ``None``)
770
771
772
773
774
775
776
            Partition histogram. If not provided, an empty histogram will be created.
        update : float (optional, default: ``1``)
            Each call increases the current count by the amount given by this
            parameter.

        Returns
        -------
777
        h : :class:`~graph_tool.inference.PartitionHist` (optional, default: ``None``)
778
779
780
781
782
783
784
785
786
787
            Updated Partition histogram.

        """

        if h is None:
            h = PartitionHist()
        bs = [_prop("v", state.g, state.b) for state in self.levels]
        libinference.collect_hierarchical_partitions(bs, h, update)
        return h

788
789
790
791
792
793
    def draw(self, **kwargs):
        r"""Convenience wrapper to :func:`~graph_tool.draw.draw_hierarchy` that
        draws the hierarchical state."""
        import graph_tool.draw
        return graph_tool.draw.draw_hierarchy(self, **kwargs)

794
def get_hierarchy_tree(state, empty_branches=False):
795
796
    r"""Obtain the nested hierarchical levels as a tree.

797
    This transforms a :class:`~graph_tool.inference.NestedBlockState` instance
798
799
800
801
802
    into a single :class:`~graph_tool.Graph` instance containing the hierarchy
    tree.

    Parameters
    ----------
803
    state : :class:`~graph_tool.inference.NestedBlockState`
804
       Nested block model state.
805
    empty_branches : ``bool`` (optional, default: ``False``)
806
807
808
809
810
811
812
813
814
       If ``empty_branches == False``, dangling branches at the upper layers
       will be pruned.

    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.
815
    label : :class:`~graph_tool.VertexPropertyMap`
816
       A vertex property map containing the block label for each node.
817
    order : :class:`~graph_tool.VertexPropertyMap`
818
819
820
821
822
823
824
825
826
827
828
829
830
831
       A vertex property map containing the relative ordering of each layer
       according to the total degree of the groups at the specific levels.
    """

    bstack = state.get_bstack()

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

    if bstack[-1].num_vertices() > 1:
        bg = Graph(directed=g.is_directed())
        bg.add_vertex()
        e = bg.add_edge(0, 0)
832
833
834
        bg.vp.count = bg.new_vp("int", 1)
        bg.ep.count = bg.new_ep("int", g.ep.count.fa.sum())
        bg.vp.b = bg.new_vp("int", 0)
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
        bstack.append(bg)

    t = Graph()

    if g.get_vertex_filter()[0] is None:
        t.add_vertex(g.num_vertices())
    else:
        t.add_vertex(g.num_vertices(ignore_filter=True))
        filt = g.get_vertex_filter()
        t.set_vertex_filter(t.own_property(filt[0].copy()),
                            filt[1])
    label = t.vertex_index.copy("int")

    order = t.own_property(g.degree_property_map("total").copy())
    t_vertices = list(t.vertices())

    last_pos = 0
    for l, s in enumerate(bstack):
        pos = t.num_vertices()
        if s.num_vertices() > 1:
            t_vertices.extend(t.add_vertex(s.num_vertices()))
        else:
            t_vertices.append(t.add_vertex(s.num_vertices()))
        label.a[-s.num_vertices():] = arange(s.num_vertices())

        # relative ordering based on total degree
        count = s.ep["count"].copy("double")
        for e in s.edges():
            if e.source() == e.target():
                count[e] /= 2
        vs = []
        pvs = {}
        for vi in range(pos, t.num_vertices()):
            vs.append(t_vertices[vi])
            pvs[vs[-1]] = vi - pos
        vs = sorted(vs, key=lambda v: (s.vertex(pvs[v]).out_degree(count) +
                                       s.vertex(pvs[v]).in_degree(count)))
        for vi, v in enumerate(vs):
            order[v] = vi

        for vi, v in enumerate(g.vertices()):
            w = t_vertices[vi + last_pos]
877
878
879
880
            if s.num_vertices() == 1:
                u = t_vertices[pos]
            else:
                u = t_vertices[b[v] + pos]
881
882
883
884
            t.add_edge(u, w)

        last_pos = pos
        g = s
Tiago Peixoto's avatar
Tiago Peixoto committed
885
886
887
888
889
890
        if empty_branches:
            if g.num_vertices() == 1:
                break
        else:
            if g.vp.count.fa.sum() == 1:
                break
891
892
893
        b = g.vp["b"]

    if not empty_branches:
894
        vmask = t.new_vertex_property("bool", True)
895
896
897
898
899
900
        t = GraphView(t, vfilt=vmask)
        vmask = t.get_vertex_filter()[0]
        N = t.num_vertices()
        for vi, v in enumerate(list(t.vertices())):
            if vi < state.g.num_vertices():
                continue
901
902
            if v.out_degree() == 0:
                vmask[v] = False
903
904
        label = t.own_property(label)
        order = t.own_property(order)
905
906
907
908

    return t, label, order

from . minimize import *