blockmodel.py 88.6 KB
Newer Older
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033

    .. math::

        H = - \sum_{v,r}\pi_r^v\ln\pi_r^v,

    where :math:`\pi_r^v` is the marginal probability that vertex :math:`v`
    belongs to block :math:`r`.

    References
    ----------
    .. [mezard-information-2009] Marc Mézard, Andrea Montanari, "Information,
       Physics, and Computation", Oxford Univ Press, 2009.

    """
    H = 0
    for v in state.g.vertices():
        N = p[v].a.sum()
        if N == 0:
            continue
        pvi = asarray(p[v].a, dtype="float") /  N
        pvi = pvi[pvi > 0]
        H -= (pvi * log(pvi)).sum()
    return H


def condensation_graph(g, prop, vweight=None, eweight=None, avprops=None,
                       aeprops=None, self_loops=False):
    r"""
    Obtain the condensation graph, where each vertex with the same 'prop' value is condensed in one vertex.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
2034
        Graph to be modelled.
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
    prop : :class:`~graph_tool.PropertyMap`
        Vertex property map with the community partition.
    vweight : :class:`~graph_tool.PropertyMap` (optional, default: None)
        Vertex property map with the optional vertex weights.
    eweight : :class:`~graph_tool.PropertyMap` (optional, default: None)
        Edge property map with the optional edge weights.
    avprops : list of :class:`~graph_tool.PropertyMap` (optional, default: None)
        If provided, the average value of each property map in this list for
        each vertex in the condensed graph will be computed and returned.
    aeprops : list of :class:`~graph_tool.PropertyMap` (optional, default: None)
        If provided, the average value of each property map in this list for
        each edge in the condensed graph will be computed and returned.
    self_loops : ``bool`` (optional, default: ``False``)
        If ``True``, self-loops due to intra-block edges are also included in
        the condensation graph.

    Returns
    -------
    condensation_graph : :class:`~graph_tool.Graph`
        The community network
    prop : :class:`~graph_tool.PropertyMap`
        The community values.
    vcount : :class:`~graph_tool.PropertyMap`
        A vertex property map with the vertex count for each community.
    ecount : :class:`~graph_tool.PropertyMap`
        An edge property map with the inter-community edge count for each edge.
2061
2062
2063
2064
2065
2066
    va : list of :class:`~graph_tool.PropertyMap`
        A list of vertex property maps with average values of the properties
        passed via the ``avprops`` parameter.
    ea : list of :class:`~graph_tool.PropertyMap`
        A list of edge property maps with average values of the properties
        passed via the ``avprops`` parameter.
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183

    See Also
    --------
    community_structure: Obtain the community structure
    modularity: Calculate the network modularity
    condensation_graph: Network of communities, or blocks

    Notes
    -----
    Each vertex in the condensation graph represents one community in the
    original graph (vertices with the same 'prop' value), and the edges
    represent existent edges between vertices of the respective communities in
    the original graph.

    Examples
    --------

    .. testsetup:: condensation_graph

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

    Let's first obtain the best block partition with ``B=5``.

    .. doctest:: condensation_graph

       >>> g = gt.collection.data["polbooks"]
       >>> state = gt.BlockState(g, B=5, deg_corr=True)
       >>> 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, beta=float("inf"))
       >>> b = state.get_blocks()
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=b, vertex_shape=b, output="polbooks_blocks_B5.pdf")
       <...>

    Now we get the condensation graph:

    .. doctest:: condensation_graph

       >>> bg, bb, vcount, ecount, avp, aep = gt.condensation_graph(g, b, avprops=[g.vp["pos"]], self_loops=True)
       >>> gt.graph_draw(bg, pos=avp[0], vertex_fill_color=bb, vertex_shape=bb,
       ...               vertex_size=gt.prop_to_size(vcount, mi=40, ma=100),
       ...               edge_pen_width=gt.prop_to_size(ecount, mi=2, ma=10),
       ...               output="polbooks_blocks_B5_cond.pdf")
       <...>

    .. testcleanup:: condensation_graph

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=b, vertex_shape=b, output="polbooks_blocks_B5.png")
       gt.graph_draw(bg, pos=avp[0], vertex_fill_color=bb, vertex_shape=bb,
                     vertex_size=gt.prop_to_size(vcount, mi=40, ma=100),
                     edge_pen_width=gt.prop_to_size(ecount, mi=2, ma=10),
                     output="polbooks_blocks_B5_cond.png")

    .. figure:: polbooks_blocks_B5.*
       :align: left

       Block partition of a political books network with :math:`B=5`.

    .. figure:: polbooks_blocks_B5_cond.*
       :align: right

       Condensation graph of the obtained block partition.

    """
    gp = Graph(directed=g.is_directed())
    if vweight is None:
        vcount = gp.new_vertex_property("int32_t")
    else:
        vcount = gp.new_vertex_property(vweight.value_type())
    if eweight is None:
        ecount = gp.new_edge_property("int32_t")
    else:
        ecount = gp.new_edge_property(eweight.value_type())

    if prop is g.vertex_index:
        prop = prop.copy(value_type="int32_t")
    cprop = gp.new_vertex_property(prop.value_type())

    if avprops is None:
        avprops = []
    avp = []
    r_avp = []
    for p in avprops:
        if p is g.vertex_index:
            p = p.copy(value_type="int")
        if "string" in p.value_type():
            raise ValueError("Cannot compute average of string properties!")
        temp = g.new_vertex_property(p.value_type())
        cp = gp.new_vertex_property(p.value_type())
        avp.append((_prop("v", g, p), _prop("v", g, temp), _prop("v", g, cp)))
        r_avp.append(cp)

    if aeprops is None:
        aeprops = []
    aep = []
    r_aep = []
    for p in aeprops:
        if p is g.edge_index:
            p = p.copy(value_type="int")
        if "string" in p.value_type():
            raise ValueError("Cannot compute average of string properties!")
        temp = g.new_edge_property(p.value_type())
        cp = gp.new_edge_property(p.value_type())
        aep.append((_prop("e", g, p), _prop("e", g, temp), _prop("e", g, cp)))
        r_aep.append(cp)

    libcommunity.community_network(g._Graph__graph,
                                   gp._Graph__graph,
                                   _prop("v", g, prop),
                                   _prop("v", gp, cprop),
                                   _prop("v", gp, vcount),
                                   _prop("e", gp, ecount),
                                   _prop("v", g, vweight),
                                   _prop("e", g, eweight),
                                   self_loops)
2184
    u = GraphView(g, directed=True, reversed=False)
2185
2186
2187
2188
2189
2190
2191
    libcommunity.community_network_vavg(u._Graph__graph,
                                        gp._Graph__graph,
                                        _prop("v", g, prop),
                                        _prop("v", gp, cprop),
                                        _prop("v", gp, vcount),
                                        _prop("v", g, vweight),
                                        avp)
2192
    u = GraphView(g, directed=True)
2193
2194
2195
2196
2197
2198
2199
2200
2201
    libcommunity.community_network_eavg(u._Graph__graph,
                                        gp._Graph__graph,
                                        _prop("v", g, prop),
                                        _prop("v", gp, cprop),
                                        _prop("e", gp, ecount),
                                        _prop("e", g, eweight),
                                        aep,
                                        self_loops)
    return gp, cprop, vcount, ecount, r_avp, r_aep