blockmodel.py 88.6 KB
Newer Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
        self.b_cache = {}
        self.checkpoint_state = defaultdict(dict)

    def clear(self):
        self.b_cache.clear()
        self.checkpoint_state.clear()


def multilevel_minimize(state, B, nsweeps=10, adaptive_sweeps=True, epsilon=0,
                        anneal=(1., 1.), r=2., nmerge_sweeps=10, greedy=True,
1011
                        c=0., dense=False, multigraph=False, sequential=True,
1012
                        checkpoint=None, minimize_state=None, verbose=False):
Tiago Peixoto's avatar
Tiago Peixoto committed
1013
    r"""Performs an agglomerative heuristic, which progressively merges blocks together (while allowing individual node moves) to achieve a good partition in ``B`` blocks.
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045

    Parameters
    ----------
    state : :class:`~graph_tool.community.BlockState`
        The block state.
    B : ``int``
        The desired number of blocks.
    nsweeps : ``int`` (optional, default: ``10``)
        The number of sweeps done after each merge step to reach the local
        minimum.
    adaptive_sweeps : ``bool`` (optional, default: ``True``)
        If ``True``, the number of sweeps necessary for the local minimum will
        be estimated to be enough so that no more than ``epsilon * N`` nodes
        changes their states in the last ``nsweeps`` sweeps.
    epsilon : ``float`` (optional, default: ``0``)
        Converge criterion for ``adaptive_sweeps``.
    anneal : pair of ``floats`` (optional, default: ``(1., 1.)``)
        The first value specifies the starting value for  ``beta`` of the MCMC
        steps, and the second value is the factor which is multiplied to ``beta``
        after each estimated equilibration (according to ``nsweeps`` and
        ``adaptive_sweeps``).
    r : ``float`` (optional, default: ``2.``)
        Agglomeration ratio for the merging steps. Each merge step will attempt
        to find the best partition into :math:`B_{i-1} / r` blocks, where
        :math:`B_{i-1}` is the number of blocks in the last step.
    nmerge_sweeps : `int` (optional, default: `10`)
        The number of merge sweeps done, where in each sweep a better merge
        candidate is searched for every block.
    greedy : ``bool`` (optional, default: ``True``)
        If ``True``, the value of ``beta`` of the MCMC steps are kept at
        infinity for all steps. Otherwise they change according to the ``anneal``
        parameter.
1046
    c : ``float`` (optional, default: ``0.0``)
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
        This parameter specifies how often fully random moves are attempted,
        instead of more likely moves based on the inferred block partition.
        For ``c == 0``, no fully random moves are attempted, and for ``c == inf``
        they are always attempted.
    dense : ``bool`` (optional, default: ``False``)
        If ``True``, the "dense" variant of the entropy will be computed.
    multigraph : ``bool`` (optional, default: ``False``)
        If ``True``, the multigraph entropy will be used. Only has an effect
        if ``dense == True``.
    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.
    vertices: ``list of ints`` (optional, default: ``None``)
        A list of vertices which will be attempted to be moved. If ``None``, all
        vertices will be attempted.
    checkpoint : function (optional, default: ``None``)
        If provided, this function will be called after each call to
        :func:`mcmc_sweep`. This can be used to store the current state, so it
        can be continued later. The function must have the following signature:

        .. code-block:: python

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

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

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

    Returns
    -------

    state : :class:`~graph_tool.community.BlockState`
        The new :class:`~graph_tool.community.BlockState` with ``B`` blocks.

    Notes
    -----

    This algorithm performs an agglomerative heuristic on the current block state,
    where blocks are progressively merged together, using repeated applications of
1105
    the :func:`mcmc_sweep` moves, at different scales. See [peixoto-efficient-2014]_
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
    for more details.

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

    Examples
    --------
    .. testsetup:: multilevel_minimize

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

    .. doctest:: multilevel_minimize

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(gt.GraphView(g, directed=False)))
       >>> state = gt.BlockState(g, B=g.num_vertices(), deg_corr=True)
       >>> state = gt.multilevel_minimize(state, B=2)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=state.get_blocks(), output="polblogs_agg.pdf")
       <...>

    .. testcleanup:: multilevel_minimize

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=state.get_blocks(), output="polblogs_agg.png")

    .. figure:: polblogs_agg.*
       :align: center

       Block partition of a political blogs network with :math:`B=2`.

     References
    ----------

1139
1140
1141
    .. [peixoto-efficient-2014] Tiago P. Peixoto, "Efficient Monte Carlo and greedy
       heuristic for the inference of stochastic block models", Phys. Rev. E 89, 012804 (2014),
       :doi:`10.1103/PhysRevE.89.012804`, :arxiv:`1310.4378`.
1142
1143
1144
1145
1146
1147
1148
1149
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
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
    """

    if minimize_state is None:
        minimize_state = MinimizeState()
    b_cache = minimize_state.b_cache
    checkpoint_state = minimize_state.checkpoint_state

    # some trivial boundary conditions
    if B == 1:
        bi = state.g.new_vertex_property("int")
        state = BlockState(state.g, vweight=state.vweight, eweight=state.eweight,
                           b=bi, clabel=state.clabel, deg_corr=state.deg_corr,
                           max_BE=state.max_BE)
        return state
    if B == state.g.num_vertices():
        bi = state.g.new_vertex_property("int")
        bi.fa = range(state.g.num_vertices())
        state = BlockState(state.g, vweight=state.vweight, eweight=state.eweight,
                           B=state.g.num_vertices(), b=bi,
                           clabel=state.clabel, deg_corr=state.deg_corr,
                           max_BE=state.max_BE)
        return state

    Bi = state.B
    while True:
        Bi = max(int(round(Bi / r)), B)
        if Bi == state.B and Bi > B:
            Bi -= 1

        if b_cache is not None and Bi in b_cache:
            bi = state.g.new_vertex_property("int")
            bi.fa = b_cache[Bi][1]
            state = BlockState(state.g, B=Bi, b=bi,
                               vweight=state.vweight, eweight=state.eweight,
                               clabel=state.clabel, deg_corr=state.deg_corr,
                               max_BE=state.max_BE)

        if Bi < state.B:
            if verbose:
                print("Shrinking:", state.B, "->", Bi)
            state = greedy_shrink(state, B=Bi, nsweeps=nsweeps, epsilon=epsilon, c=c,
                                  dense=dense, multigraph=multigraph,
                                  nmerge_sweeps=nmerge_sweeps, sequential=sequential,
                                  verbose=verbose)

        if "S" in checkpoint_state[Bi]:
            S = checkpoint_state[Bi]["S"]
            niter = checkpoint_state[Bi]["niter"]
        else:
            S = state.entropy(dl=True)
            checkpoint_state[Bi]["S"] = S
            niter = 0
            checkpoint_state[Bi]["niter"] = niter

        if b_cache is not None and Bi not in b_cache:
            b_cache[Bi] = [float("inf"), array(state.b.fa), None]

        if not adaptive_sweeps:
            ntotal = nsweeps if greedy else 2 * nsweeps
            if verbose:
                print("Performing %d sweeps for B=%d..." % (ntotal, Bi))

            for i in range(ntotal):
                if i < niter:
                    continue
                if i < nsweeps and not greedy:
                    beta = anneal[0]
1209
                else:
1210
1211
1212
                    beta = float("inf")
                delta, nmoves = mcmc_sweep(state, beta=beta, c=c,
                                           dense=dense, multigraph=multigraph,
1213
                                           sequential=sequential)
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
                S += delta
                niter += 1
                checkpoint_state[Bi]["S"] = S
                checkpoint_state[Bi]["niter"] = niter
                if b_cache is not None:
                    b_cache[Bi][1] = array(state.b.fa)
                if checkpoint is not None:
                    checkpoint(state, S, delta, nmoves, minimize_state)
        else:
            # adaptive mode
            min_dl = checkpoint_state[Bi].get("min_dl", S)
            max_dl = checkpoint_state[Bi].get("max_dl", S)
            count = checkpoint_state[Bi].get("count", 0)
            bump = checkpoint_state[Bi].get("bump", False)
            beta =  checkpoint_state[Bi].get("beta", anneal[0])
            last_min = checkpoint_state[Bi].get("last_min", min_dl)
            greedy_step = checkpoint_state[Bi].get("greedy_step", greedy)
            total_nmoves = checkpoint_state[Bi].get("total_nmoves", 0)

            if verbose and not greedy:
                print("Performing sweeps for beta = %g, B=%d (N=%d)..." % \
                       (beta, Bi, state.g.num_vertices()))

            eps = 1e-8
            niter = 0
            while True:
                if greedy_step:
                    break
                if count > nsweeps:
                    if not bump:
                        min_dl = max_dl = S
                        bump = True
1246
                        count = 0
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
                    else:
                        if anneal[1] <= 1 or min_dl == last_min:
                            break
                        else:
                            beta *= anneal[1]
                            count = 0
                            last_min = min_dl
                            if verbose:
                                print("Performing sweeps for beta = %g, B=%d (N=%d)..." % \
                                       (beta, Bi, state.g.num_vertices()))

                delta, nmoves = mcmc_sweep(state, beta=beta, c=c,
                                           dense=dense, multigraph=multigraph,
1260
                                           sequential=sequential)
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
                S += delta
                niter += 1
                total_nmoves += nmoves

                if S > max_dl + eps:
                    max_dl = S
                    count = 0
                elif S < min_dl - eps:
                    min_dl = S
                    count = 0
                else:
                    count += 1

                checkpoint_state[B]["S"] = S
                checkpoint_state[B]["niter"] = niter
                checkpoint_state[B]["min_dl"] = min_dl
                checkpoint_state[B]["max_dl"] = max_dl
                checkpoint_state[B]["count"] = count
                checkpoint_state[B]["bump"] = bump
                checkpoint_state[B]["total_nmoves"] = total_nmoves

                if b_cache is not None:
                    b_cache[Bi][0] = float("inf")
                    b_cache[Bi][1] = array(state.b.fa)
                if checkpoint is not None:
                    checkpoint(state, S, delta, nmoves, minimize_state)
1287

1288
1289
1290
            if verbose:
                if not greedy_step:
                    print("... performed %d sweeps with %d vertex moves" % (niter, total_nmoves))
1291
1292
                print("Performing sweeps for beta = ∞, B=%d (N=%d)..." % \
                      (Bi, state.g.num_vertices()))
1293

1294
1295
            if not greedy_step:
                checkpoint_state[Bi]["greedy_step"] = True
1296
1297
1298
                min_dl = S
                count = 0

1299
1300
1301
1302
1303
            niter = 0
            total_nmoves = 0
            while count <= nsweeps:
                delta, nmoves = mcmc_sweep(state, beta=float("inf"), c=c,
                                           dense=dense, multigraph=multigraph,
1304
                                           sequential=sequential)
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
                S += delta
                niter += 1
                total_nmoves += nmoves

                # if verbose:
                #     print("Moved:", delta, nmoves,
                #           nmoves / state.g.num_vertices(),
                #           epsilon, count)

                #if nmoves > epsilon * state.g.num_vertices():
                if abs(delta) > eps and nmoves / state.g.num_vertices() > epsilon:
                    min_dl = S
                    count = 0
                else:
                    count += 1
                checkpoint_state[Bi]["S"] = S
                checkpoint_state[Bi]["min_dl"] = min_dl
                checkpoint_state[Bi]["count"] = count
                checkpoint_state[B]["total_nmoves"] = total_nmoves
                if b_cache is not None:
                    b_cache[Bi][1] = array(state.b.fa)
                if checkpoint is not None:
                    checkpoint(state, S, delta, nmoves, minimize_state)
1328

1329
1330
            if verbose:
                print("... performed %d sweeps with %d vertex moves" % (niter, total_nmoves))
1331

1332
1333
1334
            bi = state.b
            if Bi == B:
                break
1335

1336
    return state
1337

1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
def get_state_dl(state, dense, nested_dl, clabel=None):
    if not nested_dl:
        dl = state.entropy(dense=dense, multigraph=dense, dl=True)
    else:
        dl = state.entropy(dense=dense, multigraph=dense, dl=False) + \
             partition_entropy(B=state.B, N=state.N, nr=state.wr.a) / state.E
        if clabel is None:
            bclabel = state.bclabel
        else:
            bclabel = state.bg.new_vertex_property("int")
            libcommunity.vector_rmap(state.b.a, bclabel.a)
            libcommunity.vector_map(bclabel.a, clabel.a)

        bstate = BlockState(state.bg, b=bclabel, eweight=state.mrs,
                            deg_corr=False)
        dl += bstate.entropy(dl=False, dense=True, multigraph=True) + \
              partition_entropy(B=bstate.B, N=bstate.N, nr=bstate.wr.a) / state.E
    return dl


1358
def get_b_dl(g, vweight, eweight, B, nsweeps, adaptive_sweeps, c,
1359
1360
1361
1362
1363
1364
             sequential, shrink, r, anneal, greedy, epsilon, nmerge_sweeps, clabel,
             deg_corr, dense, sparse_heuristic, checkpoint, minimize_state,
             max_BE, nested_dl,  verbose):
    bs = minimize_state.b_cache
    checkpoint_state = minimize_state.checkpoint_state
    previous = None
1365
    if B in bs and checkpoint_state[B].get("done", False):
1366
1367
1368
        # A previous finished result is available. Use that and keep going.
        if verbose:
            print("(using previous finished result for B=%d)" % B)
1369
        return bs[B][0]
1370
    elif B in bs:
1371
        # A previous unfinished result is available. Use that as the starting point.
1372
        if verbose:
1373
1374
1375
1376
1377
1378
            print("(starting from previous result for B=%d)" % B)
        b = g.new_vertex_property("int")
        b.fa = bs[B][1]
        state = BlockState(g, b=b, B=B, vweight=vweight, eweight=eweight,
                           clabel=clabel, deg_corr=deg_corr, max_BE=max_BE)
        previous = bs[B]
1379
    else:
1380
        # No previous result is available.
1381
        bs_keys = [k for k in bs.keys() if type(k) != str]
1382
        B_sup = max(max(bs_keys), B) if len(bs_keys) > 0 else B
1383
1384
1385
        for Bi in bs_keys:
            if Bi > B and Bi < B_sup:
                B_sup = Bi
1386
1387
1388
1389
1390
1391
1392
1393
        if B_sup == B or not shrink:
            # Start from scratch.
            bi = g.new_vertex_property("int")
            bi.fa = range(g.num_vertices())
            state = BlockState(g, B=g.num_vertices(), b=bi,
                               vweight=vweight,
                               eweight=eweight, clabel=clabel,
                               deg_corr=deg_corr, max_BE=max_BE)
1394
        else:
1395
            # Start from result with B_sup > B, and shrink it.
1396
            if verbose:
1397
1398
1399
                print("(shrinking from B=%d to B=%d)" % (B_sup, B))
            b = g.new_vertex_property("int")
            b.fa = bs[B_sup][1]
1400

1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
            if B > 1:
                state = BlockState(g, B=B_sup, b=b, vweight=vweight, eweight=eweight,
                                   clabel=clabel, deg_corr=deg_corr,
                                   max_BE=max_BE)
            else:
                bi = g.new_vertex_property("int")
                bi.fa = range(g.num_vertices())
                state = BlockState(g, B=g.num_vertices(), b=bi,
                                   vweight=vweight,
                                   eweight=eweight, clabel=clabel,
                                   deg_corr=deg_corr, max_BE=max_BE)

    # perform the actual minimization
    state = multilevel_minimize(state, B, nsweeps=nsweeps,
                                adaptive_sweeps=adaptive_sweeps,
                                epsilon=epsilon, r=r, greedy=greedy,
                                nmerge_sweeps=nmerge_sweeps, anneal=anneal,
1418
                                c=c, dense=dense and not sparse_heuristic,
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
                                multigraph=dense,
                                sequential=sequential,
                                minimize_state=minimize_state,
                                checkpoint=checkpoint,
                                verbose=verbose)
    dl = get_state_dl(state, dense, nested_dl)

    if previous is None or dl < previous[0]:
        # the current result improved the previous one
        bs[B] = [dl, array(state.b.fa)]
        if verbose:
            print("(using new result for B=%d with L=%g)" % (B, dl))
    else:
        # the previous result is better than the current one
        if verbose:
            print("(kept old result for B=%d with L=%g [vs L=%g])" % (B, previous[0], dl))
        dl = previous[0]
1436
    checkpoint_state[B]["done"] = True
1437
    assert(not isinf(dl))
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
    return dl

def fibo(n):
    phi = (1 + sqrt(5)) / 2
    return int(round(phi ** n / sqrt(5)))

def fibo_n_floor(x):
    phi = (1 + sqrt(5)) / 2
    n = floor(log(x * sqrt(5) + 0.5) / log(phi))
    return int(n)

def get_mid(a, b):
    n = fibo_n_floor(b - a)
    return b - fibo(n - 1)

def is_fibo(x):
    return fibo(fibo_n_floor(x)) == x

1456
def minimize_blockmodel_dl(g, eweight=None, vweight=None, deg_corr=True, dense=False,
1457
                           sparse_heuristic=False, c=0, nsweeps=100,
1458
1459
1460
1461
1462
1463
                           adaptive_sweeps=True, epsilon=0., anneal=(1., 1.),
                           greedy_cooling=True, sequential=True, r=2,
                           nmerge_sweeps=10, max_B=None, min_B=1, mid_B=None,
                           clabel=None, checkpoint=None, minimize_state=None,
                           exhaustive=False, max_BE=None, nested_dl=False,
                           verbose=False):
1464
1465
1466
1467
1468
1469
1470
1471
    r"""Find the block partition of an unspecified size which minimizes the description
    length of the network, according to the stochastic blockmodel ensemble which
    best describes it.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph being used.
1472
1473
1474
1475
    eweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Edge weights (i.e. multiplicity).
    vweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex weights (i.e. multiplicity).
1476
1477
1478
    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.
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
    dense : ``bool`` (optional, default: ``False``)
        If ``True``, the "dense" variant of the entropy will be computed.
    sparse_heuristic : ``bool`` (optional, default: ``False``)
        If ``True``, the sparse entropy will be used to find the best partition,
        but the dense entropy will be used to compare different partitions. This
        has an effect only if ``dense == True``.
    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.
    nsweeps : ``int`` (optional, default: ``10``)
        The number of sweeps done after each merge step to reach the local
        minimum.
    adaptive_sweeps : ``bool`` (optional, default: ``True``)
        If ``True``, the number of sweeps necessary for the local minimum will
        be estimated to be enough so that no more than ``epsilon * N`` nodes
        changes their states in the last ``nsweeps`` sweeps.
    epsilon : ``float`` (optional, default: ``0``)
        Converge criterion for ``adaptive_sweeps``.
    anneal : pair of ``floats`` (optional, default: ``(1., 1.)``)
        The first value specifies the starting value for  ``beta`` of the MCMC
        steps, and the second value is the factor which is multiplied to ``beta``
        after each estimated equilibration (according to ``nsweeps`` and
        ``adaptive_sweeps``).
1504
    greedy_cooling : ``bool`` (optional, default: ``True``)
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
        If ``True``, the value of ``beta`` of the MCMC steps are kept at
        infinity for all steps. Otherwise they change according to the ``anneal``
        parameter.
    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.
    r : ``float`` (optional, default: ``2.``)
        Agglomeration ratio for the merging steps. Each merge step will attempt
        to find the best partition into :math:`B_{i-1} / r` blocks, where
        :math:`B_{i-1}` is the number of blocks in the last step.
    nmerge_sweeps : `int` (optional, default: `10`)
        The number of merge sweeps done, where in each sweep a better merge
        candidate is searched for every block.
1520
1521
1522
1523
1524
1525
1526
1527
    max_B : ``int`` (optional, default: ``None``)
        Maximum number of blocks tried. If not supplied, it will be
        automatically determined.
    min_B : ``int`` (optional, default: `1`)
        Minimum number of blocks tried.
    mid_B : ``int`` (optional, default: ``None``)
        Middle of the range which brackets the minimum. If not supplied, will be
        automatically determined.
1528
1529
1530
    clabel : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Constraint labels on the vertices, such that vertices with different
        labels cannot belong to the same block.
1531
1532
1533
1534
1535
1536
1537
    checkpoint : function (optional, default: ``None``)
        If provided, this function will be called after each call to
        :func:`mcmc_sweep`. This can be used to store the current state, so it
        can be continued later. The function must have the following signature:

        .. code-block:: python

1538
            def checkpoint(state, L, delta, nmoves, minimize_state):
1539
1540
1541
1542
1543
                ...

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

        This function will also be called when the MCMC has finished for the
        current value of :math:`B`, in which case ``state == None``, and the
1552
        remaining parameters will be zero, except the last.
1553
    minimize_state : :class:`~graph_tool.community.MinimizeState` (optional, default: ``None``)
1554
        If provided, this will specify an exact point of execution from which
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
        the algorithm will continue. The expected object is a
        :class:`~graph_tool.community.MinimizeState`
        instance which will be passed to the callback of the ``checkpoint``
        option above, and  can be stored by :mod:`pickle`.
    exhaustive : ``bool`` (optional, default: ``False``)
        If ``True``, the best value of ``B`` will be found by testing all possible
        values, instead of performing a bisection search.
    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,
1566
1567
1568
1569
1570
1571
1572
    verbose : ``bool`` (optional, default: ``False``)
        If ``True``, verbose information is displayed.

    Returns
    -------
    b : :class:`~graph_tool.PropertyMap`
       Vertex property map with the best block partition.
1573
1574
    min_dl : ``float``
       Minimum value of the description length (in `nats <http://en.wikipedia.org/wiki/Nat_%28information%29>`_ per edge).
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595

    Notes
    -----

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

    .. math::

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

    where :math:`\mathcal{S}_{t/c}` is the blockmodel entropy (as described in
    the docstring of :func:`mcmc_sweep` and :meth:`BlockState.entropy`) and
    :math:`\mathcal{L}_{t/c}` is the information necessary to describe the model
    (as described in the docstring of :func:`model_entropy` and
    :meth:`BlockState.entropy`).

    The algorithm works by minimizing the entropy :math:`\mathcal{S}_{t/c}` for
    specific values of :math:`B` via :func:`mcmc_sweep` (with :math:`\beta = 1`
    and :math:`\beta\to\infty`), and minimizing :math:`\Sigma_{t/c}` via an
    one-dimensional Fibonacci search on :math:`B`. See
Tiago Peixoto's avatar
Tiago Peixoto committed
1596
    [peixoto-parsimonious-2013]_ for more details.
1597

1598
1599
    This algorithm has a complexity of :math:`O(\tau N\ln^2 B_{\text{max}})`,
    where :math:`N` is the number of nodes in the network, :math:`\tau` is the
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
    mixing time of the MCMC, and :math:`B_{\text{max}}` is the maximum number of
    blocks considered. If :math:`B_{\text{max}}` is not supplied, it is computed
    as :math:`\sim\sqrt{E}` via :func:`get_max_B`, in which case the complexity
    becomes :math:`O(\tau E\ln E)`.


    Examples
    --------
    .. testsetup:: mdl

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

    .. doctest:: mdl

       >>> g = gt.collection.data["polbooks"]
1616
       >>> b, mdl = gt.minimize_blockmodel_dl(g)
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=b, vertex_shape=b, output="polbooks_blocks_mdl.pdf")
       <...>

    .. testcleanup:: mdl

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=b, vertex_shape=b, output="polbooks_blocks_mdl.png")

    .. figure:: polbooks_blocks_mdl.*
       :align: center

       Block partition of a political books network, which minimizes the description
1628
       length of the network according to the degree-corrected stochastic blockmodel.
1629
1630
1631
1632
1633
1634
1635
1636
1637

    References
    ----------

    .. [holland-stochastic-1983] Paul W. Holland, Kathryn Blackmond Laskey,
       Samuel Leinhardt, "Stochastic blockmodels: First steps",
       Carnegie-Mellon University, Pittsburgh, PA 15213, U.S.A., :doi:`10.1016/0378-8733(83)90021-7`
    .. [faust-blockmodels-1992] Katherine Faust, and Stanley
       Wasserman. "Blockmodels: Interpretation and Evaluation." Social Networks
1638
       14, no. 1-2 (1992): 5-61. :doi:`10.1016/0378-8733(92)90013-W`
1639
1640
1641
1642
1643
1644
    .. [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
       Ensembles." Physical Review E 85, no. 5 (2012): 056122. :doi:`10.1103/PhysRevE.85.056122`,
       :arxiv:`1112.6028`.
Tiago Peixoto's avatar
Tiago Peixoto committed
1645
1646
    .. [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`.
1647
1648
1649
    .. [peixoto-efficient-2014] Tiago P. Peixoto, "Efficient Monte Carlo and greedy
       heuristic for the inference of stochastic block models", Phys. Rev. E 89, 012804 (2014),
       :doi:`10.1103/PhysRevE.89.012804`, :arxiv:`1310.4378`.
1650
1651
1652
    """

    if max_B is None:
1653
1654
1655
1656
        if dense:
            max_B = max(g.num_vertices(), 1)
        else:
            max_B = get_max_B(g.num_vertices(), g.num_edges(), g.is_directed())
1657
1658
1659
1660
1661
1662
1663
1664
1665
        if verbose:
            print("max_B:", max_B)
    if min_B is None:
        min_B = 1

    if mid_B is None:
        mid_B = get_mid(min_B, max_B)

    greedy = greedy_cooling
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
    shrink = True

    if minimize_state is None:
        minimize_state = MinimizeState()

    b_cache = minimize_state.b_cache
    checkpoint_state = minimize_state.checkpoint_state

    if exhaustive:
        if max_B not in b_cache:
            bi = g.new_vertex_property("int")
            bi.fa = range(g.num_vertices())
            state = BlockState(g, B=g.num_vertices(), b=bi,
                               vweight=vweight, eweight=eweight,
                               clabel=clabel, deg_corr=deg_corr,
                               max_BE=max_BE)

        for B in reversed(range(min_B, max_B + 1)):
            if B in b_cache:
                bi = g.new_vertex_property("int")
                bi.fa = b_cache[B][1]
                state = BlockState(g, b=bi, vweight=vweight, eweight=eweight,
                                   clabel=clabel, deg_corr=deg_corr,
                                   max_BE=max_BE)

                if checkpoint_state[B].get("done", False):
                    continue

            state = multilevel_minimize(state, B, nsweeps=nsweeps,
                                        adaptive_sweeps=adaptive_sweeps,
                                        r=r, greedy=greedy,
                                        anneal=anneal, c=c,
                                        dense=dense and not sparse_heuristic,
                                        multigraph=dense,
                                        sequential=sequential,
                                        nmerge_sweeps=nmerge_sweeps,
                                        epsilon=epsilon,
                                        checkpoint=checkpoint,
                                        minimize_state=checkpoint_state,
                                        verbose=verbose)

            dl = get_state_dl(state, dense, nested_dl)

            b_cache[B] = [dl, array(state.b.fa)]

            if verbose:
                print("Result for B=%d: L=%g" % (B, dl))

        min_dl = float(inf)
        best_B = None
        for Bi in b_cache.keys():
            if b_cache[Bi][0] <= min_dl:
                min_dl = b_cache[Bi][0]
                best_B = Bi
        if verbose:
            print("Best result: B=%d, L=%g" % (best_B, min_dl))
        b = g.new_vertex_property("int")
        b.fa = b_cache[best_B][1]

        return b, b_cache[best_B][0]

1727

1728
    args = dict(g=g, vweight=vweight, eweight=eweight, nsweeps=nsweeps,
1729
                adaptive_sweeps=adaptive_sweeps, c=c,
1730
1731
1732
1733
1734
1735
1736
1737
1738
                sequential=sequential, shrink=shrink, r=r, anneal=anneal,
                greedy=greedy, epsilon=epsilon, nmerge_sweeps=nmerge_sweeps,
                clabel=clabel, deg_corr=deg_corr, dense=dense,
                sparse_heuristic=sparse_heuristic, checkpoint=checkpoint,
                minimize_state=minimize_state, max_BE=max_BE,
                nested_dl=nested_dl, verbose=verbose)


    # Initial bracketing
1739
    while True:
1740
1741
1742
        f_max = get_b_dl(B=max_B, **args)
        f_mid = get_b_dl(B=mid_B, **args)
        f_min = get_b_dl(B=min_B, **args)
1743
1744

        if verbose:
1745
            print("Current bracket:", (min_B, mid_B, max_B), (f_min, f_mid, f_max))
1746
1747

        if checkpoint is not None:
1748
             checkpoint(None, 0, 0, 0, minimize_state)
1749
1750
1751
1752
1753

        if f_max > f_mid > f_min:
            max_B = mid_B
            mid_B = get_mid(min_B, mid_B)
        elif f_max < f_mid < f_min:
1754
            min_B = mid_B
1755
1756
1757
1758
            mid_B = get_mid(mid_B, max_B)
        else:
            break

1759
    # Fibonacci search
1760
1761
1762
1763
1764
1765
    while True:
        if max_B - mid_B > mid_B - min_B:
            x = get_mid(mid_B, max_B)
        else:
            x = get_mid(min_B, mid_B)

1766
1767
        f_x = get_b_dl(B=x, **args)
        f_mid = get_b_dl(B=mid_B, **args)
1768
1769

        if verbose:
1770
1771
1772
1773
            print("Current bracket:",
                  (min_B, mid_B, max_B), (get_b_dl(B=min_B, **args), f_mid,
                                          get_b_dl(B=max_B, **args)))
            print("Bisect at", x, "with L=%g" % f_x)
1774
1775
1776
1777

        if max_B - mid_B <= 1:
            min_dl = float(inf)
            best_B = None
1778
1779
1780
            for Bi in b_cache.keys():
                if b_cache[Bi][0] <= min_dl:
                    min_dl = b_cache[Bi][0]
1781
1782
                    best_B = Bi
            if verbose:
1783
1784
1785
1786
1787
                print("Best result: B=%d, L=%g" % (best_B, min_dl))
            b = g.new_vertex_property("int")
            b.fa = b_cache[best_B][1]

            return b, b_cache[best_B][0]
1788
1789

        if checkpoint is not None:
1790
            checkpoint(None, 0, 0, 0, minimize_state)
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848

        if f_x < f_mid:
            if max_B - mid_B > mid_B - min_B:
                min_B = mid_B
                mid_B = x
            else:
                max_B = mid_B
                mid_B = x
        else:
            if max_B - mid_B > mid_B - min_B:
                max_B = x
            else:
                min_B = x


def collect_edge_marginals(state, p=None):
    r"""Collect the edge marginal histogram, which counts the number of times
    the endpoints of each node have been assigned to a given block pair.

    This should be called multiple times, after repeated runs of the
    :func:`mcmc_sweep` function.

    Parameters
    ----------
    state : :class:`~graph_tool.community.BlockState`
        The block state.
    p : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Edge property map with vector-type values, storing the previous block
        membership counts.  Each vector entry corresponds to ``b[i] + B *
        b[j]``, where ``b`` is the block membership and ``i = min(source(e),
        target(e))`` and ``j = max(source(e), target(e))``. If not provided, an
        empty histogram will be created.

    Returns
    -------
    p : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex property map with vector-type values, storing the accumulated
        block membership counts.


    Examples
    --------
    .. testsetup:: collect_edge_marginals

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

    .. doctest:: collect_edge_marginals

       >>> g = gt.collection.data["polbooks"]
       >>> state = gt.BlockState(g, B=4, deg_corr=True)
       >>> pe = 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)
       ...     pe = gt.collect_edge_marginals(state, pe)
       >>> gt.bethe_entropy(state, pe)[0]
Tiago Peixoto's avatar
Tiago Peixoto committed
1849
       17.443089842818125
1850
1851
1852
1853
1854
1855
1856
    """

    if p is None:
        p = state.g.new_edge_property("vector<int>")

    libcommunity.edge_marginals(state.g._Graph__graph,
                                state.bg._Graph__graph,
1857
                                state.B,
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
                                _prop("v", state.g, state.b),
                                _prop("e", state.g, p))
    return p

def collect_vertex_marginals(state, p=None):
    r"""Collect the vertex marginal histogram, which counts the number of times a
    node was assigned to a given block.

    This should be called multiple times, after repeated runs of the
    :func:`mcmc_sweep` function.

    Parameters
    ----------
    state : :class:`~graph_tool.community.BlockState`
        The block state.
    p : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex property map with vector-type values, storing the previous block
        membership counts. If not provided, an empty histogram will be created.

    Returns
    -------
    p : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex property map with vector-type values, storing the accumulated
        block membership counts.

    Examples
    --------
    .. testsetup:: cvm

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

    .. doctest:: cvm

       >>> g = gt.collection.data["polbooks"]
       >>> state = gt.BlockState(g, B=4, 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.mf_entropy(state, pv)
Tiago Peixoto's avatar
Tiago Peixoto committed
1901
       19.94955528942717
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_shape="pie", vertex_pie_fractions=pv, output="polbooks_blocks_soft_B4.pdf")
       <...>

    .. testcleanup:: cvm

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

    .. figure:: polbooks_blocks_soft_B4.*
       :align: center

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

    """
1915
    B = state.B
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969

    if p is None:
        p = state.g.new_vertex_property("vector<int>")

    libcommunity.vertex_marginals(state.g._Graph__graph,
                                  _prop("v", state.g, state.b),
                                  _prop("v", state.g, p))
    return p

def bethe_entropy(state, p):
    r"""Compute the Bethe entropy given the edge block membership marginals.

    Parameters
    ----------
    state : :class:`~graph_tool.community.BlockState`
        The block state.
    p : :class:`~graph_tool.PropertyMap`
        Edge property map with vector-type values, storing the previous block
        membership counts.  Each vector entry corresponds to ``b[i] + B *
        b[j]``, where ``b`` is the block membership and ``i = min(source(e),
        target(e))`` and ``j = max(source(e), target(e))``.

    Returns
    -------
    H : ``float``
        The Bethe entropy value (in `nats <http://en.wikipedia.org/wiki/Nat_%28information%29>`_)
    Hmf : ``float``
        The "mean field" entropy value (in `nats <http://en.wikipedia.org/wiki/Nat_%28information%29>`_),
        as would be returned by the :func:`mf_entropy` function.
    pv : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex property map with vector-type values, storing the accumulated
        block membership counts. These are the node marginals, as would be
        returned by the :func:`collect_vertex_marginals` function.

    Notes
    -----

    The Bethe entropy is defined as,

    .. math::

        H = -\sum_{e,(r,s)}\pi_{(r,s)}^e\ln\pi_{(r,s)}^e - \sum_{v,r}(1-k_i)\pi_r^v\ln\pi_r^v,

    where :math:`\pi_{(r,s)}^e` is the marginal probability that the endpoints
    of the edge :math:`e` belong to blocks :math:`(r,s)`, and :math:`\pi_r^v` is
    the marginal probability that vertex :math:`v` belongs to block :math:`r`,
    and :math:`k_i` is the degree of vertex :math:`v` (or total degree for
    directed graphs).

    References
    ----------
    .. [mezard-information-2009] Marc Mézard, Andrea Montanari, "Information,
       Physics, and Computation", Oxford Univ Press, 2009.
    """
1970
    B = state.B
1971
1972
1973
1974
    H = 0
    pv =  state.g.new_vertex_property("vector<double>")

    H, sH, Hmf, sHmf  = libcommunity.bethe_entropy(state.g._Graph__graph,
1975
1976
1977
                                                   state.B,
                                                   _prop("e", state.g, p),
                                                   _prop("v", state.g, pv))
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
    return H, Hmf, pv


def mf_entropy(state, p):
    r"""Compute the "mean field" entropy given the vertex block membership marginals.

    Parameters
    ----------
    state : :class:`~graph_tool.community.BlockState`
        The block state.
    p : :class:`~graph_tool.PropertyMap`
        Vertex property map with vector-type values, storing the accumulated block
        membership counts.

    Returns
    -------
    Hmf : ``float``
        The "mean field" entropy value (in `nats <http://en.wikipedia.org/wiki/Nat_%28information%29>`_).

    Notes
    -----

    The "mean field" entropy is defined as,