nested_blockmodel.py 34.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2016 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

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

from .. import _degree, _prop, Graph, GraphView, conv_pickle_state
from . blockmodel import *
from . blockmodel import _bm_test
from . overlap_blockmodel import *
from . layered_blockmodel import *

from numpy import *
import numpy
import copy

36
def get_edges_dl(state, hstate_args, hentropy_args):
37
    bclabel = state.get_bclabel()
38 39 40
    bstate = state.get_block_state(b=bclabel, **hstate_args)
    return bstate.entropy(**overlay(hentropy_args, dl=True, edges_dl=False,
                                    multigraph=True))
41 42 43 44 45 46 47 48


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
49
        Graph to be modeled.
50 51
    bs : ``list`` of :class:`~graph_tool.PropertyMap` or :class:`numpy.ndarray`
        Hierarchical node partition.
52
    base_type : ``type`` (optional, default: :class:`~graph_tool.inference.BlockState`)
Tiago Peixoto's avatar
Tiago Peixoto committed
53 54 55 56
        State type for lowermost level
        (e.g. :class:`~graph_tool.inference.BlockState`,
        :class:`~graph_tool.inference.OverlapBlockState` or
        :class:`~graph_tool.inference.LayeredBlockState`)
57 58 59 60 61 62 63 64 65
    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.
    sampling : ``bool`` (optional, default: ``False``)
        If ``True``, the state will be properly prepared for MCMC sampling (as
        opposed to minimization).
66 67 68
    **kwargs :  keyword arguments
        Keyword arguments to be passed to base type constructor.
    """
69

70 71
    def __init__(self, g, bs, base_type=BlockState, hstate_args={},
                 hentropy_args={}, sampling=False, **kwargs):
72
        self.g = g
73
        self.kwargs = kwargs.copy()
74
        self.hstate_args = overlay(dict(deg_corr=False), **hstate_args)
75
        self.sampling = sampling
76 77 78 79 80 81 82 83 84 85 86 87
        if sampling:
            self.hstate_args = overlay(self.hstate_args, vweight="nonempty",
                                       copy_bg=False, B=g.num_vertices())
            self.kwargs = overlay(self.kwargs, vweight="unity", eweight="unity",
                                  B=g.num_vertices())
            nbs = []
            for b in bs:
                nb = numpy.zeros(g.num_vertices(), dtype="int")
                nb[:len(b)] = b
                nbs.append(nb)
            bs = nbs
        self.hentropy_args = overlay(dict(adjacency=True,
88 89 90 91
                                          dense=True,
                                          multigraph=True,
                                          dl=True,
                                          partition_dl=True,
92 93
                                          degree_dl=True,
                                          degree_dl_kind="distributed",
94 95
                                          edges_dl=True,
                                          exact=True),
96
                                     **hentropy_args)
97 98 99
        self.levels = [base_type(g, b=bs[0], **self.kwargs)]
        for b in bs[1:]:
            state = self.levels[-1]
100
            bstate = state.get_block_state(b=b, **self.hstate_args)
101 102 103 104 105
            self.levels.append(bstate)

        if _bm_test():
            self._consistency_check()

106 107 108
    def _regen_levels(self):
        for l in range(1, len(self.levels)):
            state = self.levels[l]
109 110
            nstate = self.levels[l-1].get_block_state(b=state.b,
                                                      **self.hstate_args)
111 112
            self.levels[l] = nstate

113 114 115
    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),
116
             str([(s.get_N(), s.get_nonempty_B()) for s in self.levels]), id(self))
117 118 119 120 121 122 123 124

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

    def __deepcopy__(self, memo):
        g = copy.deepcopy(self.g, memo)
        return self.copy(g=g)

125 126
    def copy(self, g=None, bs=None, hstate_args=None, hentropy_args=None,
             sampling=None, **kwargs):
127 128 129 130 131
        r"""Copies the block state. The parameters override the state properties,
        and have the same meaning as in the constructor."""
        bs = self.get_bs() if bs is None else bs
        return NestedBlockState(self.g if g is None else g, bs,
                                base_type=type(self.levels[0]),
132 133 134
                                hstate_args=self.hstate_args if hstate_args is None else hstate_args,
                                hentropy_args=self.hentropy_args if hentropy_args is None else hentropy_args,
                                sampling=self.sampling if sampling is None else sampling,
135 136 137
                                **overlay(self.kwargs, **kwargs))

    def __getstate__(self):
138 139
        state = dict(g=self.g, bs=self.get_bs(), base_type=type(self.levels[0]),
                     hstate_args=self.hstate_args,
Tiago Peixoto's avatar
Tiago Peixoto committed
140
                     hentropy_args=self.hentropy_args, sampling=self.sampling,
141
                     kwargs=self.kwargs)
142 143 144 145
        return state

    def __setstate__(self, state):
        conv_pickle_state(state)
Tiago Peixoto's avatar
Tiago Peixoto committed
146
        self.__init__(**overlay(dmask(state, ["kwargs"]), **state["kwargs"]))
147

148 149 150 151 152 153 154 155 156 157 158
    def get_bs(self):
        """Get hierarchy levels as a list of :class:`numpy.ndarray` objects with the
        group memberships at each level.
        """
        return [s.b.fa for s in self.levels]

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

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
    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

186 187 188 189
    def impose_bclabels(self):
        for l in range(len(self.levels) - 1):
            self.levels[l].bclabel.a = self.levels[l + 1].b.a

190 191 192 193
    def _consistency_check(self):
        for l in range(1, len(self.levels)):
            b = self.levels[l].b.fa.copy()
            state = self.levels[l-1]
194
            bstate = state.get_block_state(b=b, **self.hstate_args)
195 196 197 198 199 200 201 202
            b2 = bstate.b.fa.copy()
            continuous_map(b)
            continuous_map(b2)
            assert ((b == b2).all() and
                    (bstate.entropy() - self.levels[l].entropy())) < 1e-6, \
                "inconsistent level %d (%s %g,  %s %g): %s" % \
                (l, str(bstate), bstate.entropy(), str(self.levels[l]),
                 self.levels[l].entropy(), str(self))
203 204
            assert (bstate.get_N() >= bstate.get_nonempty_B()), \
                (l, bstate.get_N(), bstate.get_nonempty_B(), str(self))
205 206 207 208 209 210 211 212 213 214 215

    def replace_level(self, l, b):
        """Replace level ``l`` given the new partition ``b``"""

        if l < len(self.levels) - 1:
            clabel = self.project_partition(l + 1, l)
        self.levels[l] = self.levels[l].copy(b=b)
        if l < len(self.levels) - 1:
            bclabel = self.levels[l].bg.new_vertex_property("int")
            reverse_map(self.levels[l].b, bclabel)
            pmap(bclabel, clabel)
216 217
            bstate = self.levels[l].get_block_state(b=bclabel,
                                                    **self.hstate_args)
218 219 220 221 222 223 224 225 226 227
            self.levels[l + 1] = bstate

        if _bm_test():
            self._consistency_check()

    def delete_level(self, l):
        """Delete level ``l``."""
        if l == 0:
            raise ValueError("cannot delete level l=0")
        b = self.project_partition(l, l - 1)
228
        self.replace_level(l - 1, b.fa)
229 230 231 232 233 234 235 236 237 238 239 240 241
        del self.levels[l]

        if _bm_test():
            self._consistency_check()

    def duplicate_level(self, l):
        """Duplicate level ``l``."""
        bstate = self.levels[l].copy(b=self.levels[l].g.vertex_index.copy("int").fa)
        self.levels.insert(l, bstate)

        if _bm_test():
            self._consistency_check()

242
    def level_entropy(self, l, bstate=None, **kwargs):
243 244 245 246 247
        """Compute the entropy of level ``l``."""

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

248
        if l > 0:
249
            eargs = self.hentropy_args
250 251 252 253 254
        else:
            eargs = kwargs

        S = bstate.entropy(**overlay(eargs, dl=True,
                                     edges_dl=(l == (len(self.levels) - 1))))
255 256
        return S

257
    def entropy(self, **kwargs):
Tiago Peixoto's avatar
Tiago Peixoto committed
258 259
        """Compute the entropy of whole hierarchy.

260 261
        The keyword arguments are passed to the ``entropy()`` method of the
        underlying state objects
Tiago Peixoto's avatar
Tiago Peixoto committed
262 263
        (e.g. :class:`graph_tool.inference.BlockState.entropy`,
        :class:`graph_tool.inference.OverlapBlockState.entropy`, or
264
        :class:`graph_tool.inference.LayeredBlockState.entropy`).  """
265 266
        S = 0
        for l in range(len(self.levels)):
267
            S += self.level_entropy(l, **kwargs)
268 269
        return S

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
    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()

302 303 304 305 306 307 308 309
    def get_edges_prob(self, edge_list, missing=True, entropy_args={}):
        """Compute the log-probability of the missing (or spurious if ``missing=False``)
        edges given by ``edge_list`` (a list of ``(source, target)`` tuples, or
        :meth:`~graph_tool.Edge` instances). The values in ``entropy_args`` are
        passed to :meth:`graph_tool.NestedBlockState.entropy()` to calculate the
        log-probability.
        """
        L = 0
310
        for l, lstate in enumerate(self.levels):
311
            if l > 0:
312 313 314 315 316 317 318 319 320 321 322
                eargs = self.hentropy_args
            else:
                eargs = entropy_args

            eargs = overlay(eargs, dl=True,
                            edges_dl=(l == (len(self.levels) - 1)))

            if self.sampling:
                lstate._couple_state(None, None)
                if l > 0:
                    lstate._state.sync_emat()
323
                    lstate._state.clear_egroups()
324 325 326 327 328 329

            L += lstate.get_edges_prob(edge_list, missing, entropy_args=eargs)
            if isinstance(self.levels[0], LayeredBlockState):
                edge_list = [(lstate.b[u], lstate.b[v], l) for u, v, l in edge_list]
            else:
                edge_list = [(lstate.b[u], lstate.b[v]) for u, v in (tuple(e_) for e_ in edge_list)]
330 331
        return L

332

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    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()
349 350 351
            if bstate.is_weighted:
                cg.ep["count"] = cg.own_property(bstate.eweight.copy())
                cg.vp["count"] = cg.own_property(bstate.vweight.copy())
352 353 354 355
            else:
                cg.ep["count"] = cg.new_ep("int", 1)

            bstack.append(cg)
356
            if bstate.get_N() == 1:
357 358 359 360 361 362 363
                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)
364
        return self.levels[0].copy(b=b)
365 366 367 368

    def print_summary(self):
        """Print a hierarchy summary."""
        for l, state in enumerate(self.levels):
369 370
            print("l: %d, N: %d, B: %d" % (l, state.get_N(),
                                           state.get_nonempty_B()))
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

    def find_new_level(self, l, sparse_thres=100, bisection_args={}, B_min=None,
                       B_max=None, b_min=None, b_max=None):
        """Attempt to find a better network partition at level ``l``, using
        :func:`~graph_tool.inference.bisection_minimize` with arguments given by
        ``bisection_args``.

        If the number of nodes is larger than `sparse_thres`, the graph is
        treated as a sparse graph for minimization purposes (the full entropy is
        always computed exactly).
        """

        # assemble minimization arguments
        mcmc_multilevel_args = bisection_args.get("mcmc_multilevel_args", {})
        mcmc_equilibrate_args = mcmc_multilevel_args.get("mcmc_equilibrate_args", {})
        mcmc_args = mcmc_equilibrate_args.get("mcmc_args", {})
        entropy_args = mcmc_args.get("entropy_args", {})
        entropy_args = overlay(entropy_args, dl=True,
                               edges_dl=l==len(self.levels) - 1)
        extra_entropy_args = bisection_args.get("extra_entropy_args", {})
391
        if l > 0 and self.hentropy_args.get("dense"):
392
            entropy_args = overlay(entropy_args,
393 394
                                   dense=self.levels[l].get_N() < sparse_thres)
            if self.levels[l].get_N() >= sparse_thres:
395 396
                extra_entropy_args = overlay(extra_entropy_args, dense=True)
        if l < len(self.levels) - 1:
397 398 399 400 401 402 403
            entropy_args = overlay(entropy_args,
                                   callback=lambda s: get_edges_dl(s,
                                                                   self.hstate_args,
                                                                   self.hentropy_args))
        mcmc_args = overlay(mcmc_args, entropy_args=entropy_args,
                            disable_callback_test=isinstance(self.levels[0],
                                                             LayeredBlockState))
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
        if l > 0:
            mcmc_args = dmask(mcmc_args, ["bundled"])
        mcmc_equilibrate_args = overlay(mcmc_equilibrate_args,
                                        mcmc_args=mcmc_args)
        mcmc_multilevel_args = overlay(mcmc_multilevel_args,
                                       mcmc_equilibrate_args=mcmc_equilibrate_args)
        bisection_args = overlay(bisection_args,
                                 mcmc_multilevel_args=mcmc_multilevel_args,
                                 extra_entropy_args=extra_entropy_args)

        # construct boundary states and constraints
        clabel = self.get_clabel(l)
        state = self.levels[l]
        if b_max is None:
            b_max = state.g.vertex_index.copy("int").a
419 420 421
        else:
            b_max = b_max + (b_max.max() + 1) * clabel.fa
            continuous_map(b_max)
422 423 424 425 426 427
        max_state = state.copy(b=b_max, clabel=clabel)
        if B_max is not None and max_state.B > B_max:
            max_state = mcmc_multilevel(max_state, B_max,
                                        **mcmc_multilevel_args)
        if l < len(self.levels) - 1:
            if B_min is None:
428
                min_state = state.copy(b=clabel.fa, clabel=clabel.fa)
429
            else:
430
                B_min = max(B_min, clabel.fa.max() + 1)
431 432 433
                min_state = mcmc_multilevel(max_state, B_min,
                                            **mcmc_multilevel_args)
            if _bm_test():
434 435
                assert min_state.B == self.levels[l+1].B, (min_state.B,
                                                           self.levels[l+1].B)
436
        else:
437
            min_state = state.copy(b=clabel.fa, clabel=clabel.fa)
438 439 440 441
        if B_min is not None and  min_state.B > B_min:
            min_state = mcmc_multilevel(min_state, B_min,
                                        **mcmc_multilevel_args)

442 443 444 445
        if _bm_test():
            assert min_state._check_clabel(), "invalid clabel %s" % str((l, self))
            assert max_state._check_clabel(), "invalid clabel %s" % str((l, self))

446 447 448 449 450
        # find new state
        state = bisection_minimize([min_state, max_state], **bisection_args)

        if _bm_test():
            assert state.B >= min_state.B, (l, state.B, min_state.B, str(self))
451
            assert state._check_clabel(), "invalid clabel %s" % str((l, self))
452 453
        return state

454 455 456 457 458 459
    def _h_sweep(self, algo, **kwargs):
        verbose = kwargs.get("verbose", False)
        entropy_args = kwargs.get("entropy_args", {})

        for l in range(len(self.levels) - 1):
            eargs = overlay(self.hentropy_args,
460
                            edges_dl=(l + 1 == len(self.levels) - 1))
461 462 463 464 465 466 467 468 469 470
            self.levels[l]._couple_state(self.levels[l + 1],
                                         get_entropy_args(eargs))
            self.levels[l + 1]._state.clear_egroups()
            self.levels[l + 1]._state.sync_emat()

        self.impose_bclabels()

        dS = 0
        nmoves = 0

471 472
        c = kwargs.get("c", None)

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
        for l in range(len(self.levels)):
            if check_verbose(verbose):
                print(verbose_pad(verbose) + "level:", l)
            if l > 0:
                eargs = overlay(self.hentropy_args,
                                **overlay(entropy_args, multigraph=True))
            else:
                eargs = entropy_args

            eargs = overlay(eargs, dl=True,
                            edges_dl=(l == len(self.levels) - 1))

            if l < len(self.levels) - 1:
                def callback(s):
                    s = self.levels[l + 1]
                    S = s.entropy(**overlay(self.hentropy_args,
489
                                            edges_dl=(l + 1 == len(self.levels) - 1)))
490 491 492 493 494
                    return S
                eargs = overlay(eargs, callback=callback)

            if l > 0:
                self.levels[l]._state.sync_emat()
Tiago Peixoto's avatar
Tiago Peixoto committed
495
                self.levels[l]._state.rebuild_neighbour_sampler()
496 497 498
            if l < len(self.levels) - 1:
                self.levels[l + 1]._state.sync_emat()

499 500 501 502 503 504 505
            if c is None:
                args = overlay(kwargs, entropy_args=eargs)
            else:
                args = overlay(kwargs, entropy_args=eargs, c=c[l])

            ret = algo(self.levels[l], **args)

506 507 508 509 510 511 512
            dS += ret[0]
            nmoves += ret[1]

        return dS, nmoves

    def mcmc_sweep(self, **kwargs):
        r"""Perform ``niter`` sweeps of a Metropolis-Hastings acceptance-rejection
Tiago Peixoto's avatar
Tiago Peixoto committed
513
        MCMC to sample hierarchical network partitions.
514 515 516

        The arguments accepted are the same as in
        :method:`graph_tool.inference.BlockState.mcmc_sweep`.
517 518 519 520 521

        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.
522
        """
523

Tiago Peixoto's avatar
Tiago Peixoto committed
524 525 526 527 528
        c = extract_arg(kwargs, "c", 1)
        if not isinstance(c, collections.Iterable):
            c = [c] + [c * 2 ** l for l in range(1, len(self.levels))]

        return self._h_sweep(lambda s, **a: s.mcmc_sweep(**a), c=c, **kwargs)
529 530

    def gibbs_sweep(self, **kwargs):
Tiago Peixoto's avatar
Tiago Peixoto committed
531 532
        r"""Perform ``niter`` sweeps of a rejection-free Gibbs MCMC to sample network
        partitions.
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547

        The arguments accepted are the same as in
        :method:`graph_tool.inference.BlockState.gibbs_sweep`.
        """
        return self._h_sweep(lambda s, **a: s.gibbs_sweep(**a))

    def multicanonical_sweep(self, **kwargs):
        r"""Perform ``niter`` sweeps of a non-Markovian multicanonical sampling using the
        Wang-Landau algorithm.

        The arguments accepted are the same as in
        :method:`graph_tool.inference.BlockState.multicanonical_sweep`.
        """
        return self._h_sweep(lambda s, **a: s.multicanonical_sweep(**a))

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
    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
        :meth:`graph_tool.inference.NestedBlockState.mcmc_sweep` function.

        Parameters
        ----------
        h : :class:`~graph_tool.inference.PartitionHist` (optional, default: ``None``)
            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
        -------
        h : :class:`~graph_tool.inference.PartitionHist` (optional, default: ``None``)
            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

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    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)



def hierarchy_minimize(state, B_min=None, B_max=None, b_min=None, b_max=None,
                       frozen_levels=None, sparse_thres=100, bisection_args={},
                       verbose=False):
    """Attempt to find a fit of the nested stochastic block model that minimizes the
    description length.

    Parameters
    ----------
    state : :class:`~graph_tool.inference.NestedBlockState`
        The nested block state.
    B_min : ``int`` (optional, default: ``None``)
        The minimum number of blocks.
    B_max : ``int`` (optional, default: ``None``)
        The maximum number of blocks.
    b_min : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        The partition to be used with the minimum number of blocks.
    b_max : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        The partition to be used with the maximum number of blocks.
    frozen_levels : sequence of ``int``s (optional, default: ``None``)
        List of hierarchy levels that are kept constant during the minimization.
    sparse_thres : int (optional, default: ``100``)
        If the number of nodes in a given level is larger than `sparse_thres`,
        the graph is treated as a sparse graph for minimization purposes (the
        full entropy is always computed exactly).
    bisection_args : ``dict`` (optional, default: ``{}``)
        Arguments to be passed to :func:`~graph_tool.inference.bisection_minimize`.
    verbose : ``bool`` or ``tuple`` (optional, default: ``False``)
        If ``True``, progress information will be shown. Optionally, this
        accepts arguments of the type ``tuple`` of the form ``(level, prefix)``
        where ``level`` is a positive integer that specifies the level of
        detail, and ``prefix`` is a string that is prepended to the all output
        messages.

    Returns
    -------
    min_state : :class:`~graph_tool.inference.NestedBlockState`
        Nested state with minimal description length.

    Notes
    -----

    This algorithms moves along the hierarchical levels, attempting to replace,
    delete or insert partitions that minimize the description length, until no
    further progress is possible.

    See [peixoto-hierarchical-2014]_ for details on the algorithm.

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

    References
    ----------

    .. [peixoto-hierarchical-2014] Tiago P. Peixoto, "Hierarchical block
       structures and high-resolution model selection in large networks ",
       Phys. Rev. X 4, 011047 (2014), :doi:`10.1103/PhysRevX.4.011047`,
       :arxiv:`1310.4377`.
    """

    dS = 0

    if frozen_levels is None:
        frozen_levels = set()

    l = len(state.levels) - 1  # begin from top!
    done = []
    while l >= 0:

        bisection_args = overlay(bisection_args,
                                 verbose=verbose_push(verbose, ("    l=%d  " % l)))

        while len(done) < len(state.levels) + 2:
            done.append(False)

        if done[l]:
            if check_verbose(verbose):
                print(verbose_pad(verbose) + "level", l, ": skipping",
                      state.levels[l].B)
            l -= 1
            continue

        Si = state.entropy()

        kept = True

        if l in frozen_levels:
            kept = False

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

            if l < len(state.levels) - 1:
                bstates = [state.levels[l], state.levels[l+1]]
            else:
                bstates = [state.levels[l]]

            if l == 0:
                bstate = state.find_new_level(l, bisection_args=bisection_args,
                                              B_min=B_min, B_max=B_max,
                                              b_min=b_min, b_max=b_max)
            else:
                bstate = state.find_new_level(l, bisection_args=bisection_args)
            state.replace_level(l, bstate.b.fa)

            Sf = state.entropy()

            if Sf < Si:
                kept = False
                dS += Sf - Si

                if check_verbose(verbose):
                    print(verbose_pad(verbose) + "level", l, ": replaced",
696 697 698
                          (bstates[0].get_N(), bstates[0].get_nonempty_B()), "->",
                          (bstate.get_N(), bstate.get_nonempty_B()),", dS:",
                          Sf - Si, len(state.levels))
699 700 701 702 703 704
            else:
                state.levels[l:l+len(bstates)] = bstates

                if check_verbose(verbose):
                    print(verbose_pad(verbose) + "level", l,
                          ": rejected replacement",
705 706 707
                          (bstates[0].get_N(), bstates[0].get_nonempty_B()), "->",
                          (bstate.get_N(), bstate.get_nonempty_B()),", dS:",
                          Sf - Si)
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

        # delete level
        if (kept and l > 0 and l < len(state.levels) - 1 and
            not (B_min is not None and l == 1 and state.levels[l].B < B_min)):

            Si = state.entropy()

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

            state.delete_level(l)

            Sf = state.entropy()

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

                if check_verbose(verbose):
                    print(verbose_pad(verbose) + "level", l, ": deleted",
731 732
                          (bstates[1].get_N(), bstates[1].get_nonempty_B()),
                          ", dS:", Sf - Si, len(state.levels))
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 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843

            if _bm_test():
                if kept:
                    assert abs(state.entropy() - Si) < 1e-6, \
                    "inconsistent delete at level %d (%g, %g)" % \
                    (l, state.entropy(), Si)

        # insert new level (duplicate and replace)
        if kept and l > 0:
            Si = state.entropy()

            bstates = [state.levels[l]]
            if l < len(state.levels) - 1:
                bstates.append(state.levels[l + 1])
            if l < len(state.levels) - 2:
                bstates.append(state.levels[l + 2])

            state.duplicate_level(l)
            bstate = state.find_new_level(l + 1, bisection_args=bisection_args)
            state.replace_level(l + 1, bstate.b.fa)

            Sf = state.entropy()

            if Sf >= Si:
                if check_verbose(verbose):
                    print(verbose_pad(verbose) + "level", l, ": rejected insert",
                          state.levels[l].B, ", dS:", Sf - Si)

                del state.levels[l + 1]
                for j in range(len(bstates)):
                    state.levels[l + j] = bstates[j]
                if bstates[-1].B == 1:
                    del state.levels[l + len(bstates):]
            else:
                kept = False
                dS += Sf - Si

                l += 1
                done.insert(l, False)

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

        # create a new level at the top with B=1, if necessary
        if state.levels[-1].B > 1:
            bstate = state.levels[-1]
            bstate = bstate.get_block_state(b=zeros(state.levels[-1].B),
                                            deg_corr=False)
            state.levels.append(bstate)
            if _bm_test():
                state._consistency_check()

        done[l] = True
        if not kept:
            if l + 1 < len(state.levels):
                done[l+1] = False
            if l > 0:
                done[l-1] = False
            l += 1
        else:
            if ((l + 1 < len(state.levels) and not done[l + 1]) or
                (l + 1 == len(state.levels) and state.levels[l].B > 1)):
                l += 1
            else:
                l -= 1

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

    return dS


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

    This transforms a :class:`~graph_tool.inference.NestedBlockState` instance
    into a single :class:`~graph_tool.Graph` instance containing the hierarchy
    tree.

    Parameters
    ----------
    state : :class:`~graph_tool.inference.NestedBlockState`
       Nested block model state.
    empty_branches : ``bool`` (optional, default: ``True``)
       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.
    label : :class:`~graph_tool.PropertyMap`
       A vertex property map containing the block label for each node.
    order : :class:`~graph_tool.PropertyMap`
       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)
844 845 846
        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)
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
        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]
889 890 891 892
            if s.num_vertices() == 1:
                u = t_vertices[pos]
            else:
                u = t_vertices[b[v] + pos]
893 894 895 896 897 898 899 900 901
            t.add_edge(u, w)

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

    if not empty_branches:
902
        vmask = t.new_vertex_property("bool", True)
903 904 905 906 907 908
        t = GraphView(t, vfilt=vmask)
        vmask = t.get_vertex_filter()[0]

        for vi in range(state.g.num_vertices(ignore_filter=True),
                        t.num_vertices()):
            v = t.vertex(t_vertices[vi])
909 910
            if v.out_degree() == 0:
                vmask[v] = False
911 912 913

        t.vp.label = label
        t.vp.order = order
914
        t = Graph(t, prune=True)
915 916
        label = t.vp.label
        order = t.vp.order
917
        del t.vp["label"]
918
        del t.vp["order"]
919 920 921 922

    return t, label, order

from . minimize import *