blockmodel.py 121 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-2015 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
#
# 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

26
27
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, PropertyMap
from .. stats import label_self_loops
28
from .. spectral import adjacency
29
30
import random
from numpy import *
31
import numpy
32
33
from scipy.optimize import fsolve, fminbound
import scipy.special
34
from collections import defaultdict
35
36
import copy
import heapq
37
38
39
40

from .. dl_import import dl_import
dl_import("from . import libgraph_tool_community as libcommunity")

41
__test__ = False
42

43
44
45
46
47
48
49
50
def set_test(test):
    global __test__
    __test__ = test

def _bm_test():
    global __test__
    return __test__

51
52
53
54
55
56
57
58
59
60
61
62
def get_block_graph(g, B, b, vcount, ecount):
    cg, br, vcount, ecount = condensation_graph(g, b,
                                                vweight=vcount,
                                                eweight=ecount,
                                                self_loops=True)[:4]
    cg.vp["count"] = vcount
    cg.ep["count"] = ecount
    cg = Graph(cg, vorder=br)

    cg.add_vertex(B - cg.num_vertices())
    return cg

63
64
65
66
67
68
69
70
class BlockState(object):
    r"""This class encapsulates the block state of a given graph.

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

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
71
        Graph to be modelled.
72
    eweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
73
        Edge multiplicities (for multigraphs or block graphs).
74
    vweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
75
        Vertex multiplicities (for block graphs).
76
77
78
79
80
81
82
83
    b : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Initial block labels on the vertices. If not supplied, it will be
        randomly sampled.
    B : ``int`` (optional, default: ``None``)
        Number of blocks. If not supplied it will be either obtained from the
        parameter ``b``, or set to the maximum possible value according to the
        minimum description length.
    clabel : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
84
85
        Constraint labels on the vertices. If supplied, vertices with different
        label values will not be clustered in the same group.
86
87
88
    deg_corr : ``bool`` (optional, default: ``True``)
        If ``True``, the degree-corrected version of the blockmodel ensemble will
        be assumed, otherwise the traditional variant will be used.
89
90
91
92
    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,
93
94
    """

95
    def __init__(self, g, eweight=None, vweight=None, b=None,
96
97
                 B=None, clabel=None, deg_corr=True,
                 max_BE=1000, **kwargs):
98

99
        # initialize weights to unity, if necessary
100
101
        if eweight is None:
            eweight = g.new_edge_property("int")
102
            eweight.fa = 1
103
104
105
106
        elif eweight.value_type() != "int32_t":
            eweight = eweight.copy(value_type="int32_t")
        if vweight is None:
            vweight = g.new_vertex_property("int")
107
            vweight.fa = 1
108
109
        elif vweight.value_type() != "int32_t":
            vweight = vweight.copy(value_type="int32_t")
110
111
112
        self.eweight = g.own_property(eweight)
        self.vweight = g.own_property(vweight)

113
114
115
116
        self.is_weighted = False
        if ((g.num_edges() > 0 and self.eweight.fa.max() > 1) or
            kwargs.get("force_weighted", False)):
            self.is_weighted = True
117
118
119

        # configure the main graph and block model parameters
        self.g = g
120

121
122
        self.E = int(self.eweight.fa.sum())
        self.N = int(self.vweight.fa.sum())
123
124
125

        self.deg_corr = deg_corr

126
        # ensure we have at most as many blocks as nodes
127
        if B is not None and b is None:
128
129
            B = min(B, self.g.num_vertices())

130
        if b is None:
131
            # create a random partition into B blocks.
132
133
            if B is None:
                B = get_max_B(self.N, self.E, directed=g.is_directed())
134
135
            B = min(B, self.g.num_vertices())
            ba = random.randint(0, B, self.g.num_vertices())
136
            ba[:B] = arange(B)        # avoid empty blocks
137
138
            if B < self.g.num_vertices():
                random.shuffle(ba)
139
            b = g.new_vertex_property("int")
140
            b.fa = ba
141
142
            self.b = b
        else:
143
144
145
146
147
148
            # if a partition is available, we will incorporate it.
            if isinstance(b, numpy.ndarray):
                self.b = g.new_vertex_property("int")
                self.b.fa = b
            else:
                self.b = b = g.own_property(b.copy(value_type="int"))
149
            if B is None:
150
151
152
153
                B = int(self.b.fa.max()) + 1

        # if B > self.N:
        #     raise ValueError("B > N!")
154

155
        if self.b.fa.max() >= B:
156
            raise ValueError("Maximum value of b is larger or equal to B! (%d vs %d)" % (self.b.fa.max(), B))
157
158

        # Construct block-graph
159
        self.bg = get_block_graph(g, B, self.b, self.vweight, self.eweight)
160
161
162
163
        self.bg.set_fast_edge_removal()

        self.mrs = self.bg.ep["count"]
        self.wr = self.bg.vp["count"]
164

165
166
167
168
169
170
171
172
173
        del self.bg.ep["count"]
        del self.bg.vp["count"]

        self.mrp = self.bg.degree_property_map("out", weight=self.mrs)

        if g.is_directed():
            self.mrm = self.bg.degree_property_map("in", weight=self.mrs)
        else:
            self.mrm = self.mrp
174
175
176

        self.vertices = libcommunity.get_vector(B)
        self.vertices.a = arange(B)
177
        self.B = B
178

179
180
        if clabel is not None:
            if isinstance(clabel, PropertyMap):
181
                self.clabel = self.g.own_property(clabel.copy("int"))
182
183
184
185
            else:
                self.clabel = self.g.new_vertex_property("int")
                self.clabel.a = clabel
        else:
186
187
188
189
190
191
            self.clabel = self.g.new_vertex_property("int")

        if max_BE is None:
            max_BE = 1000
        self.max_BE = max_BE

192
        self.overlap = False
193
194
195
        self.ignore_degrees = kwargs.get("ignore_degrees", None)
        if self.ignore_degrees is None:
            self.ignore_degrees = g.new_vertex_property("bool", False)
196

197
198
199
        self.clear_cache()

    def clear_cache(self):
200
201
202
203
        # used by mcmc_sweep()
        self.egroups = None
        self.nsampler = None
        self.sweep_vertices = None
204
205
        self.overlap_stats = libcommunity.overlap_stats()
        self.partition_stats = libcommunity.partition_stats()
206
        self.edges_dl = False
207
        self.emat = None
208

209
210
211
212
213
214
    def __repr__(self):
        return "<BlockState object with %d blocks,%s for graph %s, at 0x%x>" % \
            (self.B, " degree corrected," if self.deg_corr else "", str(self.g),
             id(self))


215
216
    def __init_partition_stats(self, empty=True, edges_dl=False):
        self.edges_dl = edges_dl
217
218
219
220
        if not empty:
            self.partition_stats = libcommunity.init_partition_stats(self.g._Graph__graph,
                                                                     _prop("v", self.g, self.b),
                                                                     _prop("e", self.g, self.eweight),
221
                                                                     self.N, self.B,
222
223
                                                                     edges_dl,
                                                                     _prop("v", self.g, self.ignore_degrees))
224
225
226
227
        else:
            self.partition_stats = libcommunity.partition_stats()


228
229
230
231
232
233
234
235
236
237
238
    def __copy__(self):
        return self.copy()

    def __deepcopy__(self, memo):
        g = self.g.copy()
        eweight = g.own_property(self.eweight.copy())
        vweight = g.own_property(self.vweight.copy())
        clabel = g.own_property(self.clabel.copy())
        b = g.own_property(self.b.copy())
        return self.copy(g=g, eweight=eweight, vweight=vweight, b=b,
                         clabel=clabel)
239

240
    def copy(self, g=None, eweight=None, vweight=None, b=None, B=None,
241
             deg_corr=None, clabel=None, overlap=False, **kwargs):
242
243
244
        r"""Copies the block state. The parameters override the state properties, and
         have the same meaning as in the constructor. If ``overlap=True`` an
         instance of :class:`~graph_tool.community.OverlapBlockState` is
245
         returned. This is by default a shallow copy."""
246
247

        if not overlap:
248
            state = BlockState(self.g if g is None else g,
249
250
                               eweight=self.eweight if eweight is None else eweight,
                               vweight=self.vweight if vweight is None else vweight,
251
252
253
254
                               b=self.b.copy() if b is None else b,
                               B=(self.B if b is None else None) if B is None else B,
                               clabel=self.clabel if clabel is None else clabel,
                               deg_corr=self.deg_corr if deg_corr is None else deg_corr,
255
                               max_BE=self.max_BE,
256
257
                               ignore_degrees=kwargs.pop("ignore_degrees", self.ignore_degrees),
                               **kwargs)
258
        else:
259
            state = OverlapBlockState(self.g if g is None else g,
260
261
262
263
                                      b=b if b is not None else self.b,
                                      B=(self.B if b is None else None) if B is None else B,
                                      clabel=self.clabel if clabel is None else clabel,
                                      deg_corr=self.deg_corr if deg_corr is None else deg_corr,
264
                                      max_BE=self.max_BE, **kwargs)
265
266

        if not state.__check_clabel():
267
268
            if _bm_test() or not kwargs.get("fix_clabel", True) :
                raise RuntimeError("Inconsistent clabel after copy!")
269
270
            b = state.b.a + state.clabel.a * state.B
            continuous_map(b)
271
            state = state.copy(b=b, fix_clabel=False)
272
273
274
275
276
277
278
279
280
281
282
283

        return state


    def __getstate__(self):
        state = dict(g=self.g,
                     eweight=self.eweight,
                     vweight=self.vweight,
                     b=self.b,
                     B=self.B,
                     clabel=self.clabel,
                     deg_corr=self.deg_corr,
284
285
                     max_BE=self.max_BE,
                     ignore_degrees=self.ignore_degrees)
286
287
288
289
290
291
        return state

    def __setstate__(self, state):
        self.__init__(**state)
        return state

292
293
    def get_block_state(self, b=None, vweight=False, deg_corr=False,
                        overlap=False, **kwargs):
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
        r"""Returns a :class:`~graph_tool.community.BlockState`` corresponding to the
        block graph. The parameters have the same meaning as the in the constructor."""


        state = BlockState(self.bg, eweight=self.mrs,
                           vweight=self.wr if vweight else None,
                           b=self.bg.vertex_index.copy("int") if b is None else b,
                           clabel=self.get_bclabel(),
                           deg_corr=deg_corr,
                           max_BE=self.max_BE)
        if overlap:
            state = state.copy(overlap=True)
        n_map = self.b.copy()
        return state, n_map

    def get_bclabel(self):
        r"""Returns a :class:`~graph_tool.PropertyMap`` corresponding to constraint
        labels for the block graph."""

        bclabel = self.bg.new_vertex_property("int")
        reverse_map(self.b, bclabel)
        pmap(bclabel, self.clabel)
        return bclabel

    def __check_clabel(self):
319
320
        b = self.b.fa + self.clabel.fa * self.B
        b2 = self.b.fa.copy()
321
        continuous_map(b)
322
323
        continuous_map(b2)
        return (b == b2).all()
324

325
326
327
328
    def __get_emat(self):
        if self.emat is None:
            self.__regen_emat()
        return self.emat
329
330

    def __regen_emat(self):
331
        if self.B <= self.max_BE:
332
333
334
            self.emat = libcommunity.create_emat(self.g._Graph__graph,
                                                 _prop("v", self.g, self.b),
                                                 self.bg._Graph__graph)
335
        else:
336
337
338
339
            self.emat = libcommunity.create_ehash(self.g._Graph__graph,
                                                  _prop("v", self.g, self.b),
                                                  self.bg._Graph__graph,
                                                  _get_rng())
340

341
    def __build_egroups(self, empty=False):
342
343
        self.esrcpos = self.g.new_edge_property("int")
        self.etgtpos = self.g.new_edge_property("int")
344

345
        self.egroups = libcommunity.build_egroups(self.g._Graph__graph,
346
347
348
349
350
                                                  self.bg._Graph__graph,
                                                  _prop("v", self.g, self.b),
                                                  _prop("e", self.g, self.eweight),
                                                  _prop("e", self.g, self.esrcpos),
                                                  _prop("e", self.g, self.etgtpos),
351
                                                  self.is_weighted, empty)
352

353
    def __build_nsampler(self, empty=False):
354
        self.nsampler = libcommunity.init_neighbour_sampler(self.g._Graph__graph,
355
                                                            _prop("e", self.g, self.eweight),
356
                                                            True, empty)
357

358
359
360
361
362
363
364
365
366
    def get_blocks(self):
        r"""Returns the property map which contains the block labels for each vertex."""
        return self.b

    def get_bg(self):
        r"""Returns the block graph."""
        return self.bg

    def get_ers(self):
367
368
        r"""Returns the edge property map of the block graph which contains the :math:`e_{rs}` matrix entries.
        For undirected graphs, the diagonal values (self-loops) contain :math:`e_{rr}/2`."""
369
370
371
372
373
374
375
376
        return self.mrs

    def get_er(self):
        r"""Returns the vertex property map of the block graph which contains the number
        :math:`e_r` of half-edges incident on block :math:`r`. If the graph is
        directed, a pair of property maps is returned, with the number of
        out-edges :math:`e^+_r` and in-edges :math:`e^-_r`, respectively."""
        if self.bg.is_directed():
377
            return self.mrp, self.mrm
378
379
380
381
382
383
384
        else:
            return self.mrp

    def get_nr(self):
        r"""Returns the vertex property map of the block graph which contains the block sizes :math:`n_r`."""
        return self.wr

385
386
387
    def entropy(self, complete=True, dl=False, partition_dl=True,
                degree_dl=True, edges_dl=True, dense=False, multigraph=True,
                norm=False, dl_ent=False, **kwargs):
388
        r"""Calculate the entropy associated with the current block partition.
389
390
391
392
393
394
395
396

        Parameters
        ----------
        complete : ``bool`` (optional, default: ``False``)
            If ``True``, the complete entropy will be returned, including constant
            terms not relevant to the block partition.
        dl : ``bool`` (optional, default: ``False``)
            If ``True``, the full description length will be returned.
397
398
399
400
401
402
403
404
        partition_dl : ``bool`` (optional, default: ``True``)
            If ``True``, and ``dl == True`` the partition description length
            will be considered.
        edges_dl : ``bool`` (optional, default: ``True``)
            If ``True``, and ``dl == True`` the edge matrix description length
            will be considered.
        degree_dl : ``bool`` (optional, default: ``True``)
            If ``True``, and ``dl == True`` the degree sequence description
405
            length will be considered.
406
407
408
        dense : ``bool`` (optional, default: ``False``)
            If ``True``, the "dense" variant of the entropy will be computed.
        multigraph : ``bool`` (optional, default: ``False``)
409
410
411
412
413
414
415
            If ``True``, the multigraph entropy will be used.
        norm : ``bool`` (optional, default: ``True``)
            If ``True``, the entropy will be "normalized" by dividing by the
            number of edges.
        dl_ent : ``bool`` (optional, default: ``False``)
            If ``True``, the description length of the degree sequence will be
            approximated by its entropy.
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

        Notes
        -----
        For the traditional blockmodel (``deg_corr == False``), the entropy is
        given by

        .. math::

          \mathcal{S}_t &\cong E - \frac{1}{2} \sum_{rs}e_{rs}\ln\left(\frac{e_{rs}}{n_rn_s}\right), \\
          \mathcal{S}^d_t &\cong E - \sum_{rs}e_{rs}\ln\left(\frac{e_{rs}}{n_rn_s}\right),

        for undirected and directed graphs, respectively, where :math:`e_{rs}`
        is the number of edges from block :math:`r` to :math:`s` (or the number
        of half-edges for the undirected case when :math:`r=s`), and :math:`n_r`
        is the number of vertices in block :math:`r` .

        For the degree-corrected variant with "hard" degree constraints the
        equivalent expressions are

        .. math::

            \mathcal{S}_c &\cong -E -\sum_kN_k\ln k! - \frac{1}{2} \sum_{rs}e_{rs}\ln\left(\frac{e_{rs}}{e_re_s}\right), \\
            \mathcal{S}^d_c &\cong -E -\sum_{k^+}N_{k^+}\ln k^+!  -\sum_{k^-}N_{k^-}\ln k^-! - \sum_{rs}e_{rs}\ln\left(\frac{e_{rs}}{e^+_re^-_s}\right),

        where :math:`e_r = \sum_se_{rs}` is the number of half-edges incident on
        block :math:`r`, and :math:`e^+_r = \sum_se_{rs}` and :math:`e^-_r =
442
        \sum_se_{sr}` are the numbers of out- and in-edges adjacent to block
443
444
        :math:`r`, respectively.

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
        If ``dense == False`` and ``multigraph == True``, the entropy used will
        be of the "Poisson" model, with the additional term:

        .. math::

            {\mathcal{S}_{cm}^{(d)}} = \mathcal{S}_c^{(d)} + \sum_{i>j} \ln A_{ij}! + \sum_i \ln A_{ii}!!


        If ``dl == True``, the description length :math:`\mathcal{L}_t` of the
        model will be returned as well, as described in
        :func:`model_entropy`. Note that for the degree-corrected version the
        description length is

        .. math::

            \mathcal{L}_c = \mathcal{L}_t + \sum_r\min\left(\mathcal{L}^{(1)}_r, \mathcal{L}^{(2)}_r\right),

        with

        .. math::

              \mathcal{L}^{(1)}_r &= \ln{\left(\!\!{n_r \choose e_r}\!\!\right)}, \\
              \mathcal{L}^{(2)}_r &= \ln\Xi_r + \ln n_r! - \sum_k \ln n^r_k!,

        and :math:`\ln\Xi_r \simeq 2\sqrt{\zeta(2)e_r}`, where :math:`\zeta(x)`
        is the `Riemann zeta function
        <https://en.wikipedia.org/wiki/Riemann_zeta_function>`_, and
        :math:`n^r_k` is the number of nodes in block :math:`r` with degree
        :math:`k`. For directed graphs we have instead :math:`k \to (k^-, k^+)`,
        and :math:`\ln\Xi_r \to \ln\Xi^+_r + \ln\Xi^-_r` with :math:`\ln\Xi_r^+
        \simeq 2\sqrt{\zeta(2)e^+_r}` and :math:`\ln\Xi_r^- \simeq
        2\sqrt{\zeta(2)e^-_r}`.

        If ``dl_ent=True`` is passed, this will be approximated instead by
479
480
481

        .. math::

482
            \mathcal{L}_c \simeq \mathcal{L}_t - \sum_rn_r\sum_kp^r_k\ln p^r_k,
483

484
        where :math:`p^r_k = n^r_k / n_r`.
485

486
487
        If the "dense" entropies are requested (``dense=True``), they will be
        computed as
488
489
490
491
492
493
494
495
496
497
498
499
500

        .. math::

            \mathcal{S}_t  &= \sum_{r>s} \ln{\textstyle {n_rn_s \choose e_{rs}}} + \sum_r \ln{\textstyle {{n_r\choose 2}\choose e_{rr}/2}}\\
            \mathcal{S}^d_t  &= \sum_{rs} \ln{\textstyle {n_rn_s \choose e_{rs}}},

        for simple graphs, and

        .. math::

            \mathcal{S}_m  &= \sum_{r>s} \ln{\textstyle \left(\!\!{n_rn_s \choose e_{rs}}\!\!\right)} + \sum_r \ln{\textstyle \left(\!\!{\left(\!{n_r\choose 2}\!\right)\choose e_{rr}/2}\!\!\right)}\\
            \mathcal{S}^d_m  &= \sum_{rs} \ln{\textstyle \left(\!\!{n_rn_s \choose e_{rs}}\!\!\right)},

501
502
503
        for multigraphs (i.e. ``multigraph == True``). A dense entropy for the
        degree-corrected model is not available, and if requested will return a
        :exc:`NotImplementedError`.
504

505
506
        If ``complete == False`` constants in the above equations which do not
        depend on the partition of the nodes will be omitted.
507

508
509
        Note that in all cases if ``norm==True`` the value returned corresponds
        to the entropy `per edge`, i.e. :math:`(\mathcal{S}_{t/c}\; [\,+\,\mathcal{L}_{t/c}])/ E`.
510
511
        """

512
513
514
        xi_fast = kwargs.get("xi_fast", False)
        dl_deg_alt = kwargs.get("dl_deg_alt", True)

515
516
517
        E = self.E
        N = self.N

518
519
        if dense:
            if self.deg_corr:
520
                raise NotImplementedError('A degree-corrected "dense" entropy is not yet implemented')
521

522
            S = libcommunity.entropy_dense(self.bg._Graph__graph,
523
524
525
                                            _prop("e", self.bg, self.mrs),
                                            _prop("v", self.bg, self.wr),
                                            multigraph)
526
527
        else:
            S = libcommunity.entropy(self.bg._Graph__graph,
528
529
530
531
532
                                      _prop("e", self.bg, self.mrs),
                                      _prop("v", self.bg, self.mrp),
                                      _prop("v", self.bg, self.mrm),
                                      _prop("v", self.bg, self.wr),
                                      self.deg_corr)
533

534
            if _bm_test():
535
536
537
                assert not isnan(S) and not isinf(S), "invalid entropy %g (%s) " % (S, str(dict(complete=complete,
                                                                                                random=random, dl=dl,
                                                                                                partition_dl=partition_dl,
538
                                                                                                edges_dl=edges_dl,
539
540
                                                                                                dense=dense, multigraph=multigraph,
                                                                                                norm=norm)))
541
542
543
544
545
            if self.deg_corr:
                S -= E
            else:
                S += E

546
547
            if complete:
                if self.deg_corr:
548
549
550
                    S += libcommunity.deg_entropy_term(self.g._Graph__graph,
                                                       libcore.any(),
                                                       self.overlap_stats,
551
552
553
                                                       self.N,
                                                       _prop("e", self.g, self.eweight),
                                                       _prop("v", self.g, self.ignore_degrees))
554

555
556
557
558
                if multigraph:
                    S += libcommunity.entropy_parallel(self.g._Graph__graph,
                                                       _prop("e", self.g, self.eweight))

559
                if _bm_test():
560
561
562
                    assert not isnan(S) and not isinf(S), "invalid entropy %g (%s) " % (S, str(dict(complete=complete,
                                                                                                    random=random, dl=dl,
                                                                                                    partition_dl=partition_dl,
563
                                                                                                    edges_dl=edges_dl,
564
565
                                                                                                    dense=dense, multigraph=multigraph,
                                                                                                    norm=norm)))
566
        if dl:
567
568
569
570
571
572
573
574
            if partition_dl:
                if self.partition_stats.is_enabled():
                    S += self.partition_stats.get_partition_dl()
                else:
                    self.__init_partition_stats(empty=False)
                    S += self.partition_stats.get_partition_dl()
                    self.__init_partition_stats(empty=True)

575
                if _bm_test():
576
577
578
                    assert not isnan(S) and not isinf(S), "invalid entropy %g (%s) " % (S, str(dict(complete=complete,
                                                                                                    random=random, dl=dl,
                                                                                                    partition_dl=partition_dl,
579
                                                                                                    edges_dl=edges_dl,
580
581
                                                                                                    dense=dense, multigraph=multigraph,
                                                                                                    norm=norm)))
582
583
584
            if edges_dl:
                actual_B = (self.wr.a > 0).sum()
                S += model_entropy(actual_B, N, E, directed=self.g.is_directed(), nr=False)
585

586
            if self.deg_corr and degree_dl:
587
588
589
590
591
592
                if self.partition_stats.is_enabled():
                    S_seq = self.partition_stats.get_deg_dl(dl_ent, dl_deg_alt, xi_fast)
                else:
                    self.__init_partition_stats(empty=False)
                    S_seq = self.partition_stats.get_deg_dl(dl_ent, dl_deg_alt, xi_fast)
                    self.__init_partition_stats(empty=True)
593

594
                S += S_seq
595

596
                if _bm_test():
597
598
599
                    assert not isnan(S_seq) and not isinf(S_seq), "invalid entropy %g (%s) " % (S_seq, str(dict(complete=complete,
                                                                                                                random=random, dl=dl,
                                                                                                                partition_dl=partition_dl,
600
                                                                                                                edges_dl=edges_dl,
601
602
603
                                                                                                                dense=dense, multigraph=multigraph,
                                                                                                                norm=norm)))

604
        if _bm_test():
605
606
607
            assert not isnan(S) and not isinf(S), "invalid entropy %g (%s) " % (S, str(dict(complete=complete,
                                                                                            random=random, dl=dl,
                                                                                            partition_dl=partition_dl,
608
                                                                                            edges_dl=edges_dl,
609
610
611
612
613
614
615
                                                                                            dense=dense, multigraph=multigraph,
                                                                                            norm=norm)))

        if norm:
            return S / E
        else:
            return S
616

617
618
619
    def get_matrix(self):
        r"""Returns the block matrix (as a sparse :class:`~scipy.sparse.csr_matrix`),
        which contains the number of edges between each block pair.
620

621
622
623
624
625
626
        .. warning::

           This corresponds to the adjacency matrix of the block graph, which by
           convention includes twice the amount of edges in the diagonal entries
           if the graph is undirected.

627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
        Examples
        --------

        .. testsetup:: get_matrix

           gt.seed_rng(42)
           np.random.seed(42)
           from pylab import *

        .. doctest:: get_matrix

           >>> g = gt.collection.data["polbooks"]
           >>> state = gt.BlockState(g, B=5, deg_corr=True)
           >>> for i in range(1000):
           ...     ds, nmoves = gt.mcmc_sweep(state)
642
           >>> m = state.get_matrix()
643
644
           >>> figure()
           <...>
645
           >>> matshow(m.todense())
646
647
648
649
650
651
652
653
654
655
656
657
658
           <...>
           >>> savefig("bloc_mat.pdf")

        .. testcleanup:: get_matrix

           savefig("bloc_mat.png")

        .. figure:: bloc_mat.*
           :align: center

           A  5x5 block matrix.

       """
659

660
        return adjacency(self.bg, weight=self.mrs)
661
662


663
def model_entropy(B, N, E, directed=False, nr=None):
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
    r"""Computes the amount of information necessary for the parameters of the traditional blockmodel ensemble, for ``B`` blocks, ``N`` vertices, ``E`` edges, and either a directed or undirected graph.

    A traditional blockmodel is defined as a set of :math:`N` vertices which can
    belong to one of :math:`B` blocks, and the matrix :math:`e_{rs}` describes
    the number of edges from block :math:`r` to :math:`s` (or twice that number
    if :math:`r=s` and the graph is undirected).

    For an undirected graph, the number of distinct :math:`e_{rs}` matrices is given by,

    .. math::

       \Omega_m = \left(\!\!{\left(\!{B \choose 2}\!\right) \choose E}\!\!\right)

    and for a directed graph,

    .. math::
       \Omega_m = \left(\!\!{B^2 \choose E}\!\!\right)


    where :math:`\left(\!{n \choose k}\!\right) = {n+k-1\choose k}` is the
    number of :math:`k` combinations with repetitions from a set of size :math:`n`.

    The total information necessary to describe the model is then,

    .. math::

690
691
       \mathcal{L}_t = \ln\Omega_m + \ln\left(\!\!{B \choose N}\!\!\right) + \ln N! - \sum_r \ln n_r!,

692

693
694
    where the remaining term is the information necessary to describe the
    block partition, where :math:`n_r` is the number of nodes in block :math:`r`.
695

696
697
    If ``nr`` is ``None``, it is assumed :math:`n_r=N/B`.

698
699
700
    References
    ----------

Tiago Peixoto's avatar
Tiago Peixoto committed
701
702
    .. [peixoto-parsimonious-2013] Tiago P. Peixoto, "Parsimonious module inference in large networks",
       Phys. Rev. Lett. 110, 148701 (2013), :doi:`10.1103/PhysRevLett.110.148701`, :arxiv:`1212.4794`.
Tiago Peixoto's avatar
Tiago Peixoto committed
703
704
705
    .. [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`.
706
707
708

    """

709
710
711
712
    if directed:
        x = (B * B);
    else:
        x = (B * (B + 1)) / 2;
713
714
715
716
717
    if nr is False:
        L = lbinom(x + E - 1, E)
    else:
        L = lbinom(x + E - 1, E) + partition_entropy(B, N, nr)
    return L
718

719
def lbinom(n, k):
720
    return scipy.special.gammaln(float(n + 1)) - scipy.special.gammaln(float(n - k + 1)) - scipy.special.gammaln(float(k + 1))
721

722
723
724
725
726
727
def lbinom_careful(n, k):
    return libcommunity.lbinom_careful(n, k)

def lbinom_fast(n, k):
    return libcommunity.lbinom_fast(n, k)

728
729
730
731
def partition_entropy(B, N, nr=None):
    if nr is None:
        S = N * log(B) + log1p(-(1 - 1./B) ** N)
    else:
732
        S = lbinom(B + N - 1, N) + scipy.special.gammaln(N + 1) - scipy.special.gammaln(nr + 1).sum()
733
    return S
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753

def get_max_B(N, E, directed=False):
    r"""Return the maximum detectable number of blocks, obtained by minimizing:

    .. math::

        \mathcal{L}_t(B, N, E) - E\ln B

    where :math:`\mathcal{L}_t(B, N, E)` is the information necessary to
    describe a traditional blockmodel with `B` blocks, `N` nodes and `E`
    edges (see :func:`model_entropy`).

    Examples
    --------

    >>> gt.get_max_B(N=1e6, E=5e6)
    1572

    References
    ----------
Tiago Peixoto's avatar
Tiago Peixoto committed
754
755
    .. [peixoto-parsimonious-2013] Tiago P. Peixoto, "Parsimonious module inference in large networks",
       Phys. Rev. Lett. 110, 148701 (2013), :doi:`10.1103/PhysRevLett.110.148701`, :arxiv:`1212.4794`.
756
757
758
759


    """

760
761
762
    def Sdl(B, S, N, E, directed=False):
        return S + model_entropy(B, N, E, directed) / E

763
764
765
766
    B = fminbound(lambda B: Sdl(B, -log(B), N, E, directed), 1, E,
                  xtol=1e-6, maxfun=1500, disp=0)
    if isnan(B):
        B = 1
767
    return min(N, max(int(ceil(B)), 2))
768

769
def get_akc(B, I, N=numpy.inf, directed=False):
Tiago Peixoto's avatar
Tiago Peixoto committed
770
    r"""Return the minimum value of the average degree of the network, so that some block structure with :math:`B` blocks can be detected, according to the minimum description length criterion.
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

    This is obtained by solving

    .. math::

       \Sigma_b = \mathcal{L}_t(B, N, E) - E\mathcal{I}_{t/c} = 0,

    where :math:`\mathcal{L}_{t}` is the necessary information to describe the
    blockmodel parameters (see :func:`model_entropy`), and
    :math:`\mathcal{I}_{t/c}` characterizes the planted block structure, and is
    given by

    .. math::

        \mathcal{I}_t &= \sum_{rs}m_{rs}\ln\left(\frac{m_{rs}}{w_rw_s}\right),\\
        \mathcal{I}_c &= \sum_{rs}m_{rs}\ln\left(\frac{m_{rs}}{m_rm_s}\right),

    where :math:`m_{rs} = e_{rs}/2E` (or :math:`m_{rs} = e_{rs}/E` for directed
    graphs) and :math:`w_r=n_r/N`. We note that :math:`\mathcal{I}_{t/c}\in[0,
    \ln B]`. In the case where :math:`E \gg B^2`, this simplifies to

    .. math::

       \left<k\right>_c &= \frac{2\ln B}{\mathcal{I}_{t/c}},\\
       \left<k^{-/+}\right>_c &= \frac{\ln B}{\mathcal{I}_{t/c}},

    for undirected and directed graphs, respectively. This limit is assumed if
    ``N == inf``.

    Examples
    --------

    >>> gt.get_akc(10, log(10) / 100, N=100)
804
    2.414413200430159
805
806
807

    References
    ----------
Tiago Peixoto's avatar
Tiago Peixoto committed
808
809
    .. [peixoto-parsimonious-2013] Tiago P. Peixoto, "Parsimonious module inference in large networks",
       Phys. Rev. Lett. 110, 148701 (2013), :doi:`10.1103/PhysRevLett.110.148701`, :arxiv:`1212.4794`.
810
811

    """
812
    if N != numpy.inf:
813
        if directed:
814
            get_dl = lambda ak: model_entropy(B, N, N * ak, directed) / N * ak - N * ak * I
815
        else:
816
            get_dl = lambda ak: model_entropy(B, N, N * ak / 2., directed) * 2 / (N * ak)  - N * ak * I / 2.
817
818
819
820
821
822
823
824
        ak = fsolve(lambda ak: get_dl(ak), 10)
        ak = float(ak)
    else:
        ak = 2 * log(B) / S
        if directed:
            ak /= 2
    return ak

825
826
def mcmc_sweep(state, beta=1., c=1., niter=1, dl=False, dense=False,
               multigraph=False, node_coherent=False, confine_layers=False,
827
               sequential=True, parallel=False, vertices=None,
Tiago Peixoto's avatar
Tiago Peixoto committed
828
               target_blocks=None, verbose=False, **kwargs):
829
    r"""Performs a Markov chain Monte Carlo sweep on the network, to sample the block partition according to a probability :math:`\propto e^{-\beta \mathcal{S}_{t/c}}`, where :math:`\mathcal{S}_{t/c}` is the blockmodel entropy.
830
831
832

    Parameters
    ----------
833
    state : :class:`~graph_tool.community.BlockState`, :class:`~graph_tool.community.OverlapBlockState` or :class:`~graph_tool.community.CovariateBlockState`
834
        The block state.
835
    beta : ``float`` (optional, default: `1.0`)
836
        The inverse temperature parameter :math:`\beta`.
837
838
839
840
841
    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.
842
843
    niter : ``int`` (optional, default: ``1``)
        Number of sweeps to perform.
844
845
846
    dl : ``bool`` (optional, default: ``False``)
        If ``True``, the change in the whole description length will be
        considered after each vertex move, not only the entropy.
847
848
849
850
851
    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``.
852
853
854
855
    node_coherent : ``bool`` (optional, default: ``False``)
        If ``True``, and if the ``state`` is an instance of
        :class:`~graph_tool.community.OverlapBlockState`, then all half-edges
        incident on the same node are moved simultaneously.
856
857
858
859
860
    confine_layers : ``bool`` (optional, default: ``False``)
        If ``True``, and if the ``state`` is an instance of
        :class:`~graph_tool.community.CovariateBlockState`, with an
        *overlapping* partition, the half edges will only be moved in such a way
         that inside each layer the group membership remains non-overlapping.
861
862
863
864
865
    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.
866
867
868
869
870
871
872
873
874
875
    parallel : ``bool`` (optional, default: ``False``)
        If ``True``, the updates are performed in parallel (multiple
        threads).

        .. warning::

            If this is used, the Markov Chain is not guaranteed to be sampled with
            the correct probabilities. This is better used in conjunction with
            ``beta=float('inf')``, where this is not an issue.

Tiago Peixoto's avatar
Tiago Peixoto committed
876
    vertices : ``list of ints`` (optional, default: ``None``)
877
878
        A list of vertices which will be attempted to be moved. If ``None``, all
        vertices will be attempted.
879
880
881
    target_blocks : ``list of ints`` (optional, default: ``None``)
        A list of groups to which the corresponding vertices will to be forcibly
        moved. If ``None``, the standard MCMC rules will be applied.
882
883
884
885
886
887
    verbose : ``bool`` (optional, default: ``False``)
        If ``True``, verbose information is displayed.

    Returns
    -------

888
    dS : ``float``
889
       The entropy difference (in nats) after the sweeps.
890
891
892
893
894
895
896
    nmoves : ``int``
       The number of accepted block membership moves.


    Notes
    -----

897
    This algorithm performs a Markov chain Monte Carlo sweep on the network,
898
899
    where the block memberships are randomly moved, and either accepted or
    rejected, so that after sufficiently many sweeps the partitions are sampled
900
    with probability proportional to :math:`e^{-\beta\mathcal{S}_{t/c}}`, where
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
    :math:`\mathcal{S}_{t/c}` is the blockmodel entropy, given by

    .. math::

      \mathcal{S}_t &\cong - \frac{1}{2} \sum_{rs}e_{rs}\ln\left(\frac{e_{rs}}{n_rn_s}\right), \\
      \mathcal{S}^d_t &\cong - \sum_{rs}e_{rs}\ln\left(\frac{e_{rs}}{n_rn_s}\right),

    for undirected and directed traditional blockmodels (``deg_corr == False``),
    respectively, where :math:`e_{rs}` is the number of edges from block
    :math:`r` to :math:`s` (or the number of half-edges for the undirected case
    when :math:`r=s`), and :math:`n_r` is the number of vertices in block
    :math:`r`, and constant terms which are independent of the block partition
    were dropped (see :meth:`BlockState.entropy` for the complete entropy). For
    the degree-corrected variant with "hard" degree constraints the equivalent
    expressions are

    .. math::

       \mathcal{S}_c &\cong  - \frac{1}{2} \sum_{rs}e_{rs}\ln\left(\frac{e_{rs}}{e_re_s}\right), \\
       \mathcal{S}^d_c &\cong - \sum_{rs}e_{rs}\ln\left(\frac{e_{rs}}{e^+_re^-_s}\right),

    where :math:`e_r = \sum_se_{rs}` is the number of half-edges incident on
    block :math:`r`, and :math:`e^+_r = \sum_se_{rs}` and :math:`e^-_r =
    \sum_se_{sr}` are the number of out- and in-edges adjacent to block
    :math:`r`, respectively.

    The Monte Carlo algorithm employed attempts to improve the mixing time of
928
929
    the Markov chain by proposing membership moves :math:`r\to s` with
    probability :math:`p(r\to s|t) \propto e_{ts} + c`, where :math:`t` is the
930
    block label of a random neighbour of the vertex being moved. See
931
    [peixoto-efficient-2014]_ for more details.
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

    This algorithm has a complexity of :math:`O(E)`, where :math:`E` is the
    number of edges in the network.

    Examples
    --------
    .. testsetup:: mcmc

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

    .. doctest:: mcmc

       >>> g = gt.collection.data["polbooks"]
       >>> state = gt.BlockState(g, B=3, deg_corr=True)
       >>> pv = None
       >>> for i in range(1000):        # remove part of the transient
       ...     ds, nmoves = gt.mcmc_sweep(state)
       >>> for i in range(1000):
       ...     ds, nmoves = gt.mcmc_sweep(state)
       ...     pv = gt.collect_vertex_marginals(state, pv)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_shape="pie", vertex_pie_fractions=pv, output="polbooks_blocks_soft.pdf")
       <...>

    .. testcleanup:: mcmc

       gt.graph_draw(g, pos=g.vp["pos"], vertex_shape="pie", vertex_pie_fractions=pv, output="polbooks_blocks_soft.png")

    .. figure:: polbooks_blocks_soft.*
       :align: center

       "Soft" block partition of a political books network with :math:`B=3`.

     References
    ----------

    .. [holland-stochastic-1983] Paul W. Holland, Kathryn Blackmond Laskey,
       Samuel Leinhardt, "Stochastic blockmodels: First steps",
970
971
       Carnegie-Mellon University, Pittsburgh, PA 15213, U.S.A.,
       :doi:`10.1016/0378-8733(83)90021-7`
972
973
    .. [faust-blockmodels-1992] Katherine Faust, and Stanley
       Wasserman. "Blockmodels: Interpretation and Evaluation." Social Networks
974
       14, no. 1-2 (1992): 5-61. :doi:`10.1016/0378-8733(92)90013-W`
975
976
977
978
    .. [karrer-stochastic-2011] Brian Karrer, and M. E. J. Newman. "Stochastic
       Blockmodels and Community Structure in Networks." Physical Review E 83,
       no. 1 (2011): 016107. :doi:`10.1103/PhysRevE.83.016107`.
    .. [peixoto-entropy-2012] Tiago P. Peixoto "Entropy of Stochastic Blockmodel
979
980
981
982
983
       Ensembles." Physical Review E 85, no. 5 (2012): 056122.
       :doi:`10.1103/PhysRevE.85.056122`, :arxiv:`1112.6028`.
    .. [peixoto-parsimonious-2013] Tiago P. Peixoto, "Parsimonious module
       inference in large networks", Phys. Rev. Lett. 110, 148701 (2013),
       :doi:`10.1103/PhysRevLett.110.148701`, :arxiv:`1212.4794`.
984
    .. [peixoto-efficient-2014] Tiago P. Peixoto, "Efficient Monte Carlo and greedy
985
986
987
       heuristic for the inference of stochastic block models", Phys. Rev. E 89,
       012804 (2014), :doi:`10.1103/PhysRevE.89.012804`, :arxiv:`1310.4378`.
    .. [peixoto-model-2015] Tiago P. Peixoto, "Model selection and hypothesis
988
       testing for large-scale network models with overlapping groups",
989
       Phys. Rev. X 5, 011033 (2015), :doi:`10.1103/PhysRevX.5.011033`,
990
       :arxiv:`1409.3059`.
991
992
    """

993
994
995
996
997
    nmerges = kwargs.get("nmerges", 0)
    merge_map = kwargs.get("merge_map", None)
    coherent_merge = kwargs.get("coherent_merge", False)
    edges_dl = kwargs.get("edges_dl", False)

998
    if state.B == 1:
999
1000
        return 0., 0

1001
    if vertices is not None:
1002
1003
1004
        temp = libcommunity.get_vector(len(vertices))
        temp.a = vertices
        vertices = temp
1005
        state.sweep_vertices = vertices
1006
1007
    elif (state.sweep_vertices is None or
          len(state.sweep_vertices.a) < state.g.num_vertices()):
1008
1009
1010
1011
        vertices = libcommunity.get_vector(state.g.num_vertices())
        vertices.a = state.g.vertex_index.copy("int").fa
        state.sweep_vertices = vertices

1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
    if target_blocks is not None:
        temp = libcommunity.get_vector(len(target_blocks))
        temp.a = target_blocks
        target_blocks = temp
        if len(target_blocks) != len(state.sweep_vertices):
            raise ValueError("'target_blocks' must have the same length as 'vertices'")
    else:
        target_blocks = libcommunity.get_vector(0)


1022
    random_move = c == numpy.inf
1023

1024
    bclabel = state.get_bclabel()
1025

1026
1027
1028
1029
    if nmerges == 0 or merge_map is None:
        merge_map = state.g.vertex_index.copy("int")

    if nmerges > 0:
1030
        beta = numpy.inf
1031

1032
1033
    nsampler = []
    ncavity_sampler = []
1034

1035
1036
1037
1038
1039
1040
1041
    main_state = state
    if isinstance(state, CovariateBlockState):
        states = state.states
        covariate = True
    else:
        states = [state]
        covariate = False
1042

1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
    for l, state in enumerate(states):

        if l == 0 and (random_move or nmerges > 0):
            state._BlockState__build_egroups(empty=True)
        elif state.egroups is None:
            state._BlockState__build_egroups(empty=False)

        if nmerges == 0:
            if state.nsampler is None:
                state._BlockState__build_nsampler(empty=state.overlap)
            nsampler.append(state.nsampler)
            ncavity_sampler.append(state.nsampler)
1055
        else:
1056
            if not kwargs.get("unweighted_merge", False):
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
                emask = state.mrs
            else:
                emask = state.mrs.copy()
                emask.a = emask.a > 0

            nsampler.append(libcommunity.init_neighbour_sampler(state.bg._Graph__graph,
                                                                _prop("e", state.bg, emask),
                                                                True, False))
            ncavity_sampler.append(libcommunity.init_neighbour_sampler(state.bg._Graph__graph,
                                                                       _prop("e", state.bg, emask),
                                                                       False, False))

        dl_enable = dl
        if dl and covariate and (state.slave or state.master):
            dl_enable = state.master
        if state.partition_stats.is_enabled() != dl_enable or edges_dl != state.edges_dl:
            if state.overlap:
                state._OverlapBlockState__init_partition_stats(empty=not dl_enable, edges_dl=edges_dl)
            else:
                state._BlockState__init_partition_stats(empty=not dl_enable, edges_dl=edges_dl)
1077

1078
1079
1080
1081
1082
    if _bm_test():
        assert main_state._BlockState__check_clabel(), "clabel already invalid!"
        S = main_state.entropy(dense=dense, multigraph=multigraph,
                               complete=False, dl=dl, edges_dl=edges_dl,
                               dl_deg_alt=False, xi_fast=True)
1083
        assert not (isinf(S) or isnan(S)), "invalid entropy before sweep: %g" % S
1084

1085
    nmoves = 1
1086
    try:
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
        if not covariate:
            state = states[0]
            if not state.overlap:
                dS, nmoves = libcommunity.move_sweep(state.g._Graph__graph,
                                                     state.bg._Graph__graph,
                                                     state._BlockState__get_emat(),
                                                     nsampler[0], ncavity_sampler[0],
                                                     _prop("e", state.bg, state.mrs),
                                                     _prop("v", state.bg, state.mrp),
                                                     _prop("v", state.bg, state.mrm),
                                                     _prop("v", state.bg, state.wr),
                                                     _prop("v", state.g, state.b),
                                                     _prop("v", state.bg, bclabel),
                                                     state.sweep_vertices,
1101
                                                     target_blocks,
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
                                                     state.deg_corr, dense, multigraph,
                                                     _prop("e", state.g, state.eweight),
                                                     _prop("v", state.g, state.vweight),
                                                     state.egroups,
                                                     _prop("e", state.g, state.esrcpos),
                                                     _prop("e", state.g, state.etgtpos),
                                                     float(beta), sequential,
                                                     parallel, random_move,
                                                     c, state.is_weighted,
                                                     nmerges,
                                                     _prop("v", state.g, merge_map),
                                                     niter,
                                                     state.partition_stats,
                                                     verbose, _get_rng())
            else:
                dS, nmoves = libcommunity.move_sweep_overlap(state.g._Graph__graph,
                                                             state.bg._Graph__graph,
                                                             state._BlockState__get_emat(),
                                                             nsampler[0],
                                                             ncavity_sampler[0],
                                                             _prop("e", state.bg, state.mrs),
                                                             _prop("v", state.bg, state.mrp),
                                                             _prop("v", state.bg, state.mrm),
                                                             _prop("v", state.bg, state.wr),
                                                             _prop("v", state.g, state.b),
                                                             _prop("v", state.bg, bclabel),
                                                             state.sweep_vertices,
1129
                                                             target_blocks,
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
                                                             state.deg_corr, dense, multigraph,
                                                             multigraph,
                                                             _prop("e", state.g, state.eweight),
                                                             _prop("v", state.g, state.vweight),
                                                             state.egroups,
                                                             _prop("e", state.g, state.esrcpos),
                                                             _prop("e", state.g, state.etgtpos),
                                                             float(beta),
                                                             sequential, parallel,
                                                             random_move, float(c),
                                                             ((nmerges == 0 and node_coherent) or
                                                              (nmerges > 0 and coherent_merge)),
                                                             state.is_weighted,
                                                             nmerges,
                                                             _prop("v", state.g, merge_map),
                                                             niter,
                                                             state.overlap_stats,
                                                             state.partition_stats,
                                                             verbose, _get_rng())
1149
        else:
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
            if _bm_test():
                for l, state in enumerate(states):
                    assert state.mrs.fa.sum() == state.eweight.fa.sum(), (l, state.mrs.fa.sum(), state.eweight.fa.sum())
                    #assert state.mrs.a.sum() == state.eweight.a.sum(), (l, state.mrs.a.sum(), state.eweight.a.sum())

            if confine_layers:
                node_coherent = True

            dS, nmoves = libcommunity.cov_move_sweep(main_state.g._Graph__graph,
                                                     _prop("e", main_state.g, main_state.ec),
                                                     _prop("v", main_state.g, main_state.vc),
                                                     _prop("v", main_state.g, main_state.vmap),
                                                     [state.g._Graph__graph for state in states],
                                                     [state.bg._Graph__graph for state in states],
                                                     [state._BlockState__get_emat() for state in states],
                                                     nsampler, ncavity_sampler,
                                                     [_prop("e", state.bg, state.mrs) for state in states],
                                                     [_prop("v", state.bg, state.mrp) for state in states],
                                                     [_prop("v", state.bg, state.mrm) for state in states],
                                                     [_prop("v", state.bg, state.wr) for state in states],
                                                     _prop("v", main_state.g, main_state.b),
                                                     [_prop("v", state.g, state.b) for state in states],
                                                     main_state.bmap,
                                                     [_prop("v", state.g, state.g.vp["brmap"]) for state in states],
                                                     [state.free_blocks for state in states],
                                                     [state.master for state in states],
                                                     [state.slave for state in states],
                                                     _prop("v", None, bclabel),
1178
                                                     [main_state.sweep_vertices, target_blocks],
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
                                                     main_state.deg_corr, dense, multigraph,
                                                     [_prop("e", state.g, state.eweight) for state in states],
                                                     [_prop("v", state.g, state.vweight) for state in states],
                                                     [state.egroups for state in states],
                                                     [_prop("e", state.g, state.esrcpos) for state in states],
                                                     [_prop("e", state.g, state.etgtpos) for state in states],
                                                     float(beta), sequential,
                                                     parallel, random_move,
                                                     (node_coherent, confine_layers),
                                                     c, main_state.is_weighted,
                                                     nmerges,
                                                     _prop("v", main_state.g, merge_map),
                                                     niter, main_state.B,
                                                     [state.partition_stats for state in states] if not main_state.overlap else [],
                                                     [state.partition_stats for state in states] if main_state.overlap else [],
                                                     [state.overlap_stats for state in states],
                                                     verbose, _get_rng())
1196
    finally:
1197
1198
1199
1200
1201
1202
1203
1204
1205
        for state in states:
            if random_move:
                state.egroups = None
            if nmerges > 0:
                state.nsampler = None
                state.egroups = None
        if covariate and nmoves > 0:
            main_state._CovariateBlockState__bg = None

1206
1207
1208
1209
        libcommunity.clear_safelog()
        libcommunity.clear_xlogx()
        libcommunity.clear_lgamma()

1210
1211
    if _bm_test():
        assert main_state._BlockState__check_clabel(), "clabel invalidated!"
1212
        assert not (isinf(dS) or isnan(dS)), "invalid after sweep: %g" % dS
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
        if not covariate or nmerges == 0:
            S2 = main_state.entropy(dense=dense, multigraph=multigraph,
                                    complete=False, dl=dl, edges_dl=edges_dl,
                                    dl_deg_alt=False, xi_fast=True)
            c_dS = S2 - S
            if not abs(dS - c_dS) < 1e-6 * state.E:
                S3 = main_state.copy().entropy(dense=dense, multigraph=multigraph, complete=False,
                                               dl=dl, edges_dl=False, dl_deg_alt=False, xi_fast=True)
                print(dS, c_dS, nmoves, state.overlap, dense, multigraph,
                      main_state.deg_corr, main_state.is_weighted, node_coherent, beta, S2, S3)
            assert abs(dS - c_dS) < 1e-6 * state.E, "invalid delta S (%g, %g)" % (dS, c_dS)
1224

1225
    return dS, nmoves
1226

1227

1228
1229
1230
1231
def pmap(prop, value_map):
    """Maps all the values of `prop` to the values given by `value_map`, which
    is indexed by the values of `prop`."""
    if isinstance(prop, PropertyMap):
1232
1233
1234
        a = prop.fa
    else:
        a = prop
1235
    if isinstance(value_map, PropertyMap):
1236
        value_map = value_map.fa
1237
1238
    if a.max() >= len(value_map):
        raise ValueError("value map is not large enough! %s, %s" % (a.max(),
1239
                                                                    len(value_map)))
1240
1241
1242
1243
    if a.dtype != value_map.dtype:
        value_map = array(value_map, dtype=a.dtype)
    if a.dtype == "int64":
        libcommunity.vector_map64(a, value_map)
1244
    else:
1245
1246
1247
        libcommunity.vector_map(a, value_map)
    if isinstance(prop, PropertyMap):
        prop.fa = a
1248
1249
1250
1251
1252

def reverse_map(prop, value_map):
    """Modify `value_map` such that the positions indexed by the values in `prop`
    correspond to their index in `prop`."""
    if isinstance(prop, PropertyMap):
1253
        prop = prop.fa
1254
    if isinstance(value_map, PropertyMap):
1255
1256
1257
1258
1259
1260
1261
1262
1263
        a = value_map.fa
    else:
        a = value_map
    if prop.max() >= len(a):
        raise ValueError("value map is not large enough! (%d, %d)" % (prop.max(), len(a)))
    if prop.dtype != a.dtype:
        prop = array(prop, dtype=a.dtype)
    if a.dtype == "int64":
        libcommunity.vector_rmap64(prop, a)