Source code for graph_tool.inference.hrg

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2026 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from .. import _get_rng, Graph, GraphView
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_inference as libinference")

import numpy as np

__all__ = ["hrg_fit", "hrg_predict", "hrg_consensus", "hrg_generate"]

def _hrg_input(g):
    if g.is_directed():
        g = GraphView(g, directed=False)
    vs = g.get_vertices()
    idx = np.full(g.num_vertices(True), -1, dtype="int64")
    idx[vs] = np.arange(len(vs))
    es = np.ascontiguousarray(idx[g.get_edges()[:, :2]], dtype="int64")
    return vs, es.reshape(-1, 2)

def _tree_from_parents(parent):
    t = Graph(directed=True)
    t.add_vertex(len(parent))
    parent = np.asarray(parent, dtype="int64")
    ch = np.flatnonzero(parent >= 0)
    t.add_edge_list(np.stack([parent[ch], ch], axis=1), parallel=False)
    return t

def _parents_from_tree(t):
    parent = np.full(t.num_vertices(), -1, dtype="int64")
    es = t.get_edges()
    parent[es[:, 1]] = es[:, 0]
    return parent

[docs] def hrg_fit(g, niter=1000, start=None, beta=1.): r"""Fit a hierarchical random graph to a graph. Parameters ---------- g : :class:`~graph_tool.Graph` Graph to be used. Edge directions, self-loops, and parallel edges are ignored. niter : ``int`` (optional, default: ``1000``) Number of sweeps of the Markov chain, each with :math:`V - 1` steps. start : :class:`~graph_tool.Graph` (optional, default: ``None``) Initial dendrogram, as returned by this function. If not given, a random one is used. beta : ``float`` (optional, default: ``1.``) Inverse temperature of the Markov chain. Returns ------- tree : :class:`~graph_tool.Graph` The dendrogram of largest likelihood found, as a directed tree with :math:`2V - 1` vertices, whose leaves :math:`0, \dots, V - 1` are the vertices of ``g`` (in the order of :meth:`~graph_tool.Graph.get_vertices`), and whose edges point from parents to children. p : :class:`~graph_tool.VertexPropertyMap` Connection probability of every internal vertex of the tree (zero for the leaves). L : ``float`` Log-likelihood of the dendrogram. See Also -------- hrg_predict: Prediction of missing edges with the hierarchical random graph hrg_consensus: Consensus tree of the hierarchical random graph hrg_generate: Sampling of graphs from a hierarchical random graph NestedBlockState: Nested stochastic block model Notes ----- In the hierarchical random graph of Clauset, Moore, and Newman [clauset-hierarchical-2008]_, every pair of vertices is connected independently with the probability :math:`p_r` of their lowest common ancestor :math:`r` in a binary `dendrogram <https://en.wikipedia.org/wiki/Dendrogram>`_. With the maximum likelihood :math:`p_r = E_r / (L_rR_r)`, where :math:`E_r` is the number of edges between the left and right subtrees of :math:`r`, which have :math:`L_r` and :math:`R_r` leaves, the log-likelihood is .. math:: \ln\mathcal{L} = \sum_r \left[E_r\ln p_r + (L_rR_r - E_r)\ln(1 - p_r)\right], with :math:`0\ln 0 = 0`, where the sum runs over the :math:`V - 1` internal nodes. Dendrograms are sampled with probability proportional to :math:`\mathcal{L}^\beta` by the `Markov chain Monte Carlo <https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo>`_ algorithm of the paper, which rearranges the three subtrees below an internal node and its internal child. In every step, an internal node :math:`r` and one of its two children :math:`s` are chosen uniformly at random (repeating the choice until :math:`s` is an internal node); if :math:`u` and :math:`v` are the children of :math:`s` and :math:`t` is the other child of :math:`r`, one of the two other arrangements, in which :math:`s` has the children :math:`(u, t)` and :math:`r` the children :math:`(s, v)`, or :math:`s` has :math:`(v, t)` and :math:`r` has :math:`(s, u)`, is proposed with equal probability, and accepted with probability :math:`\min(1, e^{\beta\Delta\ln\mathcal{L}})`. The initial dendrogram, if ``start`` is not given, is obtained by merging random pairs of subtrees, starting from the single vertices, until one tree remains. The dendrogram of largest likelihood visited is returned. Each step takes time proportional to the size of the rearranged subtrees times their degrees. This is a descriptive model with a single, non-nested level of hierarchy per split; inference of hierarchical structure with the nested stochastic block model (see :func:`~graph_tool.inference.minimize_nested_blockmodel_dl`) is usually preferable. Examples -------- .. testsetup:: hrg gt.seed_rng(42) .. doctest:: hrg >>> g = gt.collection.data["karate"] >>> tree, p, L = gt.hrg_fit(g, niter=500) >>> print(tree.num_vertices(), L) 67 -87.2... The dendrogram, shown in the figure below, can be drawn with :func:`~graph_tool.draw.tree_layout`, starting from its root, as follows: .. doctest:: hrg >>> from matplotlib.colors import LinearSegmentedColormap >>> cmap = LinearSegmentedColormap.from_list("p", ["#d9d9d9", ... "#ed6a6b"]) >>> leaf = tree.get_out_degrees(tree.get_vertices()) == 0 >>> vs = tree.get_vertices() >>> root = np.flatnonzero(tree.get_in_degrees(vs) == 0)[0] >>> shape = tree.new_vp("string", ... vals=np.where(leaf, "square", "circle")) >>> label = tree.new_vp("string", vals=[str(v) if l else "" ... for v, l in enumerate(leaf)]) >>> gt.graph_draw(tree, pos=gt.tree_layout(tree, root), ... vertex_fill_color=p, vcmap=cmap, vertex_shape=shape, ... vertex_text=label, vertex_font_size=8, ... edge_end_marker="none", output_size=(600, 500), ... output="hrg-fit-karate.pdf") <...> .. testcleanup:: hrg conv_png("hrg-fit-karate.pdf") .. figure:: hrg-fit-karate.png :align: center :width: 80% Dendrogram of the hierarchical random graph fitted to the karate club network, with the root at the top. The leaves (squares) are labeled with the vertex indices, and the internal vertices are colored by their connection probabilities :math:`p_r`, from gray (zero) to red (the largest value). References ---------- .. [clauset-hierarchical-2008] Aaron Clauset, Cristopher Moore and M. E. J. Newman, "Hierarchical structure and the prediction of missing links in networks", Nature 453, 98-101 (2008), :DOI:`10.1038/nature06830`, :arxiv:`0811.0484` """ vs, es = _hrg_input(g) n = len(vs) if n < 2: raise ValueError("The graph must have at least two vertices.") st = np.zeros(0, dtype="int64") if start is None else \ _parents_from_tree(start) parent, L = libinference.hrg_fit(n, es, st, int(niter), float(beta), _get_rng()) tree = _tree_from_parents(parent) probs, L2 = libinference.hrg_probs(n, es, np.asarray(parent)) p = tree.new_vp("double", vals=probs) return tree, p, L
[docs] def hrg_predict(g, vertex_pairs=None, niter=100, nsamples=100, burnin=None, start=None): r"""Predict missing edges with the hierarchical random graph. Parameters ---------- g : :class:`~graph_tool.Graph` Graph to be used. Edge directions, self-loops, and parallel edges are ignored. vertex_pairs : iterable of pairs of ``int`` (optional, default: ``None``) The pairs of vertices to score. If not given, all non-adjacent pairs are scored and returned in decreasing order of probability. niter : ``int`` (optional, default: ``100``) Number of sweeps between samples. nsamples : ``int`` (optional, default: ``100``) Number of sampled dendrograms. burnin : ``int`` (optional, default: ``None``) Number of initial sweeps discarded; if not given, ``10 * niter``. start : :class:`~graph_tool.Graph` (optional, default: ``None``) Initial dendrogram (see :func:`~graph_tool.inference.hrg_fit`). Returns ------- pairs : :class:`numpy.ndarray` The scored pairs (only if ``vertex_pairs`` is ``None``). prob : :class:`numpy.ndarray` The average connection probability of every pair. See Also -------- hrg_fit: Fit of a hierarchical random graph MeasuredBlockState: Network reconstruction from noisy measurements graph_tool.structure.vertex_similarity: Similarity between pairs of vertices Notes ----- The dendrograms :math:`T_1, \dots, T_S` are sampled from the posterior distribution, proportional to the likelihood :math:`\mathcal{L}` given in :func:`~graph_tool.inference.hrg_fit`, with the Markov chain of that function at :math:`\beta = 1`, one every ``niter`` sweeps after ``burnin`` sweeps, where :math:`S` is ``nsamples``, and the probability of a pair :math:`(i, j)` is averaged over them [clauset-hierarchical-2008]_, .. math:: \hat p_{ij} = \frac{1}{S}\sum_{s=1}^S p^{(s)}_{r_s(i,j)}, where :math:`r_s(i,j)` is the `lowest common ancestor <https://en.wikipedia.org/wiki/Lowest_common_ancestor>`_ of :math:`i` and :math:`j` in :math:`T_s` and :math:`p^{(s)}_r = E_r/(L_rR_r)` its maximum likelihood connection probability. Scoring all non-adjacent pairs takes memory :math:`O(V^2)`. A principled alternative is the edge prediction with the stochastic block model described in the inference documentation. Examples -------- .. testsetup:: hrg_predict gt.seed_rng(42) .. doctest:: hrg_predict >>> g = gt.collection.data["karate"] >>> pairs, prob = gt.hrg_predict(g) >>> print(len(pairs), prob[0] >= prob[-1]) 483 True The ten most probable missing edges, shown in the figure below, can be drawn by adding them to a copy of the graph, as follows: .. doctest:: hrg_predict >>> h = g.copy() >>> new = h.new_ep("bool") >>> h.add_edge_list(np.column_stack((pairs[:10], np.ones(10))), ... eprops=[new]) >>> color = h.new_ep("string", ... vals=np.where(new.a, "#e41a1c", "#bbbbbb")) >>> width = h.new_ep("double", vals=np.where(new.a, 2.5, 1)) >>> gt.graph_draw(h, pos=g.vp.pos, vertex_fill_color="#cccccc", ... edge_color=color, edge_pen_width=width, ... output="hrg-predict-karate.pdf") <...> .. testcleanup:: hrg_predict conv_png("hrg-predict-karate.pdf") .. figure:: hrg-predict-karate.png :align: center :width: 60% Karate club network, with the ten non-adjacent pairs of vertices of largest predicted probability drawn as red edges. References ---------- .. [clauset-hierarchical-2008] Aaron Clauset, Cristopher Moore and M. E. J. Newman, "Hierarchical structure and the prediction of missing links in networks", Nature 453, 98-101 (2008), :DOI:`10.1038/nature06830`, :arxiv:`0811.0484` """ vs, es = _hrg_input(g) n = len(vs) if vertex_pairs is None: pairs = np.zeros((0, 2), dtype="int64") else: idx = np.full(g.num_vertices(True), -1, dtype="int64") idx[vs] = np.arange(n) pairs = np.asarray(vertex_pairs, dtype="int64").reshape(-1, 2) if pairs.size > 0 and (pairs.min() < 0 or pairs.max() >= g.num_vertices(True)): raise ValueError("invalid vertex in 'vertex_pairs'.") pairs = idx[pairs] if pairs.size > 0 and pairs.min() < 0: raise ValueError("invalid vertex in 'vertex_pairs'.") if burnin is None: burnin = 10 * niter st = np.zeros(0, dtype="int64") if start is None else \ _parents_from_tree(start) pairs, prob = libinference.hrg_predict(n, es, st, int(burnin), int(niter), int(nsamples), np.ascontiguousarray(pairs), vertex_pairs is None, _get_rng()) if vertex_pairs is not None: return prob return vs[pairs], prob
[docs] def hrg_consensus(g, niter=100, nsamples=100, burnin=None, start=None): r"""Return the majority consensus tree of the dendrograms of the hierarchical random graph. Parameters ---------- g : :class:`~graph_tool.Graph` Graph to be used. Edge directions, self-loops, and parallel edges are ignored. niter : ``int`` (optional, default: ``100``) Number of sweeps between samples. nsamples : ``int`` (optional, default: ``100``) Number of sampled dendrograms. burnin : ``int`` (optional, default: ``None``) Number of initial sweeps discarded; if not given, ``10 * niter``. start : :class:`~graph_tool.Graph` (optional, default: ``None``) Initial dendrogram (see :func:`~graph_tool.inference.hrg_fit`). Returns ------- tree : :class:`~graph_tool.Graph` The consensus tree, directed from parents to children, whose leaves :math:`0, \dots, V-1` are the vertices of ``g`` (in the order of :meth:`~graph_tool.Graph.get_vertices`) and whose internal vertices may have more than two children. freq : :class:`~graph_tool.VertexPropertyMap` Fraction of the samples in which the cluster of leaves of every internal vertex appears (one for the leaves and the root). See Also -------- hrg_fit: Fit of a hierarchical random graph hrg_predict: Prediction of missing edges with the hierarchical random graph get_hierarchy_tree: Hierarchy tree of a nested stochastic block model Notes ----- The dendrograms are sampled as in :func:`~graph_tool.inference.hrg_predict`, and the clusters (sets of leaves below an internal node) that appear in more than half of the sampled `dendrograms <https://en.wikipedia.org/wiki/Dendrogram>`_ are mutually compatible, and form the majority consensus tree [clauset-hierarchical-2008]_: every such cluster becomes an internal vertex, whose parent is the smallest of these clusters that contains it, and every leaf is attached to the smallest cluster that contains it. Examples -------- .. testsetup:: hrg_consensus gt.seed_rng(42) .. doctest:: hrg_consensus >>> g = gt.collection.data["karate"] >>> tree, freq = gt.hrg_consensus(g) >>> print(tree.num_vertices() > g.num_vertices()) True The consensus tree, shown in the figure below, can be drawn with :func:`~graph_tool.draw.tree_layout`, starting from its root, as follows: .. doctest:: hrg_consensus >>> from matplotlib.colors import LinearSegmentedColormap >>> cmap = LinearSegmentedColormap.from_list("f", ["#d9d9d9", ... "#ed6a6b"]) >>> leaf = tree.get_out_degrees(tree.get_vertices()) == 0 >>> vs = tree.get_vertices() >>> root = np.flatnonzero(tree.get_in_degrees(vs) == 0)[0] >>> shape = tree.new_vp("string", ... vals=np.where(leaf, "square", "circle")) >>> label = tree.new_vp("string", vals=[str(v) if l else "" ... for v, l in enumerate(leaf)]) >>> gt.graph_draw(tree, pos=gt.tree_layout(tree, root), ... vertex_fill_color=freq, vcmap=cmap, ... vertex_shape=shape, vertex_text=label, ... vertex_font_size=8, edge_end_marker="none", ... output_size=(700, 300), ... output="hrg-consensus-karate.pdf") <...> .. testcleanup:: hrg_consensus conv_png("hrg-consensus-karate.pdf") .. figure:: hrg-consensus-karate.png :align: center :width: 90% Majority consensus tree of the dendrograms of the hierarchical random graph sampled for the karate club network, with the root at the top. The leaves (squares) are labeled with the vertex indices, and the vertices are colored by the fraction of the samples in which their clusters appear, from gray (the smallest value) to red (one). References ---------- .. [clauset-hierarchical-2008] Aaron Clauset, Cristopher Moore and M. E. J. Newman, "Hierarchical structure and the prediction of missing links in networks", Nature 453, 98-101 (2008), :DOI:`10.1038/nature06830`, :arxiv:`0811.0484` """ vs, es = _hrg_input(g) n = len(vs) if burnin is None: burnin = 10 * niter st = np.zeros(0, dtype="int64") if start is None else \ _parents_from_tree(start) parent, freq = libinference.hrg_consensus(n, es, st, int(burnin), int(niter), int(nsamples), _get_rng()) t = _tree_from_parents(parent) return t, t.new_vp("double", vals=freq)
[docs] def hrg_generate(tree, p): r"""Sample a graph from a hierarchical random graph. Parameters ---------- tree : :class:`~graph_tool.Graph` Binary dendrogram as returned by :func:`~graph_tool.inference.hrg_fit`. p : :class:`~graph_tool.VertexPropertyMap` Connection probability of every internal vertex. Returns ------- g : :class:`~graph_tool.Graph` Undirected graph whose vertices are the leaves of the tree. See Also -------- hrg_fit: Fit of a hierarchical random graph graph_tool.generation.generate_sbm: Graphs from the stochastic block model Notes ----- Every pair of leaves is connected independently with the probability of their `lowest common ancestor <https://en.wikipedia.org/wiki/Lowest_common_ancestor>`_ [clauset-hierarchical-2008]_. The pairs of each internal vertex are sampled with geometric skips, in time :math:`O(V + E)` plus the time to list the leaves of every subtree, :math:`O(V\log V)` for balanced trees and :math:`O(V^2)` in the worst case. Examples -------- .. testsetup:: hrg_generate gt.seed_rng(42) .. doctest:: hrg_generate >>> g = gt.collection.data["karate"] >>> tree, p, L = gt.hrg_fit(g, niter=500) >>> h = gt.hrg_generate(tree, p) >>> print(h.num_vertices()) 34 References ---------- .. [clauset-hierarchical-2008] Aaron Clauset, Cristopher Moore and M. E. J. Newman, "Hierarchical structure and the prediction of missing links in networks", Nature 453, 98-101 (2008), :DOI:`10.1038/nature06830`, :arxiv:`0811.0484` """ parent = _parents_from_tree(tree) n = (len(parent) + 1) // 2 es = libinference.hrg_generate(parent, np.ascontiguousarray(p.a, dtype="double"), _get_rng()) g = Graph(directed=False) g.add_vertex(n) g.add_edge_list(np.asarray(es, dtype="int64").reshape(-1, 2), parallel=False) return g