diff git a/doc/conf.py b/doc/conf.py
index 21cb19980309f49a1d6d4989b364aed51e910f1c..804cdffd508719cca4abc18488d86851ee345edd 100644
 a/doc/conf.py
+++ b/doc/conf.py
@@ 83,6 +83,8 @@ release = gt_version.split()[0]
# for source files.
exclude_trees = ['.build']
+exclude_patterns = ['**/_*.rst']
+
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
diff git a/doc/demos/inference/_background.rst b/doc/demos/inference/_background.rst
new file mode 100644
index 0000000000000000000000000000000000000000..f5279c0fd448fe3b8abe3c3effd36a6f7312be49
 /dev/null
+++ b/doc/demos/inference/_background.rst
@@ 0,0 +1,214 @@
+Background: Nonparametric statistical inference
+
+
+A common task when analyzing networks is to characterize their
+structures in simple terms, often by dividing the nodes into modules or
+`"communities" `__.
+
+A principled approach to perform this task is to formulate `generative
+models `_ that include
+the idea of "modules" in their descriptions, which then can be detected
+by `inferring `_
+the model parameters from data. More precisely, given the partition
+:math:`\boldsymbol b = \{b_i\}` of the network into :math:`B` groups,
+where :math:`b_i\in[0,B1]` is the group membership of node :math:`i`,
+we define a model that generates a network :math:`\boldsymbol G` with a
+probability
+
+.. math::
+ :label: modellikelihood
+
+ P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)
+
+where :math:`\boldsymbol\theta` are additional model parameters that
+control how the node partition affects the structure of the
+network. Therefore, if we observe a network :math:`\boldsymbol G`, the
+likelihood that it was generated by a given partition :math:`\boldsymbol
+b` is obtained via the `Bayesian
+`_ posterior probability
+
+.. math::
+ :label: modelposteriorsum
+
+ P(\boldsymbol b  \boldsymbol G) = \frac{\sum_{\boldsymbol\theta}P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)}{P(\boldsymbol G)}
+
+where :math:`P(\boldsymbol\theta, \boldsymbol b)` is the `prior
+probability `_ of the
+model parameters, and
+
+.. math::
+ :label: modelevidence
+
+ P(\boldsymbol G) = \sum_{\boldsymbol\theta,\boldsymbol b}P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)
+
+is called the `evidence`, and corresponds to the total probability of
+the data summed over all model parameters. The particular types of model
+that will be considered here have "hard constraints", such that there is
+only one choice for the remaining parameters :math:`\boldsymbol\theta`
+that is compatible with the generated network, such that
+Eq. :eq:`modelposteriorsum` simplifies to
+
+.. math::
+ :label: modelposterior
+
+ P(\boldsymbol b  \boldsymbol G) = \frac{P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)}{P(\boldsymbol G)}
+
+with :math:`\boldsymbol\theta` above being the only choice compatible with
+:math:`\boldsymbol G` and :math:`\boldsymbol b`. The inference procedures considered
+here will consist in either finding a network partition that maximizes
+Eq. :eq:`modelposterior`, or sampling different partitions according
+its posterior probability.
+
+As we will show below, this approach also enables the comparison of
+`different` models according to statistical evidence (a.k.a. `model
+selection`).
+
+Minimum description length (MDL)
+++++++++++++++++++++++++++++++++
+
+We note that Eq. :eq:`modelposterior` can be written as
+
+.. math::
+
+ P(\boldsymbol b  \boldsymbol G) = \frac{\exp(\Sigma)}{P(\boldsymbol G)}
+
+where
+
+.. math::
+ :label: modeldl
+
+ \Sigma = \ln P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)  \ln P(\boldsymbol\theta, \boldsymbol b)
+
+is called the **description length** of the network :math:`\boldsymbol
+G`. It measures the amount of `information
+`_ required to
+describe the data, if we `encode
+`_ it using the
+particular parametrization of the generative model given by
+:math:`\boldsymbol\theta` and :math:`\boldsymbol b`, as well as the
+parameters themselves. Therefore, if we choose to maximize the posterior
+distribution of Eq. :eq:`modelposterior` it will be fully equivalent to
+the socalled `minimum description length
+`_
+method. This approach corresponds to an implementation of `Occam's razor
+`_, where the `simplest`
+model is selected, among all possibilities with the same explanatory
+power. The selection is based on the statistical evidence available, and
+therefore will not `overfit
+`_, i.e. mistake stochastic
+fluctuations for actual structure. In particular this means that we will
+not find modules in networks if they could have arisen simply because of
+stochastic fluctuations, as they do in fully random graphs
+[guimeramodularity2004]_.
+
+The stochastic block model (SBM)
+
+
+The `stochastic block model
+`_ is arguably
+the simplest generative process based on the notion of groups of
+nodes [hollandstochastic1983]_. The `microcanonical
+`_ formulation
+[peixotononparametric2017]_ of the basic or "traditional" version takes
+as parameters the partition of the nodes into groups
+:math:`\boldsymbol b` and a :math:`B\times B` matrix of edge counts
+:math:`\boldsymbol e`, where :math:`e_{rs}` is the number of edges
+between groups :math:`r` and :math:`s`. Given these constraints, the
+edges are then placed randomly. Hence, nodes that belong to the same
+group possess the same probability of being connected with other
+nodes of the network.
+
+An example of a possible parametrization is given in the following
+figure.
+
+.. testcode:: sbmexample
+ :hide:
+
+ import os
+ try:
+ os.chdir("demos/inference")
+ except FileNotFoundError:
+ pass
+
+ g = gt.load_graph("blockmodelexample.gt.gz")
+ gt.graph_draw(g, pos=g.vp.pos, vertex_size=10, vertex_fill_color=g.vp.bo,
+ vertex_color="#333333",
+ edge_gradient=g.new_ep("vector", val=[0]),
+ output="sbmexample.svg")
+
+ ers = g.gp.w
+
+ from pylab import *
+ figure()
+ matshow(log(ers))
+ xlabel("Group $r$")
+ ylabel("Group $s$")
+ gca().xaxis.set_label_position("top")
+ savefig("sbmexampleers.svg")
+
+.. table::
+ :class: figure
+
+ +++
+ .. figure:: sbmexampleers.svg .. figure:: sbmexample.svg 
+  :width: 300px  :width: 300px 
+  :align: center  :align: center 
+   
+  Matrix of edge counts  Generated network. 
+  :math:`\boldsymbol e` between  
+  groups.  
+ +++
+
+.. note::
+
+ We emphasize that no constraints are imposed on what `kind` of
+ modular structure is allowed, as the matrix of edge counts :math:`e`
+ is unconstrained. Hence, we can detect the putatively typical pattern
+ of `"community structure"
+ `_, i.e. when
+ nodes are connected mostly to other nodes of the same group, if it
+ happens to be the most likely network description, but we can also
+ detect a large multiplicity of other patterns, such as `bipartiteness
+ `_, coreperiphery,
+ and many others, all under the same inference framework.
+
+
+Although quite general, the traditional model assumes that the edges are
+placed randomly inside each group, and because of this the nodes that
+belong to the same group tend to have very similar degrees. As it turns
+out, this is often a poor model for many networks, which possess highly
+heterogeneous degree distributions. A better model for such networks is
+called the `degreecorrected` stochastic block model
+[karrerstochastic2011]_, and it is defined just like the traditional
+model, with the addition of the degree sequence :math:`\boldsymbol k =
+\{k_i\}` of the graph as an additional set of parameters (assuming again
+a microcanonical formulation [peixotononparametric2017]_).
+
+
+The nested stochastic block model
++++++++++++++++++++++++++++++++++
+
+The regular SBM has a drawback when applied to large networks. Namely,
+it cannot be used to find relatively small groups, as the maximum number
+of groups that can be found scales as
+:math:`B_{\text{max}}=O(\sqrt{N})`, where :math:`N` is the number of
+nodes in the network, if Bayesian inference is performed
+[peixotoparsimonious2013]_. In order to circumvent this, we need to
+replace the noninformative priors used by a hierarchy of priors and
+hyperpriors, which amounts to a `nested SBM`, where the groups
+themselves are clustered into groups, and the matrix :math:`e` of edge
+counts are generated from another SBM, and so on recursively
+[peixotohierarchical2014]_, as illustrated below.
+
+.. figure:: nesteddiagram.*
+ :width: 400px
+ :align: center
+
+ Example of a nested SBM with three levels.
+
+With this model, the maximum number of groups that can be inferred
+scales as :math:`B_{\text{max}}=O(N/\log(N))`. In addition to being able
+to find small groups in large networks, this model also provides a
+multilevel hierarchical description of the network. With such a
+description, we can uncover structural patterns at multiple scales,
+representing different levels of coarsegraining.
diff git a/doc/demos/inference/_edge_weights.rst b/doc/demos/inference/_edge_weights.rst
new file mode 100644
index 0000000000000000000000000000000000000000..90c8495a8c58463713fc0f3317d7c7f82fcd2bdd
 /dev/null
+++ b/doc/demos/inference/_edge_weights.rst
@@ 0,0 +1,273 @@
+.. _weights:
+
+Edge weights and covariates
+
+
+Very often networks cannot be completely represented by simple graphs,
+but instead have arbitrary "weights" :math:`x_{ij}` on the edges. Edge
+weights can be continuous or discrete numbers, and either strictly
+positive or positive or negative, depending on context. The SBM can be
+extended to cover these cases by treating edge weights as covariates
+that are sampled from some distribution conditioned on the node
+partition [aicherlearning2015]_ [peixotoweighted2017]_, i.e.
+
+.. math::
+
+ P(\boldsymbol x,\boldsymbol G\boldsymbol b) =
+ P(\boldsymbol x\boldsymbol G,\boldsymbol b) P(\boldsymbol G\boldsymbol b),
+
+where :math:`P(\boldsymbol G\boldsymbol b)` is the likelihood of the
+unweighted SBM described previously, and :math:`P(\boldsymbol
+x\boldsymbol G,\boldsymbol b)` is the integrated likelihood of the edge
+weights
+
+.. math::
+
+ P(\boldsymbol x\boldsymbol G,\boldsymbol b) =
+ \prod_{r\le s}\int P({\boldsymbol x}_{rs}\gamma)P(\gamma)\,\mathrm{d}\gamma,
+
+where :math:`P({\boldsymbol x}_{rs}\gamma)` is some model for the weights
+:math:`{\boldsymbol x}_{rs}` between groups :math:`(r,s)`, conditioned on
+some parameter :math:`\gamma`, sampled from its prior
+:math:`P(\gamma)`. A hierarchical version of the model can also be
+implemented by replacing this prior by a nested sequence of priors and
+hyperpriors, as described in [peixotoweighted2017]_. The posterior
+partition distribution is then simply
+
+.. math::
+
+ P(\boldsymbol b  \boldsymbol G,\boldsymbol x) =
+ \frac{P(\boldsymbol x\boldsymbol G,\boldsymbol b) P(\boldsymbol G\boldsymbol b)
+ P(\boldsymbol b)}{P(\boldsymbol G,\boldsymbol x)},
+
+which can be sampled from, or maximized, just like with the unweighted
+case, but will use the information on the weights to guide the partitions.
+
+A variety of weight models is supported, reflecting different kinds of
+edge covariates:
+
+.. csvtable::
+ :header: "Name", "Domain", "Bounds", "Shape"
+ :widths: 10, 5, 5, 5
+ :delim: 
+ :align: center
+
+ ``"realexponential"``  Real :math:`(\mathbb{R})`  :math:`[0,\infty]`  `Exponential `_
+ ``"realnormal"``  Real :math:`(\mathbb{R})`  :math:`[\infty,\infty]`  `Normal `_
+ ``"discretegeometric"``  Natural :math:`(\mathbb{N})`  :math:`[0,\infty]`  `Geometric `_
+ ``"discretebinomial"``  Natural :math:`(\mathbb{N})`  :math:`[0,M]`  `Binomial `_
+ ``"discretepoisson"``  Natural :math:`(\mathbb{N})`  :math:`[0,\infty]`  `Poisson `_
+
+In fact, the actual model implements `microcanonical
+`_ versions of
+these distributions that are asymptotically equivalent, as described in
+[peixotoweighted2017]_. These can be combined with arbitrary weight
+transformations to achieve a large family of associated
+distributions. For example, to use a `lognormal
+`_ weight model
+for positive real weights :math:`\boldsymbol x`, we can use the
+transformation :math:`y_{ij} = \ln x_{ij}` together with the
+``"realnormal"`` model for :math:`\boldsymbol y`. To model weights that
+are positive or negative integers in :math:`\mathbb{Z}`, we could either
+subtract the minimum value, :math:`y_{ij} = x_{ij}  x^*`, with
+:math:`x^*=\operatorname{min}_{ij}x_{ij}`, and use any of the above
+models for nonnegative integers in :math:`\mathbb{N}`, or
+alternatively, consider the sign as an additional covariate,
+i.e. :math:`s_{ij} = [\operatorname{sign}(x_{ij})+1]/2 \in \{0,1\}`,
+using the Binomial distribution with :math:`M=1` (a.k.a. the `Bernoulli
+distribution `_),
+and any of the other discrete distributions for the magnitude,
+:math:`y_{ij} = \operatorname{abs}(x_{ij})`.
+
+The support for weighted networks is activated by passing the parameters
+``recs`` and ``rec_types`` to
+:class:`~graph_tool.inference.blockmodel.BlockState` (or
+:class:`~graph_tool.inference.overlap_blockmodel.OverlapBlockState`),
+that specify the edge covariates (an edge
+:class:`~graph_tool.PropertyMap`) and their types (a string from the
+table above), respectively. Note that these parameters expect *lists*,
+so that multiple edge weights can be used simultaneously.
+
+For example, let us consider a network of suspected terrorists involved
+in the train bombing of Madrid on March 11, 2004
+[hayesconnecting2006]_. An edge indicates that a connection between
+the two persons have been identified, and the weight of the edge (an
+integer in the range :math:`[0,3]`) indicates the "strength" of the
+connection. We can apply the weighted SBM, using a Binomial model for
+the weights, as follows:
+
+
+.. testsetup:: weightedmodel
+
+ import os
+ try:
+ os.chdir("demos/inference")
+ except FileNotFoundError:
+ pass
+ gt.seed_rng(42)
+
+.. testcode:: weightedmodel
+
+ g = gt.collection.konect_data["moreno_train"]
+
+ # This network contains an internal edge property map with name
+ # "weight" that contains the strength of interactions. The values
+ # integers in the range [0, 3].
+
+ state = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[g.ep.weight],
+ rec_types=["discretebinomial"]))
+
+ state.draw(edge_color=g.ep.weight, ecmap=(matplotlib.cm.inferno, .6),
+ eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1),
+ edge_gradient=[], output="morenotrainwsbm.svg")
+
+.. figure:: morenotrainwsbm.*
+ :align: center
+ :width: 350px
+
+ Best fit of the Binomialweighted degreecorrected SBM for a network
+ of terror suspects, using the strength of connection as edge
+ covariates. The edge colors and widths correspond to the strengths.
+
+Model selection
++++++++++++++++
+
+In order to select the best weighted model, we proceed in the same
+manner as described in Sec. :ref:`model_selection`. However, when using
+transformations on continuous weights, we must include the associated
+scaling of the probability density, as described in
+[peixotoweighted2017]_.
+
+For example, consider a `food web
+`_ between species in south
+Florida [ulanowicznetwork2005]_. A directed link exists from species
+:math:`i` to :math:`j` if a energy flow exists between them, and a
+weight :math:`x_{ij}` on this edge indicates the magnitude of the energy
+flow (a positive real value, i.e. :math:`x_{ij}\in [0,\infty]`). One
+possibility, therefore, is to use the ``"realexponential"`` model, as
+follows:
+
+.. testsetup:: foodweb
+
+ import os
+ try:
+ os.chdir("demos/inference")
+ except FileNotFoundError:
+ pass
+ gt.seed_rng(44)
+
+.. testcode:: foodweb
+
+ g = gt.collection.konect_data["foodwebbaywet"]
+
+ # This network contains an internal edge property map with name
+ # "weight" that contains the biomass flow between species. The values
+ # are continuous in the range [0, infinity].
+
+ state = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[g.ep.weight],
+ rec_types=["realexponential"]))
+
+ state.draw(edge_color=gt.prop_to_size(g.ep.weight, power=1, log=True), ecmap=(matplotlib.cm.inferno, .6),
+ eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1, log=True),
+ edge_gradient=[], output="foodwebwsbm.svg")
+
+.. figure:: foodwebwsbm.*
+ :align: center
+ :width: 350px
+
+ Best fit of the exponentialweighted degreecorrected SBM for a food
+ web, using the biomass flow as edge covariates (indicated by the edge
+ colors and widths).
+
+Alternatively, we may consider a transformation of the type
+
+.. math::
+ :label: log_transform
+
+ y_{ij} = \ln x_{ij}
+
+so that :math:`y_{ij} \in [\infty,\infty]`. If we use a model
+``"realnormal"`` for :math:`\boldsymbol y`, it amounts to a `lognormal
+`_ model for
+:math:`\boldsymbol x`. This can be a better choice if the weights are
+distributed across many orders of magnitude, or show multimodality. We
+can fit this alternative model simply by using the transformed weights:
+
+.. testcode:: foodweb
+
+ # Apply the weight transformation
+ y = g.ep.weight.copy()
+ y.a = log(y.a)
+
+ state_ln = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[y],
+ rec_types=["realnormal"]))
+
+ state_ln.draw(edge_color=gt.prop_to_size(g.ep.weight, power=1, log=True), ecmap=(matplotlib.cm.inferno, .6),
+ eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1, log=True),
+ edge_gradient=[], output="foodwebwsbmlognormal.svg")
+
+.. figure:: foodwebwsbmlognormal.*
+ :align: center
+ :width: 350px
+
+ Best fit of the lognormalweighted degreecorrected SBM for a food
+ web, using the biomass flow as edge covariates (indicated by the edge
+ colors and widths).
+
+At this point, we ask ourselves which of the above models yields the
+best fit of the data. This is answered by performing model selection via
+posterior odds ratios just like in Sec. :ref:`model_selection`. However,
+here we need to take into account the scaling of the probability density
+incurred by the variable transformation, i.e.
+
+.. math::
+
+ P(\boldsymbol x  \boldsymbol G, \boldsymbol b) =
+ P(\boldsymbol y(\boldsymbol x)  \boldsymbol G, \boldsymbol b)
+ \prod_{ij}\left[\frac{\mathrm{d}y_{ij}}{\mathrm{d}x_{ij}}(x_{ij})\right]^{A_{ij}}.
+
+In the particular case of Eq. :eq:`log_transform`, we have
+
+.. math::
+
+ \prod_{ij}\left[\frac{\mathrm{d}y_{ij}}{\mathrm{d}x_{ij}}(x_{ij})\right]^{A_{ij}}
+ = \prod_{ij}\frac{1}{x_{ij}^{A_{ij}}}.
+
+Therefore, we can compute the posterior odds ratio between both models as:
+
+.. testcode:: foodweb
+
+ L1 = state.entropy()
+ L2 = state_ln.entropy()  log(g.ep.weight.a).sum()
+
+ print(u"ln \u039b: ", L2  L1)
+
+.. testoutput:: foodweb
+ :options: +NORMALIZE_WHITESPACE
+
+ ln Λ: 70.145685...
+
+A value of :math:`\Lambda \approx \mathrm{e}^{70} \approx 10^{30}` in
+favor the exponential model indicates that the lognormal model does not
+provide a better fit for this particular data. Based on this, we
+conclude that the exponential model should be preferred in this case.
+
+
+Posterior sampling
+++++++++++++++++++
+
+The procedure to sample from the posterior distribution is identical to
+what is described in Sec. :ref:`sampling`, but with the appropriate
+initialization, i.e.
+
+.. testcode:: weightedmodel
+
+ state = gt.BlockState(g, B=20, recs=[g.ep.weight], rec_types=["discretepoisson"])
+
+or for the nested model
+
+.. testcode:: weightedmodel
+
+ state = gt.NestedBlockState(g, bs=[np.random.randint(0, 20, g.num_vertices())] + [zeros(1)] * 10,
+ state_args=dict(recs=[g.ep.weight],
+ rec_types=["discretepoisson"]))
diff git a/doc/demos/inference/_layers.rst b/doc/demos/inference/_layers.rst
new file mode 100644
index 0000000000000000000000000000000000000000..ae106d1ab5a6b649b5743682112df2537971caa3
 /dev/null
+++ b/doc/demos/inference/_layers.rst
@@ 0,0 +1,64 @@
+Layered networks
+
+
+The edges of the network may be distributed in discrete "layers",
+representing distinct types if interactions
+[peixotoinferring2015]_. Extensions to the SBM may be defined for such
+data, and they can be inferred using the exact same interface shown
+above, except one should use the
+:class:`~graph_tool.inference.layered_blockmodel.LayeredBlockState`
+class, instead of
+:class:`~graph_tool.inference.blockmodel.BlockState`. This class takes
+two additional parameters: the ``ec`` parameter, that must correspond to
+an edge :class:`~graph_tool.PropertyMap` with the layer/covariate values
+on the edges, and the Boolean ``layers`` parameter, which if ``True``
+specifies a layered model, otherwise one with categorical edge
+covariates (not to be confused with the weighted models in
+Sec. :ref:`weights`).
+
+If we use :func:`~graph_tool.inference.minimize.minimize_blockmodel_dl`, this can
+be achieved simply by passing the option ``layers=True`` as well as the
+appropriate value of ``state_args``, which will be propagated to
+:class:`~graph_tool.inference.layered_blockmodel.LayeredBlockState`'s constructor.
+
+As an example, let us consider a social network of tribes, where two
+types of interactions were recorded, amounting to either friendship or
+enmity [readcultures1954]_. We may apply the layered model by
+separating these two types of interactions in two layers:
+
+.. testsetup:: layeredmodel
+
+ import os
+ try:
+ os.chdir("demos/inference")
+ except FileNotFoundError:
+ pass
+ gt.seed_rng(42)
+
+.. testcode:: layeredmodel
+
+ g = gt.collection.konect_data["ucidatagama"]
+
+ # The edge types are stored in the edge property map "weights".
+
+ # Note the different meanings of the two 'layers' parameters below: The
+ # first enables the use of LayeredBlockState, and the second selects
+ # the 'edge layers' version (instead of 'edge covariates').
+
+ state = gt.minimize_nested_blockmodel_dl(g, layers=True,
+ state_args=dict(ec=g.ep.weight, layers=True))
+
+ state.draw(edge_color=g.ep.weight, edge_gradient=[],
+ ecmap=(matplotlib.cm.coolwarm_r, .6), edge_pen_width=5,
+ output="tribessbmedgelayers.svg")
+
+.. figure:: tribessbmedgelayers.*
+ :align: center
+ :width: 350px
+
+ Best fit of the degreecorrected SBM with edge layers for a network
+ of tribes, with edge layers shown as colors. The groups show two
+ enemy tribes.
+
+It is possible to perform model averaging of all layered variants
+exactly like for the regular SBMs as was shown above.
diff git a/doc/demos/inference/_minimization.rst b/doc/demos/inference/_minimization.rst
new file mode 100644
index 0000000000000000000000000000000000000000..2272df8db174e034c743ddf6faea73ff7079d7d2
 /dev/null
+++ b/doc/demos/inference/_minimization.rst
@@ 0,0 +1,226 @@
+Inferring the best partition
+
+
+The simplest and most efficient approach is to find the best
+partition of the network by maximizing Eq. :eq:`modelposterior`
+according to some version of the model. This is obtained via the
+functions :func:`~graph_tool.inference.minimize.minimize_blockmodel_dl` or
+:func:`~graph_tool.inference.minimize.minimize_nested_blockmodel_dl`, which
+employs an agglomerative multilevel `Markov chain Monte Carlo (MCMC)
+`_ algorithm
+[peixotoefficient2014]_.
+
+We focus first on the nonnested model, and we illustrate its use with a
+network of American football teams, which we load from the
+:mod:`~graph_tool.collection` module:
+
+.. testsetup:: football
+
+ import os
+ try:
+ os.chdir("demos/inference")
+ except FileNotFoundError:
+ pass
+ gt.seed_rng(7)
+
+.. testcode:: football
+
+ g = gt.collection.data["football"]
+ print(g)
+
+which yields
+
+.. testoutput:: football
+
+
+
+we then fit the degreecorrected model by calling
+
+.. testcode:: football
+
+ state = gt.minimize_blockmodel_dl(g)
+
+This returns a :class:`~graph_tool.inference.blockmodel.BlockState` object that
+includes the inference results.
+
+.. note::
+
+ The inference algorithm used is stochastic by nature, and may return
+ a different answer each time it is run. This may be due to the fact
+ that there are alternative partitions with similar probabilities, or
+ that the optimum is difficult to find. Note that the inference
+ problem here is, in general, `NPHard
+ `_, hence there is no
+ efficient algorithm that is guaranteed to always find the best
+ answer.
+
+ Because of this, typically one would call the algorithm many times,
+ and select the partition with the largest posterior probability of
+ Eq. :eq:`modelposterior`, or equivalently, the minimum description
+ length of Eq. :eq:`modeldl`. The description length of a fit can be
+ obtained with the :meth:`~graph_tool.inference.blockmodel.BlockState.entropy`
+ method. See also Sec. :ref:`sec_model_selection` below.
+
+
+We may perform a drawing of the partition obtained via the
+:mod:`~graph_tool.inference.blockmodel.BlockState.draw` method, that functions as a
+convenience wrapper to the :func:`~graph_tool.draw.graph_draw` function
+
+.. testcode:: football
+
+ state.draw(pos=g.vp.pos, output="footballsbmfit.svg")
+
+which yields the following image.
+
+.. figure:: footballsbmfit.*
+ :align: center
+ :width: 400px
+
+ Stochastic block model inference of a network of American college
+ football teams. The colors correspond to inferred group membership of
+ the nodes.
+
+We can obtain the group memberships as a
+:class:`~graph_tool.PropertyMap` on the vertices via the
+:mod:`~graph_tool.inference.blockmodel.BlockState.get_blocks` method:
+
+.. testcode:: football
+
+ b = state.get_blocks()
+ r = b[10] # group membership of vertex 10
+ print(r)
+
+which yields:
+
+.. testoutput:: football
+
+ 3
+
+We may also access the matrix of edge counts between groups via
+:mod:`~graph_tool.inference.blockmodel.BlockState.get_matrix`
+
+.. testcode:: football
+
+ e = state.get_matrix()
+
+ matshow(e.todense())
+ savefig("footballedgecounts.svg")
+
+.. figure:: footballedgecounts.*
+ :align: center
+
+ Matrix of edge counts between groups.
+
+We may obtain the same matrix of edge counts as a graph, which has
+internal edge and vertex property maps with the edge and vertex counts,
+respectively:
+
+.. testcode:: football
+
+ bg = state.get_bg()
+ ers = state.mrs # edge counts
+ nr = state.wr # node counts
+
+.. _sec_model_selection:
+
+Hierarchical partitions
++++++++++++++++++++++++
+
+The inference of the nested family of SBMs is done in a similar manner,
+but we must use instead the
+:func:`~graph_tool.inference.minimize.minimize_nested_blockmodel_dl` function. We
+illustrate its use with the neural network of the `C. elegans
+`_ worm:
+
+.. testsetup:: celegans
+
+ gt.seed_rng(47)
+
+.. testcode:: celegans
+
+ g = gt.collection.data["celegansneural"]
+ print(g)
+
+which has 297 vertices and 2359 edges.
+
+.. testoutput:: celegans
+
+
+
+A hierarchical fit of the degreecorrected model is performed as follows.
+
+.. testcode:: celegans
+
+ state = gt.minimize_nested_blockmodel_dl(g)
+
+The object returned is an instance of a
+:class:`~graph_tool.inference.nested_blockmodel.NestedBlockState` class, which
+encapsulates the results. We can again draw the resulting hierarchical
+clustering using the
+:meth:`~graph_tool.inference.nested_blockmodel.NestedBlockState.draw` method:
+
+.. testcode:: celegans
+
+ state.draw(output="celeganshsbmfit.svg")
+
+.. figure:: celeganshsbmfit.*
+ :align: center
+
+ Most likely hierarchical partition of the neural network of
+ the *C. elegans* worm according to the nested degreecorrected SBM.
+
+.. note::
+
+ If the ``output`` parameter to
+ :meth:`~graph_tool.inference.nested_blockmodel.NestedBlockState.draw` is omitted, an
+ interactive visualization is performed, where the user can reorder
+ the hierarchy nodes using the mouse and pressing the ``r`` key.
+
+A summary of the inferred hierarchy can be obtained with the
+:meth:`~graph_tool.inference.nested_blockmodel.NestedBlockState.print_summary` method,
+which shows the number of nodes and groups in all levels:
+
+.. testcode:: celegans
+
+ state.print_summary()
+
+.. testoutput:: celegans
+
+ l: 0, N: 297, B: 17
+ l: 1, N: 17, B: 9
+ l: 2, N: 9, B: 3
+ l: 3, N: 3, B: 1
+
+The hierarchical levels themselves are represented by individual
+:meth:`~graph_tool.inference.blockmodel.BlockState` instances obtained via the
+:meth:`~graph_tool.inference.nested_blockmodel.NestedBlockState.get_levels()` method:
+
+.. testcode:: celegans
+
+ levels = state.get_levels()
+ for s in levels:
+ print(s)
+
+.. testoutput:: celegans
+
+ , at 0x...>
+ , at 0x...>
+ , at 0x...>
+ , at 0x...>
+
+This means that we can inspect the hierarchical partition just as before:
+
+.. testcode:: celegans
+
+ r = levels[0].get_blocks()[46] # group membership of node 46 in level 0
+ print(r)
+ r = levels[0].get_blocks()[r] # group membership of node 46 in level 1
+ print(r)
+ r = levels[0].get_blocks()[r] # group membership of node 46 in level 2
+ print(r)
+
+.. testoutput:: celegans
+
+ 7
+ 0
+ 0
diff git a/doc/demos/inference/_model_class_selection.rst b/doc/demos/inference/_model_class_selection.rst
new file mode 100644
index 0000000000000000000000000000000000000000..41309a9d22815477f9a4e3fb9995b88e7d83a257
 /dev/null
+++ b/doc/demos/inference/_model_class_selection.rst
@@ 0,0 +1,230 @@
+Model class selection
++++++++++++++++++++++
+
+When averaging over partitions, we may be interested in evaluating which
+**model class** provides a better fit of the data, considering all
+possible parameter choices. This is done by evaluating the model
+evidence summed over all possible partitions [peixotononparametric2017]_:
+
+.. math::
+
+ P(\boldsymbol G) = \sum_{\boldsymbol\theta,\boldsymbol b}P(\boldsymbol G,\boldsymbol\theta, \boldsymbol b) = \sum_{\boldsymbol b}P(\boldsymbol G,\boldsymbol b).
+
+This quantity is analogous to a `partition function
+`_
+in statistical physics, which we can write more conveniently as a
+negative `free energy
+`_ by taking
+its logarithm
+
+.. math::
+ :label: freeenergy
+
+ \ln P(\boldsymbol G) = \underbrace{\sum_{\boldsymbol b}q(\boldsymbol b)\ln P(\boldsymbol G,\boldsymbol b)}_{\left<\Sigma\right>}\;
+ \underbrace{ \sum_{\boldsymbol b}q(\boldsymbol b)\ln q(\boldsymbol b)}_{\mathcal{S}}
+
+where
+
+.. math::
+
+ q(\boldsymbol b) = \frac{P(\boldsymbol G,\boldsymbol b)}{\sum_{\boldsymbol b'}P(\boldsymbol G,\boldsymbol b')}
+
+is the posterior probability of partition :math:`\boldsymbol b`. The
+first term of Eq. :eq:`freeenergy` (the "negative energy") is minus the
+average of description length :math:`\left<\Sigma\right>`, weighted
+according to the posterior distribution. The second term
+:math:`\mathcal{S}` is the `entropy
+`_ of the
+posterior distribution, and measures, in a sense, the "quality of fit"
+of the model: If the posterior is very "peaked", i.e. dominated by a
+single partition with a very large probability, the entropy will tend to
+zero. However, if there are many partitions with similar probabilities
+ meaning that there is no single partition that describes the network
+uniquely well  it will take a large value instead.
+
+Since the MCMC algorithm samples partitions from the distribution
+:math:`q(\boldsymbol b)`, it can be used to compute
+:math:`\left<\Sigma\right>` easily, simply by averaging the description
+length values encountered by sampling from the posterior distribution
+many times.
+
+The computation of the posterior entropy :math:`\mathcal{S}`, however,
+is significantly more difficult, since it involves measuring the precise
+value of :math:`q(\boldsymbol b)`. A direct "brute force" computation of
+:math:`\mathcal{S}` is implemented via
+:meth:`~graph_tool.inference.blockmodel.BlockState.collect_partition_histogram` and
+:func:`~graph_tool.inference.blockmodel.microstate_entropy`, however this is only
+feasible for very small networks. For larger networks, we are forced to
+perform approximations. The simplest is a "mean field" one, where we
+assume the posterior factorizes as
+
+.. math::
+
+ q(\boldsymbol b) \approx \prod_i{q_i(b_i)}
+
+where
+
+.. math::
+
+ q_i(r) = P(b_i = r  \boldsymbol G)
+
+is the marginal group membership distribution of node :math:`i`. This
+yields an entropy value given by
+
+.. math::
+
+ S \approx \sum_i\sum_rq_i(r)\ln q_i(r).
+
+This approximation should be seen as an upper bound, since any existing
+correlation between the nodes (which are ignored here) will yield
+smaller entropy values.
+
+A more accurate assumption is called the `Bethe approximation`
+[mezardinformation2009]_, and takes into account the correlation
+between adjacent nodes in the network,
+
+.. math::
+
+ q(\boldsymbol b) \approx \prod_{i`_, :math:`k_i` is the
+degree of node :math:`i`, and
+
+.. math::
+
+ q_{ij}(r, s) = P(b_i = r, b_j = s\boldsymbol G)
+
+is the joint group membership distribution of nodes :math:`i` and
+:math:`j` (a.k.a. the `edge marginals`). This yields an entropy value
+given by
+
+.. math::
+
+ S \approx \sum_{i0` only the meanfield approximation is applicable, since the
+adjacency matrix of the higher layers is not constant. We show below the
+approach for the same network, using the nested model.
+
+
+.. testcode:: modelevidence
+
+ g = gt.collection.data["lesmis"]
+
+ nL = 10
+
+ for deg_corr in [True, False]:
+ state = gt.minimize_nested_blockmodel_dl(g, deg_corr=deg_corr) # Initialize the Markov
+ # chain from the "ground
+ # state"
+ bs = state.get_bs() # Get hierarchical partition.
+ bs += [np.zeros(1)] * (nL  len(bs)) # Augment it to L = 10 with
+ # singlegroup levels.
+
+ state = state.copy(bs=bs, sampling=True)
+
+ dls = [] # description length history
+ vm = [None] * len(state.get_levels()) # vertex marginals
+ em = None # edge marginals
+
+ def collect_marginals(s):
+ global vm, em
+ levels = s.get_levels()
+ vm = [sl.collect_vertex_marginals(vm[l]) for l, sl in enumerate(levels)]
+ em = levels[0].collect_edge_marginals(em)
+ dls.append(s.entropy())
+
+ # Now we collect the marginal distributions for exactly 200,000 sweeps
+ gt.mcmc_equilibrate(state, force_niter=20000, mcmc_args=dict(niter=10),
+ callback=collect_marginals)
+
+ S_mf = [gt.mf_entropy(sl.g, vm[l]) for l, sl in enumerate(state.get_levels())]
+ S_bethe = gt.bethe_entropy(g, em)[0]
+ L = mean(dls)
+
+ print("Model evidence for deg_corr = %s:" % deg_corr,
+ L + sum(S_mf), "(mean field),", L + S_bethe + sum(S_mf[1:]), "(Bethe)")
+
+
+.. testoutput:: modelevidence
+
+ Model evidence for deg_corr = True: 551.228195... (mean field), 740.460493... (Bethe)
+ Model evidence for deg_corr = False: 544.660366... (mean field), 649.135026... (Bethe)
+
+The results are similar: If we consider the most accurate approximation,
+the nondegreecorrected model possesses the largest evidence. Note also
+that we observe a better evidence for the nested models themselves, when
+comparing to the evidences for the nonnested model  which is not
+quite surprising, since the nonnested model is a special case of the
+nested one.
diff git a/doc/demos/inference/_model_selection.rst b/doc/demos/inference/_model_selection.rst
new file mode 100644
index 0000000000000000000000000000000000000000..0488f5c0e2475ae8e94bb550e7487a1e98de4aee
 /dev/null
+++ b/doc/demos/inference/_model_selection.rst
@@ 0,0 +1,89 @@
+.. _model_selection:
+
+Model selection
++++++++++++++++
+
+As mentioned above, one can select the best model according to the
+choice that yields the smallest description length
+[peixotomodel2016]_. For instance, in case of the `C. elegans` network
+we have
+
+.. testsetup:: modelselection
+
+ gt.seed_rng(43)
+
+.. testcode:: modelselection
+
+ g = gt.collection.data["celegansneural"]
+
+ state_ndc = gt.minimize_nested_blockmodel_dl(g, deg_corr=False)
+ state_dc = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
+
+ print("Nondegreecorrected DL:\t", state_ndc.entropy())
+ print("Degreecorrected DL:\t", state_dc.entropy())
+
+.. testoutput:: modelselection
+ :options: +NORMALIZE_WHITESPACE
+
+ Nondegreecorrected DL: 8456.994339...
+ Degreecorrected DL: 8233.850036...
+
+Since it yields the smallest description length, the degreecorrected
+fit should be preferred. The statistical significance of the choice can
+be accessed by inspecting the posterior odds ratio
+[peixotononparametric2017]_
+
+.. math::
+
+ \Lambda &= \frac{P(\boldsymbol b, \mathcal{H}_\text{NDC}  \boldsymbol G)}{P(\boldsymbol b, \mathcal{H}_\text{DC}  \boldsymbol G)} \\
+ &= \frac{P(\boldsymbol G, \boldsymbol b  \mathcal{H}_\text{NDC})}{P(\boldsymbol G, \boldsymbol b  \mathcal{H}_\text{DC})}\times\frac{P(\mathcal{H}_\text{NDC})}{P(\mathcal{H}_\text{DC})} \\
+ &= \exp(\Delta\Sigma)
+
+where :math:`\mathcal{H}_\text{NDC}` and :math:`\mathcal{H}_\text{DC}`
+correspond to the nondegreecorrected and degreecorrected model
+hypotheses (assumed to be equally likely `a priori`), respectively, and
+:math:`\Delta\Sigma` is the difference of the description length of both
+fits. In our particular case, we have
+
+.. testcode:: modelselection
+
+ print(u"ln \u039b: ", state_dc.entropy()  state_ndc.entropy())
+
+.. testoutput:: modelselection
+ :options: +NORMALIZE_WHITESPACE
+
+ ln Λ: 223.144303...
+
+The precise threshold that should be used to decide when to `reject a
+hypothesis `_ is
+subjective and contextdependent, but the value above implies that the
+particular degreecorrected fit is around :math:`\mathrm{e}^{233} \approx 10^{96}`
+times more likely than the nondegree corrected one, and hence it can be
+safely concluded that it provides a substantially better fit.
+
+Although it is often true that the degreecorrected model provides a
+better fit for many empirical networks, there are also exceptions. For
+example, for the American football network above, we have:
+
+.. testcode:: modelselection
+
+ g = gt.collection.data["football"]
+
+ state_ndc = gt.minimize_nested_blockmodel_dl(g, deg_corr=False)
+ state_dc = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
+
+ print("Nondegreecorrected DL:\t", state_ndc.entropy())
+ print("Degreecorrected DL:\t", state_dc.entropy())
+ print(u"ln \u039b:\t\t\t", state_ndc.entropy()  state_dc.entropy())
+
+.. testoutput:: modelselection
+ :options: +NORMALIZE_WHITESPACE
+
+ Nondegreecorrected DL: 1734.814739...
+ Degreecorrected DL: 1780.576716...
+ ln Λ: 45.761977...
+
+Hence, with a posterior odds ratio of :math:`\Lambda \approx \mathrm{e}^{45} \approx
+10^{19}` in favor of the nondegreecorrected model, it seems like the
+degreecorrected variant is an unnecessarily complex description for
+this network.
diff git a/doc/demos/inference/_prediction.rst b/doc/demos/inference/_prediction.rst
new file mode 100644
index 0000000000000000000000000000000000000000..19e788c1fda3c0d2217be7335b48aec003478b19
 /dev/null
+++ b/doc/demos/inference/_prediction.rst
@@ 0,0 +1,152 @@
+Edge prediction as binary classification
+++++++++++++++++++++++++++++++++++++++++
+
+A more traditional approach to the prediction of missing and spurious
+edges formulates it as a supervised `binary classification task
+`__, where the
+edge/nonedge scores are computed by fitting a generative model to the
+observed data, and computing their probabilities under that model
+[clausethierarchical2008]_ [guimeramissing2009]_. In this setting,
+one typically omits any explicit model of the measurement process (hence
+intrinsically assuming it to be uniform), and as a consequence of the
+overall setup, only *relative probabilities* between individual missing
+and spurious edges can be produced, instead of the full posterior
+distribution considered in the last section. Since this limits the
+overall network reconstruction, and does not yields confidence
+intervals, it is a less powerful approach. Nevertheless, it is a popular
+procedure, which can also be performed with graphtool, as we describe
+in the following.
+
+We set up the classification task by dividing the edges/nonedges into
+two sets :math:`\boldsymbol G` and :math:`\delta \boldsymbol G`, where
+the former corresponds to the observed network and the latter either to
+the missing or spurious edges. We may compute the posterior of
+:math:`\delta \boldsymbol G` as [vallescatalaconsistency2017]_
+
+.. math::
+ :label: posteriormissing
+
+ P(\delta \boldsymbol G  \boldsymbol G) \propto
+ \sum_{\boldsymbol b}\frac{P(\boldsymbol G \cup \delta\boldsymbol G \boldsymbol b)}{P(\boldsymbol G \boldsymbol b)}P(\boldsymbol b  \boldsymbol G)
+
+up to a normalization constant [#prediction_posterior]_. Although the
+normalization constant is difficult to obtain in general (since we need
+to perform a sum over all possible spurious/missing edges), the
+numerator of Eq. :eq:`posteriormissing` can be computed by sampling
+partitions from the posterior, and then inserting or deleting edges from
+the graph and computing the new likelihood. This means that we can
+easily compare alternative predictive hypotheses :math:`\{\delta
+\boldsymbol G_i\}` via their likelihood ratios
+
+.. math::
+
+ \lambda_i = \frac{P(\delta \boldsymbol G_i  \boldsymbol G)}{\sum_j P(\delta \boldsymbol G_j  \boldsymbol G)}
+
+which do not depend on the normalization constant.
+
+The values :math:`P(\delta \boldsymbol G  \boldsymbol G, \boldsymbol b)`
+can be computed with
+:meth:`~graph_tool.inference.blockmodel.BlockState.get_edges_prob`. Hence, we can
+compute spurious/missing edge probabilities just as if we were
+collecting marginal distributions when doing model averaging.
+
+Below is an example for predicting the two following edges in the
+football network, using the nested model (for which we need to replace
+:math:`\boldsymbol b` by :math:`\{\boldsymbol b_l\}` in the equations
+above).
+
+.. testcode:: missingedges
+ :hide:
+
+ import os
+ try:
+ os.chdir("demos/inference")
+ except FileNotFoundError:
+ pass
+
+ g = gt.collection.data["football"].copy()
+ color = g.new_vp("string", val="#cccccc")
+ ecolor = g.new_ep("string", val="#cccccc")
+ ewidth = g.new_ep("double", 1)
+ e = g.add_edge(101, 102)
+ ecolor[e] = "#a40000"
+ ewidth[e] = 5
+ e = g.add_edge(17, 56)
+ ecolor[e] = "#a40000"
+ ewidth[e] = 5
+ eorder = g.edge_index.copy("int")
+
+ gt.graph_draw(g, pos=g.vp.pos, vertex_color=color,
+ vertex_fill_color=color, edge_color=ecolor,
+ eorder=eorder, edge_pen_width=ewidth,
+ output="football_missing.svg")
+
+.. figure:: football_missing.*
+ :align: center
+ :width: 350px
+
+ Two nonexisting edges in the football network (in red):
+ :math:`(101,102)` in the middle, and :math:`(17,56)` in the upper
+ right region of the figure.
+
+.. testsetup:: missingedges
+
+ gt.seed_rng(7)
+
+.. testcode:: missingedges
+
+ g = gt.collection.data["football"]
+
+ missing_edges = [(101, 102), (17, 56)]
+
+ L = 10
+
+ state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
+
+ bs = state.get_bs() # Get hierarchical partition.
+ bs += [np.zeros(1)] * (L  len(bs)) # Augment it to L = 10 with
+ # singlegroup levels.
+
+ state = state.copy(bs=bs, sampling=True)
+
+ probs = ([], [])
+
+ def collect_edge_probs(s):
+ p1 = s.get_edges_prob([missing_edges[0]], entropy_args=dict(partition_dl=False))
+ p2 = s.get_edges_prob([missing_edges[1]], entropy_args=dict(partition_dl=False))
+ probs[0].append(p1)
+ probs[1].append(p2)
+
+ # Now we collect the probabilities for exactly 100,000 sweeps
+ gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
+ callback=collect_edge_probs)
+
+
+ def get_avg(p):
+ p = np.array(p)
+ pmax = p.max()
+ p = pmax
+ return pmax + log(exp(p).mean())
+
+ p1 = get_avg(probs[0])
+ p2 = get_avg(probs[1])
+
+ p_sum = get_avg([p1, p2]) + log(2)
+
+ l1 = p1  p_sum
+ l2 = p2  p_sum
+
+ print("likelihoodratio for %s: %g" % (missing_edges[0], exp(l1)))
+ print("likelihoodratio for %s: %g" % (missing_edges[1], exp(l2)))
+
+
+.. testoutput:: missingedges
+
+ likelihoodratio for (101, 102): 0.37...
+ likelihoodratio for (17, 56): 0.62...
+
+From which we can conclude that edge :math:`(17, 56)` is more likely
+than :math:`(101, 102)` to be a missing edge.
+
+The prediction using the nonnested model can be performed in an
+entirely analogous fashion.
diff git a/doc/demos/inference/_reconstruction.rst b/doc/demos/inference/_reconstruction.rst
new file mode 100644
index 0000000000000000000000000000000000000000..6e6d9c5f9992f436eb75099ff106208144caadcc
 /dev/null
+++ b/doc/demos/inference/_reconstruction.rst
@@ 0,0 +1,482 @@
+Network reconstruction
+
+
+An important application of generative models is to be able to
+generalize from observations and make predictions that go beyond what is
+seen in the data. This is particularly useful when the network we
+observe is incomplete, or contains errors, i.e. some of the edges are
+either missing or are outcomes of mistakes in measurement. In this
+situation, we can use statistical inference to reconstruct the original
+network. Following [peixotoreconstructing2018]_, if
+:math:`\boldsymbol{\mathcal{D}}` is the observed data, the network can
+be reconstructed according to the posterior distribution,
+
+.. math::
+
+ P(\boldsymbol A, \boldsymbol b  \boldsymbol{\mathcal{D}}) =
+ \frac{P(\boldsymbol{\mathcal{D}}  \boldsymbol A)P(\boldsymbol A, \boldsymbol b)}{P(\boldsymbol{\mathcal{D}})}
+
+where the likelihood :math:`P(\boldsymbol{\mathcal{D}}\boldsymbol A)`
+models the measurement process, and for the prior :math:`P(\boldsymbol
+A, \boldsymbol b)` we use the SBM as before. This means that when
+performing reconstruction, we sample both the community structure
+:math:`\boldsymbol b` and the network :math:`\boldsymbol A` itself from
+the posterior distribution. From it, we can obtain the marginal probability
+of each edge,
+
+.. math::
+
+ \pi_{ij} = \sum_{\boldsymbol A, \boldsymbol b}A_{ij}P(\boldsymbol A, \boldsymbol b  \boldsymbol{\mathcal{D}}).
+
+Based on the marginal posterior probabilities, the best estimate for the
+whole underlying network :math:`\boldsymbol{\hat{A}}` is given by the
+maximum of this distribution,
+
+.. math::
+
+ \hat A_{ij} =
+ \begin{cases}
+ 1 & \text{ if } \pi_{ij} > \frac{1}{2},\\
+ 0 & \text{ if } \pi_{ij} < \frac{1}{2}.\\
+ \end{cases}
+
+We can also make estimates :math:`\hat y` of arbitrary scalar network
+properties :math:`y(\boldsymbol A)` via posterior averages,
+
+.. math::
+ \begin{align}
+ \hat y &= \sum_{\boldsymbol A, \boldsymbol b}y(\boldsymbol A)P(\boldsymbol A, \boldsymbol b  \boldsymbol{\mathcal{D}}),\\
+ \sigma^2_y &= \sum_{\boldsymbol A, \boldsymbol b}(y(\boldsymbol A)\hat y)^2P(\boldsymbol A, \boldsymbol b  \boldsymbol{\mathcal{D}})
+ \end{align}
+
+with uncertainty given by :math:`\sigma_y`. This is gives us a complete
+probabilistic reconstruction framework that fully reflects both the
+information and the uncertainty in the measurement data. Furthermore,
+the use of the SBM means that the reconstruction can take advantage of
+the *correlations* observed in the data to further inform it, which
+generally can lead to substantial improvements
+[peixotoreconstructing2018]_.
+
+In graphtool there is support for reconstruction with the above
+framework for three measurement processes: 1. Repeated measurements with
+uniform errors (via
+:class:`~graph_tool.inference.uncertain_blockmodel.MeasuredBlockState`), 2. Repeated
+measurements with heterogeneous errors (via
+:class:`~graph_tool.inference.uncertain_blockmodel.MixedMeasuredBlockState`),
+and 3. Extraneously obtained edge probabilities (via
+:class:`~graph_tool.inference.uncertain_blockmodel.UncertainBlockState`),
+which we describe in the following.
+
+Measured networks
++++++++++++++++++
+
+This model assumes that the node pairs :math:`(i,j)` were measured
+:math:`n_{ij}` times, and an edge has been recorded :math:`x_{ij}`
+times, where a missing edge occurs with probability :math:`p` and a
+spurious edge occurs with probability :math:`q`, uniformly for all node
+pairs, yielding a likelihood
+
+.. math::
+
+ P(\boldsymbol x  \boldsymbol n, \boldsymbol A, p, q) =
+ \prod_{i`__, which
+specify the amount of prior knowledge we have on the noise
+parameters. An important special case, which is the default unless
+otherwise specified, is when we are completely agnostic *a priori* about
+the noise magnitudes, and all hyperparameters are unity,
+
+.. math::
+
+ P(\boldsymbol x  \boldsymbol n, \boldsymbol A) \equiv
+ P(\boldsymbol x  \boldsymbol n, \boldsymbol A, \alpha=1,\beta=1,\mu=1,\nu=1).
+
+In this situation the priors :math:`P(p\alpha=1,\beta=1)` and
+:math:`P(q\mu=1,\nu=1)` are uniform distribution in the interval :math:`[0,1]`.
+
+.. note::
+
+ It is important to emphasize that since this approach makes use of
+ the *correlations* between edges to inform the reconstruction, as
+ described by the inferred SBM, this means it can also be used when
+ only single measurements have been performed, :math:`n_{ij}=1`, and
+ the error magnitudes :math:`p` and :math:`q` are unknown. Since every
+ arbitrary adjacency matrix can be cast in this setting, this method
+ can be used to reconstruct networks for which no error assessments of
+ any kind have been provided.
+
+Below, we illustrate how the reconstruction can be performed with a
+simple example, using
+:class:`~graph_tool.inference.uncertain_blockmodel.MeasuredBlockState`:
+
+.. testsetup:: measured
+
+ import os
+ try:
+ os.chdir("demos/inference")
+ except FileNotFoundError:
+ pass
+ np.random.seed(42)
+ gt.seed_rng(44)
+
+.. testcode:: measured
+
+ g = gt.collection.data["lesmis"].copy()
+
+ # pretend we have measured and observed each edge twice
+
+ n = g.new_ep("int", 2) # number of measurements
+ x = g.new_ep("int", 2) # number of observations
+
+ e = g.edge(11, 36)
+ x[e] = 1 # pretend we have observed edge (11, 36) only once
+
+ e = g.add_edge(15, 73)
+ n[e] = 2 # pretend we have measured nonedge (15, 73) twice,
+ x[e] = 1 # but observed it as an edge once.
+
+ bs = [g.get_vertices()] + [zeros(1)] * 5 # initial hierarchical partition
+
+ # We inititialize MeasuredBlockState, assuming that each nonedge has
+ # been measured only once (as opposed to twice for the observed
+ # edges), as specified by the 'n_default' and 'x_default' parameters.
+
+ state = gt.MeasuredBlockState(g, n=n, n_default=1, x=x, x_default=0,
+ state_args=dict(bs=bs))
+
+ # We will first equilibrate the Markov chain
+ gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
+
+ # Now we collect the marginals for exactly 100,000 sweeps, at
+ # intervals of 10 sweeps:
+
+ u = None # marginal posterior edge probabilities
+ pv = None # marginal posterior group membership probabilities
+ cs = [] # average local clustering coefficient
+
+ def collect_marginals(s):
+ global pv, u, cs
+ u = s.collect_marginal(u)
+ bstate = s.get_block_state()
+ pv = bstate.levels[0].collect_vertex_marginals(pv)
+ cs.append(gt.local_clustering(s.get_graph()).fa.mean())
+
+ gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
+ callback=collect_marginals)
+
+ eprob = u.ep.eprob
+ print("Posterior probability of edge (11, 36):", eprob[u.edge(11, 36)])
+ print("Posterior probability of nonedge (15, 73):", eprob[u.edge(15, 73)])
+ print("Estimated average local clustering: %g ± %g" % (np.mean(cs), np.std(cs)))
+
+
+Which yields the following output:
+
+.. testoutput:: measured
+
+ Posterior probability of edge (11, 36): 0.801980198019802
+ Posterior probability of nonedge (15, 73): 0.09730973097309731
+ Estimated average local clustering: 0.572154 ± 0.00485314
+
+We have a successful reconstruction, where both ambiguous adjacency
+matrix entries are correctly recovered. The value for the average
+clustering coefficient is also correctly estimated, and is compatible
+with the true value :math:`0.57313675`, within the estimated error.
+
+Below we visualize the maximum marginal posterior estimate of the
+reconstructed network:
+
+.. testcode:: measured
+
+ # The maximum marginal posterior estimator can be obtained by
+ # filtering the edges with probability larger than .5
+
+ u = gt.GraphView(u, efilt=u.ep.eprob.fa > .5)
+
+ # Mark the recovered true edges as red, and the removed spurious edges as green
+ ecolor = u.new_ep("vector", val=[0, 0, 0, .6])
+ for e in u.edges():
+ if g.edge(e.source(), e.target()) is None or (e.source(), e.target()) == (11, 36):
+ ecolor[e] = [1, 0, 0, .6]
+ for e in g.edges():
+ if u.edge(e.source(), e.target()) is None:
+ ne = u.add_edge(e.source(), e.target())
+ ecolor[ne] = [0, 1, 0, .6]
+
+ # Duplicate the internal block state with the reconstructed network
+ # u, for visualization purposes.
+
+ bstate = state.get_block_state()
+ bstate = bstate.levels[0].copy(g=u)
+
+ pv = u.own_property(pv)
+ edash = u.new_ep("vector")
+ edash[u.edge(15, 73)] = [.1, .1, 0]
+ bstate.draw(pos=u.own_property(g.vp.pos), vertex_shape="pie", vertex_pie_fractions=pv,
+ edge_color=ecolor, edge_dash_style=edash, edge_gradient=None,
+ output="lesmisreconstructionmarginals.svg")
+
+.. figure:: lesmisreconstructionmarginals.*
+ :align: center
+ :width: 450px
+
+ Reconstructed network of characters in the novel Les Misérables,
+ assuming that each edge has been measured and recorded twice, and
+ each nonedge has been measured only once, with the exception of edge
+ (11, 36), shown in red, and nonedge (15, 73), shown in green, which
+ have been measured twice and recorded as an edge once. Despite the
+ ambiguity, both errors are successfully corrected by the
+ reconstruction. The pie fractions on the nodes correspond to the
+ probability of being in group associated with the respective color.
+
+Heterogeneous errors
+^^^^^^^^^^^^^^^^^^^^
+
+In a more general scenario the measurement errors can be different for
+each node pair, i.e. :math:`p_{ij}` and :math:`q_{ij}` are the missing
+and spurious edge probability for node pair :math:`(i,j)`. The
+measurement likelihood then becomes
+
+.. math::
+
+ P(\boldsymbol x  \boldsymbol n, \boldsymbol A, \boldsymbol p, \boldsymbol q) =
+ \prod_{i`__, like
+before. Instead of prespecifying the hyperparameters, we include them
+from the posterior distribution
+
+.. math::
+
+ P(\boldsymbol A, \boldsymbol b, \alpha,\beta,\mu,\nu  \boldsymbol x, \boldsymbol n) =
+ \frac{P(\boldsymbol x  \boldsymbol n, \boldsymbol A, \alpha,\beta,\mu,\nu)P(\boldsymbol A, \boldsymbol b)P(\alpha,\beta,\mu,\nu)}{P(\boldsymbol x \boldsymbol n)},
+
+where :math:`P(\alpha,\beta,\mu,\nu)\propto 1` is a uniform hyperprior.
+
+Operationally, the inference with this model works similarly to the one
+with uniform error rates, as we see with the same example:
+
+.. testcode:: measured
+
+ state = gt.MixedMeasuredBlockState(g, n=n, n_default=1, x=x, x_default=0,
+ state_args=dict(bs=bs))
+
+ # We will first equilibrate the Markov chain
+ gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
+
+ # Now we collect the marginals for exactly 100,000 sweeps, at
+ # intervals of 10 sweeps:
+
+ u = None # marginal posterior edge probabilities
+ pv = None # marginal posterior group membership probabilities
+ cs = [] # average local clustering coefficient
+
+ gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
+ callback=collect_marginals)
+
+ eprob = u.ep.eprob
+ print("Posterior probability of edge (11, 36):", eprob[u.edge(11, 36)])
+ print("Posterior probability of nonedge (15, 73):", eprob[u.edge(15, 73)])
+ print("Estimated average local clustering: %g ± %g" % (np.mean(cs), np.std(cs)))
+
+Which yields:
+
+.. testoutput:: measured
+
+ Posterior probability of edge (11, 36): 0.7901790179017901
+ Posterior probability of nonedge (15, 73): 0.10901090109010901
+ Estimated average local clustering: 0.572504 ± 0.00545337
+
+The results are very similar to the ones obtained with the uniform model
+in this case, but can be quite different in situations where a large
+number of measurements has been performed (see
+[peixotoreconstructing2018]_ for details).
+
+Extraneous error estimates
+++++++++++++++++++++++++++
+
+In some situations the edge uncertainties are estimated by means other
+than repeated measurements, using domainspecific models. Here we
+consider the general case where the error estimates are extraneously
+provided as independent edge probabilities :math:`\boldsymbol Q`,
+
+.. math::
+
+ P_Q(\boldsymbol A  \boldsymbol Q) = \prod_{i .5)
+
+ # Mark the recovered true edges as red, and the removed spurious edges as green
+ ecolor = u.new_ep("vector", val=[0, 0, 0, .6])
+ edash = u.new_ep("vector")
+ for e in u.edges():
+ if g.edge(e.source(), e.target()) is None or (e.source(), e.target()) == (11, 36):
+ ecolor[e] = [1, 0, 0, .6]
+
+ for e in g.edges():
+ if u.edge(e.source(), e.target()) is None:
+ ne = u.add_edge(e.source(), e.target())
+ ecolor[ne] = [0, 1, 0, .6]
+ if (e.source(), e.target()) == (15, 73):
+ edash[ne] = [.1, .1, 0]
+
+ bstate = state.get_block_state()
+ bstate = bstate.levels[0].copy(g=u)
+ pv = u.own_property(pv)
+ bstate.draw(pos=u.own_property(g.vp.pos), vertex_shape="pie", vertex_pie_fractions=pv,
+ edge_color=ecolor, edge_dash_style=edash, edge_gradient=None,
+ output="lesmisuncertainreconstructionmarginals.svg")
+
+.. figure:: lesmisuncertainreconstructionmarginals.*
+ :align: center
+ :width: 450px
+
+ Reconstructed network of characters in the novel Les Misérables,
+ assuming that each edge as a measurement probability of
+ :math:`.98`. Edge (11, 36), shown in red, and nonedge (15, 73),
+ shown in green, both have probability :math:`0.5`. Despite the
+ ambiguity, both errors are successfully corrected by the
+ reconstruction. The pie fractions on the nodes correspond to the
+ probability of being in group associated with the respective color.
diff git a/doc/demos/inference/_sampling.rst b/doc/demos/inference/_sampling.rst
new file mode 100644
index 0000000000000000000000000000000000000000..a89034ab40a209efc69b7b393bce7481f02fcaaa
 /dev/null
+++ b/doc/demos/inference/_sampling.rst
@@ 0,0 +1,386 @@
+.. _sampling:
+
+Sampling from the posterior distribution
+
+
+When analyzing empirical networks, one should be open to the possibility
+that there will be more than one fit of the SBM with similar posterior
+probabilities. In such situations, one should instead `sample`
+partitions from the posterior distribution, instead of simply finding
+its maximum. One can then compute quantities that are averaged over the
+different model fits, weighted according to their posterior
+probabilities.
+
+Full support for model averaging is implemented in ``graphtool`` via an
+efficient `Markov chain Monte Carlo (MCMC)
+`_ algorithm
+[peixotoefficient2014]_. It works by attempting to move nodes into
+different groups with specific probabilities, and `accepting or
+rejecting
+`_
+such moves so that, after a sufficiently long time, the partitions will
+be observed with the desired posterior probability. The algorithm is
+designed so that its runtime (i.e. each sweep of the MCMC) is linear on
+the number of edges in the network, and independent on the number of
+groups being used in the model, and hence is suitable for use on very
+large networks.
+
+In order to perform such moves, one needs again to operate with
+:class:`~graph_tool.inference.blockmodel.BlockState` or
+:class:`~graph_tool.inference.nested_blockmodel.NestedBlockState` instances, and calling
+their :meth:`~graph_tool.inference.blockmodel.BlockState.mcmc_sweep` methods. For
+example, the following will perform 1000 sweeps of the algorithm with
+the network of characters in the novel Les Misérables, starting from a
+random partition into 20 groups
+
+.. testcode:: modelaveraging
+
+ g = gt.collection.data["lesmis"]
+
+ state = gt.BlockState(g, B=20) # This automatically initializes the state
+ # with a random partition into B=20
+ # nonempty groups; The user could
+ # also pass an arbitrary initial
+ # partition using the 'b' parameter.
+
+ # Now we run 1,000 sweeps of the MCMC. Note that the number of groups
+ # is allowed to change, so it will eventually move from the initial
+ # value of B=20 to whatever is most appropriate for the data.
+
+ dS, nattempts, nmoves = state.mcmc_sweep(niter=1000)
+
+ print("Change in description length:", dS)
+ print("Number of accepted vertex moves:", nmoves)
+
+.. testoutput:: modelaveraging
+
+ Change in description length: 365.317522...
+ Number of accepted vertex moves: 38213
+
+.. note::
+
+ Starting from a random partition is rarely the best option, since it
+ may take a long time for it to equilibrate. It was done above simply
+ as an illustration on how to initialize
+ :class:`~graph_tool.inference.blockmodel.BlockState` by hand. Instead, a much
+ better option in practice is to start from an approximation to the
+ "ground state" obtained with
+ :func:`~graph_tool.inference.minimize.minimize_blockmodel_dl`, e.g.
+
+ .. testcode:: modelaveraging
+
+ state = gt.minimize_blockmodel_dl(g)
+ state = state.copy(B=g.num_vertices())
+ dS, nattempts, nmoves = state.mcmc_sweep(niter=1000)
+
+ print("Change in description length:", dS)
+ print("Number of accepted vertex moves:", nmoves)
+
+ .. testoutput:: modelaveraging
+
+ Change in description length: 1.660677...
+ Number of accepted vertex moves: 40461
+
+Although the above is sufficient to implement model averaging, there is a
+convenience function called
+:func:`~graph_tool.inference.mcmc.mcmc_equilibrate` that is intend to
+simplify the detection of equilibration, by keeping track of the maximum
+and minimum values of description length encountered and how many sweeps
+have been made without a "record breaking" event. For example,
+
+.. testcode:: modelaveraging
+
+ # We will accept equilibration if 10 sweeps are completed without a
+ # record breaking event, 2 consecutive times.
+
+ gt.mcmc_equilibrate(state, wait=10, nbreaks=2, mcmc_args=dict(niter=10), verbose=True)
+
+will output:
+
+.. testoutput:: modelaveraging
+ :options: +NORMALIZE_WHITESPACE
+
+ niter: 1 count: 0 breaks: 0 min_S: 706.26857 max_S: 708.14483 S: 708.14483 ΔS: 1.87626 moves: 418
+ niter: 2 count: 0 breaks: 0 min_S: 699.23453 max_S: 708.14483 S: 699.23453 ΔS: 8.91030 moves: 409
+ niter: 3 count: 0 breaks: 0 min_S: 699.23453 max_S: 715.33531 S: 715.33531 ΔS: 16.1008 moves: 414
+ niter: 4 count: 0 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 723.13301 ΔS: 7.79770 moves: 391
+ niter: 5 count: 1 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 702.93354 ΔS: 20.1995 moves: 411
+ niter: 6 count: 2 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 706.39029 ΔS: 3.45675 moves: 389
+ niter: 7 count: 3 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 706.80859 ΔS: 0.418293 moves: 404
+ niter: 8 count: 4 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 707.61960 ΔS: 0.811010 moves: 417
+ niter: 9 count: 5 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 706.46577 ΔS: 1.15383 moves: 392
+ niter: 10 count: 6 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 714.34671 ΔS: 7.88094 moves: 410
+ niter: 11 count: 7 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 706.43194 ΔS: 7.91477 moves: 383
+ niter: 12 count: 8 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 705.19434 ΔS: 1.23760 moves: 405
+ niter: 13 count: 9 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 702.21395 ΔS: 2.98039 moves: 423
+ niter: 14 count: 0 breaks: 1 min_S: 715.54878 max_S: 715.54878 S: 715.54878 ΔS: 13.3348 moves: 400
+ niter: 15 count: 0 breaks: 1 min_S: 715.54878 max_S: 716.65842 S: 716.65842 ΔS: 1.10964 moves: 413
+ niter: 16 count: 0 breaks: 1 min_S: 701.19994 max_S: 716.65842 S: 701.19994 ΔS: 15.4585 moves: 382
+ niter: 17 count: 1 breaks: 1 min_S: 701.19994 max_S: 716.65842 S: 715.56997 ΔS: 14.3700 moves: 394
+ niter: 18 count: 0 breaks: 1 min_S: 701.19994 max_S: 719.25577 S: 719.25577 ΔS: 3.68580 moves: 404
+ niter: 19 count: 0 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 723.78811 ΔS: 4.53233 moves: 413
+ niter: 20 count: 1 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 709.77340 ΔS: 14.0147 moves: 387
+ niter: 21 count: 2 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 714.14891 ΔS: 4.37551 moves: 419
+ niter: 22 count: 3 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 722.05875 ΔS: 7.90984 moves: 399
+ niter: 23 count: 4 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 714.32503 ΔS: 7.73371 moves: 422
+ niter: 24 count: 5 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 708.53927 ΔS: 5.78576 moves: 392
+ niter: 25 count: 6 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 714.05889 ΔS: 5.51962 moves: 404
+ niter: 26 count: 7 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 713.93196 ΔS: 0.126937 moves: 414
+ niter: 27 count: 8 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 709.49863 ΔS: 4.43333 moves: 410
+ niter: 28 count: 9 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 707.42167 ΔS: 2.07696 moves: 397
+ niter: 29 count: 0 breaks: 1 min_S: 699.89982 max_S: 723.78811 S: 699.89982 ΔS: 7.52185 moves: 388
+ niter: 30 count: 0 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 698.57305 ΔS: 1.32677 moves: 391
+ niter: 31 count: 1 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 706.02629 ΔS: 7.45324 moves: 412
+ niter: 32 count: 2 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 701.97778 ΔS: 4.04852 moves: 421
+ niter: 33 count: 3 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 707.50134 ΔS: 5.52356 moves: 410
+ niter: 34 count: 4 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 708.56686 ΔS: 1.06552 moves: 424
+ niter: 35 count: 0 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 724.07361 ΔS: 15.5067 moves: 399
+ niter: 36 count: 1 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 723.51969 ΔS: 0.553915 moves: 384
+ niter: 37 count: 2 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 702.36708 ΔS: 21.1526 moves: 406
+ niter: 38 count: 3 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 707.60129 ΔS: 5.23420 moves: 405
+ niter: 39 count: 4 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 709.67542 ΔS: 2.07413 moves: 400
+ niter: 40 count: 5 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 714.52753 ΔS: 4.85212 moves: 398
+ niter: 41 count: 6 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 707.86563 ΔS: 6.66190 moves: 409
+ niter: 42 count: 7 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 718.80926 ΔS: 10.9436 moves: 400
+ niter: 43 count: 8 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 716.37312 ΔS: 2.43615 moves: 378
+ niter: 44 count: 9 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 713.76944 ΔS: 2.60368 moves: 399
+ niter: 45 count: 10 breaks: 2 min_S: 698.57305 max_S: 724.07361 S: 715.29009 ΔS: 1.52066 moves: 421
+
+Note that the value of ``wait`` above was made purposefully low so that
+the output would not be overly long. The most appropriate value requires
+experimentation, but a typically good value is ``wait=1000``.
+
+The function :func:`~graph_tool.inference.mcmc.mcmc_equilibrate` accepts a
+``callback`` argument that takes an optional function to be invoked
+after each call to
+:meth:`~graph_tool.inference.blockmodel.BlockState.mcmc_sweep`. This function
+should accept a single parameter which will contain the actual
+:class:`~graph_tool.inference.blockmodel.BlockState` instance. We will use this in
+the example below to collect the posterior vertex marginals (via
+:class:`~graph_tool.inference.blockmodel.BlockState.collect_vertex_marginals`),
+i.e. the posterior probability that a node belongs to a given group:
+
+.. testcode:: modelaveraging
+
+ # We will first equilibrate the Markov chain
+ gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
+
+ pv = None
+
+ def collect_marginals(s):
+ global pv
+ pv = s.collect_vertex_marginals(pv)
+
+ # Now we collect the marginals for exactly 100,000 sweeps, at
+ # intervals of 10 sweeps:
+ gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
+ callback=collect_marginals)
+
+ # Now the node marginals are stored in property map pv. We can
+ # visualize them as pie charts on the nodes:
+ state.draw(pos=g.vp.pos, vertex_shape="pie", vertex_pie_fractions=pv,
+ edge_gradient=None, output="lesmissbmmarginals.svg")
+
+.. figure:: lesmissbmmarginals.*
+ :align: center
+ :width: 450px
+
+ Marginal probabilities of group memberships of the network of
+ characters in the novel Les Misérables, according to the
+ degreecorrected SBM. The `pie fractions
+ `_ on the nodes correspond
+ to the probability of being in group associated with the respective
+ color.
+
+We can also obtain a marginal probability on the number of groups
+itself, as follows.
+
+.. testcode:: modelaveraging
+
+ h = np.zeros(g.num_vertices() + 1)
+
+ def collect_num_groups(s):
+ B = s.get_nonempty_B()
+ h[B] += 1
+
+ # Now we collect the marginals for exactly 100,000 sweeps, at
+ # intervals of 10 sweeps:
+ gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
+ callback=collect_num_groups)
+
+.. testcode:: modelaveraging
+ :hide:
+
+ figure()
+ Bs = np.arange(len(h))
+ idx = h > 0
+ bar(Bs[idx], h[idx] / h.sum(), width=1, color="#ccb974")
+ gca().set_xticks([6,7,8,9])
+ xlabel("$B$")
+ ylabel(r"$P(B\boldsymbol G)$")
+ savefig("lesmisBposterior.svg")
+
+.. figure:: lesmisBposterior.*
+ :align: center
+
+ Marginal posterior probability of the number of nonempty groups for
+ the network of characters in the novel Les Misérables, according to
+ the degreecorrected SBM.
+
+
+Hierarchical partitions
++++++++++++++++++++++++
+
+We can also perform model averaging using the nested SBM, which will
+give us a distribution over hierarchies. The whole procedure is fairly
+analogous, but now we make use of
+:class:`~graph_tool.inference.nested_blockmodel.NestedBlockState` instances.
+
+.. note::
+
+ When using :class:`~graph_tool.inference.nested_blockmodel.NestedBlockState` instances
+ to perform model averaging, they need to be constructed with the
+ option ``sampling=True``.
+
+Here we perform the sampling of hierarchical partitions using the same
+network as above.
+
+.. testcode:: nestedmodelaveraging
+
+ g = gt.collection.data["lesmis"]
+
+ state = gt.minimize_nested_blockmodel_dl(g) # Initialize he Markov
+ # chain from the "ground
+ # state"
+
+ # Before doing model averaging, the need to create a NestedBlockState
+ # by passing sampling = True.
+
+ # We also want to increase the maximum hierarchy depth to L = 10
+
+ # We can do both of the above by copying.
+
+ bs = state.get_bs() # Get hierarchical partition.
+ bs += [np.zeros(1)] * (10  len(bs)) # Augment it to L = 10 with
+ # singlegroup levels.
+
+ state = state.copy(bs=bs, sampling=True)
+
+ # Now we run 1000 sweeps of the MCMC
+
+ dS, nattempts, nmoves = state.mcmc_sweep(niter=1000)
+
+ print("Change in description length:", dS)
+ print("Number of accepted vertex moves:", nmoves)
+
+.. testoutput:: nestedmodelaveraging
+
+ Change in description length: 2.371018...
+ Number of accepted vertex moves: 56087
+
+Similarly to the the nonnested case, we can use
+:func:`~graph_tool.inference.mcmc.mcmc_equilibrate` to do most of the boring
+work, and we can now obtain vertex marginals on all hierarchical levels:
+
+
+.. testcode:: nestedmodelaveraging
+
+ # We will first equilibrate the Markov chain
+ gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
+
+ pv = [None] * len(state.get_levels())
+
+ def collect_marginals(s):
+ global pv
+ pv = [sl.collect_vertex_marginals(pv[l]) for l, sl in enumerate(s.get_levels())]
+
+ # Now we collect the marginals for exactly 100,000 sweeps
+ gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
+ callback=collect_marginals)
+
+ # Now the node marginals for all levels are stored in property map
+ # list pv. We can visualize the first level as pie charts on the nodes:
+ state_0 = state.get_levels()[0]
+ state_0.draw(pos=g.vp.pos, vertex_shape="pie", vertex_pie_fractions=pv[0],
+ edge_gradient=None, output="lesmisnestedsbmmarginals.svg")
+
+.. figure:: lesmisnestedsbmmarginals.*
+ :align: center
+ :width: 450px
+
+ Marginal probabilities of group memberships of the network of
+ characters in the novel Les Misérables, according to the nested
+ degreecorrected SBM. The pie fractions on the nodes correspond to
+ the probability of being in group associated with the respective
+ color.
+
+We can also obtain a marginal probability of the number of groups
+itself, as follows.
+
+.. testcode:: nestedmodelaveraging
+
+ h = [np.zeros(g.num_vertices() + 1) for s in state.get_levels()]
+
+ def collect_num_groups(s):
+ for l, sl in enumerate(s.get_levels()):
+ B = sl.get_nonempty_B()
+ h[l][B] += 1
+
+ # Now we collect the marginal distribution for exactly 100,000 sweeps
+ gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
+ callback=collect_num_groups)
+
+.. testcode:: nestedmodelaveraging
+ :hide:
+
+ figure()
+ f, ax = plt.subplots(1, 5, figsize=(10, 3))
+ for i, h_ in enumerate(h[:5]):
+ Bs = np.arange(len(h_))
+ idx = h_ > 0
+ ax[i].bar(Bs[idx], h_[idx] / h_.sum(), width=1, color="#ccb974")
+ ax[i].set_xticks(Bs[idx])
+ ax[i].set_xlabel("$B_{%d}$" % i)
+ ax[i].set_ylabel(r"$P(B_{%d}\boldsymbol G)$" % i)
+ locator = MaxNLocator(prune='both', nbins=5)
+ ax[i].yaxis.set_major_locator(locator)
+ tight_layout()
+ savefig("lesmisnestedBposterior.svg")
+
+.. figure:: lesmisnestedBposterior.*
+ :align: center
+
+ Marginal posterior probability of the number of nonempty groups
+ :math:`B_l` at each hierarchy level :math:`l` for the network of
+ characters in the novel Les Misérables, according to the nested
+ degreecorrected SBM.
+
+Below we obtain some hierarchical partitions sampled from the posterior
+distribution.
+
+.. testcode:: nestedmodelaveraging
+
+ for i in range(10):
+ state.mcmc_sweep(niter=1000)
+ state.draw(output="lesmispartitionsample%i.svg" % i, empty_branches=False)
+
+.. image:: lesmispartitionsample0.svg
+ :width: 200px
+.. image:: lesmispartitionsample1.svg
+ :width: 200px
+.. image:: lesmispartitionsample2.svg
+ :width: 200px
+.. image:: lesmispartitionsample3.svg
+ :width: 200px
+.. image:: lesmispartitionsample4.svg
+ :width: 200px
+.. image:: lesmispartitionsample5.svg
+ :width: 200px
+.. image:: lesmispartitionsample6.svg
+ :width: 200px
+.. image:: lesmispartitionsample7.svg
+ :width: 200px
+.. image:: lesmispartitionsample8.svg
+ :width: 200px
+.. image:: lesmispartitionsample9.svg
+ :width: 200px
diff git a/doc/demos/inference/inference.rst b/doc/demos/inference/inference.rst
index 4933d4afec07284fc253d4039992f6e98419ebd6..a446037f510602731dceef2462c2794d12b7403f 100644
 a/doc/demos/inference/inference.rst
+++ b/doc/demos/inference/inference.rst
@@ 9,1639 +9,17 @@ explain the basic functionality with selfcontained examples. For a more
thorough theoretical introduction to the methods described here, the
reader is referred to [peixotobayesian2017]_.
Background: Nonparametric statistical inference

A common task when analyzing networks is to characterize their
structures in simple terms, often by dividing the nodes into modules or
"communities".
+.. include:: _background.rst
+.. include:: _minimization.rst
+.. include:: _model_selection.rst
+.. include:: _sampling.rst
+.. include:: _model_class_selection.rst
+.. include:: _edge_weights.rst
+.. include:: _layers.rst
+.. include:: _reconstruction.rst
+.. include:: _prediction.rst
A principled approach to perform this task is to formulate `generative
models `_ that include
the idea of "modules" in their descriptions, which then can be detected
by `inferring `_
the model parameters from data. More precisely, given the partition
:math:`\boldsymbol b = \{b_i\}` of the network into :math:`B` groups,
where :math:`b_i\in[0,B1]` is the group membership of node :math:`i`,
we define a model that generates a network :math:`\boldsymbol G` with a
probability

.. math::
 :label: modellikelihood

 P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)

where :math:`\boldsymbol\theta` are additional model parameters that
control how the node partition affects the structure of the
network. Therefore, if we observe a network :math:`\boldsymbol G`, the
likelihood that it was generated by a given partition :math:`\boldsymbol
b` is obtained via the `Bayesian
`_ posterior

.. math::
 :label: modelposteriorsum

 P(\boldsymbol b  \boldsymbol G) = \frac{\sum_{\boldsymbol\theta}P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)}{P(\boldsymbol G)}

where :math:`P(\boldsymbol\theta, \boldsymbol b)` is the `prior
probability `_ of the
model parameters, and

.. math::
 :label: modelevidence

 P(\boldsymbol G) = \sum_{\boldsymbol\theta,\boldsymbol b}P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)

is called the `evidence`. The particular types of model that will be
considered here have "hard constraints", such that there is only one
choice for the remaining parameters :math:`\boldsymbol\theta` that is
compatible with the generated network, such that
Eq. :eq:`modelposteriorsum` simplifies to

.. math::
 :label: modelposterior

 P(\boldsymbol b  \boldsymbol G) = \frac{P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)}{P(\boldsymbol G)}

with :math:`\boldsymbol\theta` above being the only choice compatible with
:math:`\boldsymbol G` and :math:`\boldsymbol b`. The inference procedures considered
here will consist in either finding a network partition that maximizes
Eq. :eq:`modelposterior`, or sampling different partitions according
its posterior probability.

As we will show below, this approach also enables the comparison of
`different` models according to statistical evidence (a.k.a. `model
selection`).

Minimum description length (MDL)
++++++++++++++++++++++++++++++++

We note that Eq. :eq:`modelposterior` can be written as

.. math::

 P(\boldsymbol b  \boldsymbol G) = \frac{\exp(\Sigma)}{P(\boldsymbol G)}

where

.. math::
 :label: modeldl

 \Sigma = \ln P(\boldsymbol G\boldsymbol\theta, \boldsymbol b)  \ln P(\boldsymbol\theta, \boldsymbol b)

is called the **description length** of the network :math:`\boldsymbol
G`. It measures the amount of `information
`_ required to
describe the data, if we `encode
`_ it using the
particular parametrization of the generative model given by
:math:`\boldsymbol\theta` and :math:`\boldsymbol b`, as well as the
parameters themselves. Therefore, if we choose to maximize the posterior
distribution of Eq. :eq:`modelposterior` it will be fully equivalent to
the socalled `minimum description length
`_
method. This approach corresponds to an implementation of `Occam's razor
`_, where the `simplest`
model is selected, among all possibilities with the same explanatory
power. The selection is based on the statistical evidence available, and
therefore will not `overfit
`_, i.e. mistake stochastic
fluctuations for actual structure. In particular this means that we will
not find modules in networks if they could have arisen simply because of
stochastic fluctuations, as they do in fully random graphs
[guimeramodularity2004]_.

The stochastic block model (SBM)


The `stochastic block model
`_ is arguably
the simplest generative process based on the notion of groups of
nodes [hollandstochastic1983]_. The `microcanonical
`_ formulation
[peixotononparametric2017]_ of the basic or "traditional" version takes
as parameters the partition of the nodes into groups
:math:`\boldsymbol b` and a :math:`B\times B` matrix of edge counts
:math:`\boldsymbol e`, where :math:`e_{rs}` is the number of edges
between groups :math:`r` and :math:`s`. Given these constraints, the
edges are then placed randomly. Hence, nodes that belong to the same
group possess the same probability of being connected with other
nodes of the network.

An example of a possible parametrization is given in the following
figure.

.. testcode:: sbmexample
 :hide:

 import os
 try:
 os.chdir("demos/inference")
 except FileNotFoundError:
 pass

 g = gt.load_graph("blockmodelexample.gt.gz")
 gt.graph_draw(g, pos=g.vp.pos, vertex_size=10, vertex_fill_color=g.vp.bo,
 vertex_color="#333333",
 edge_gradient=g.new_ep("vector", val=[0]),
 output="sbmexample.svg")

 ers = g.gp.w

 from pylab import *
 figure()
 matshow(log(ers))
 xlabel("Group $r$")
 ylabel("Group $s$")
 gca().xaxis.set_label_position("top")
 savefig("sbmexampleers.svg")

.. table::
 :class: figure

 +++
 .. figure:: sbmexampleers.svg .. figure:: sbmexample.svg 
  :width: 300px  :width: 300px 
  :align: center  :align: center 
   
  Matrix of edge counts  Generated network. 
  :math:`\boldsymbol e` between  
  groups.  
 +++

.. note::

 We emphasize that no constraints are imposed on what `kind` of
 modular structure is allowed, as the matrix of edge counts :math:`e`
 is unconstrained. Hence, we can detect the putatively typical pattern
 of `"community structure"
 `_, i.e. when
 nodes are connected mostly to other nodes of the same group, if it
 happens to be the most likely network description, but we can also
 detect a large multiplicity of other patterns, such as `bipartiteness
 `_, coreperiphery,
 and many others, all under the same inference framework.


Although quite general, the traditional model assumes that the edges are
placed randomly inside each group, and because of this the nodes that
belong to the same group tend to have very similar degrees. As it turns
out, this is often a poor model for many networks, which possess highly
heterogeneous degree distributions. A better model for such networks is
called the `degreecorrected` stochastic block model
[karrerstochastic2011]_, and it is defined just like the traditional
model, with the addition of the degree sequence :math:`\boldsymbol k =
\{k_i\}` of the graph as an additional set of parameters (assuming again
a microcanonical formulation [peixotononparametric2017]_).


The nested stochastic block model
+++++++++++++++++++++++++++++++++

The regular SBM has a drawback when applied to large networks. Namely,
it cannot be used to find relatively small groups, as the maximum number
of groups that can be found scales as
:math:`B_{\text{max}}=O(\sqrt{N})`, where :math:`N` is the number of
nodes in the network, if Bayesian inference is performed
[peixotoparsimonious2013]_. In order to circumvent this, we need to
replace the noninformative priors used by a hierarchy of priors and
hyperpriors, which amounts to a `nested SBM`, where the groups
themselves are clustered into groups, and the matrix :math:`e` of edge
counts are generated from another SBM, and so on recursively
[peixotohierarchical2014]_, as illustrated below.

.. figure:: nesteddiagram.*
 :width: 400px
 :align: center

 Example of a nested SBM with three levels.

With this model, the maximum number of groups that can be inferred
scales as :math:`B_{\text{max}}=O(N/\log(N))`. In addition to being able
to find small groups in large networks, this model also provides a
multilevel hierarchical description of the network. With such a
description, we can uncover structural patterns at multiple scales,
representing different levels of coarsegraining.

Inferring the best partition


The simplest and most efficient approach is to find the best
partition of the network by maximizing Eq. :eq:`modelposterior`
according to some version of the model. This is obtained via the
functions :func:`~graph_tool.inference.minimize.minimize_blockmodel_dl` or
:func:`~graph_tool.inference.minimize.minimize_nested_blockmodel_dl`, which
employs an agglomerative multilevel `Markov chain Monte Carlo (MCMC)
`_ algorithm
[peixotoefficient2014]_.

We focus first on the nonnested model, and we illustrate its use with a
network of American football teams, which we load from the
:mod:`~graph_tool.collection` module:

.. testsetup:: football

 import os
 try:
 os.chdir("demos/inference")
 except FileNotFoundError:
 pass
 gt.seed_rng(7)

.. testcode:: football

 g = gt.collection.data["football"]
 print(g)

which yields

.. testoutput:: football



we then fit the degreecorrected model by calling

.. testcode:: football

 state = gt.minimize_blockmodel_dl(g)

This returns a :class:`~graph_tool.inference.blockmodel.BlockState` object that
includes the inference results.

.. note::

 The inference algorithm used is stochastic by nature, and may return
 a different answer each time it is run. This may be due to the fact
 that there are alternative partitions with similar probabilities, or
 that the optimum is difficult to find. Note that the inference
 problem here is, in general, `NPHard
 `_, hence there is no
 efficient algorithm that is guaranteed to always find the best
 answer.

 Because of this, typically one would call the algorithm many times,
 and select the partition with the largest posterior probability of
 Eq. :eq:`modelposterior`, or equivalently, the minimum description
 length of Eq. :eq:`modeldl`. The description length of a fit can be
 obtained with the :meth:`~graph_tool.inference.blockmodel.BlockState.entropy`
 method. See also Sec. :ref:`sec_model_selection` below.


We may perform a drawing of the partition obtained via the
:mod:`~graph_tool.inference.blockmodel.BlockState.draw` method, that functions as a
convenience wrapper to the :func:`~graph_tool.draw.graph_draw` function

.. testcode:: football

 state.draw(pos=g.vp.pos, output="footballsbmfit.svg")

which yields the following image.

.. figure:: footballsbmfit.*
 :align: center
 :width: 400px

 Stochastic block model inference of a network of American college
 football teams. The colors correspond to inferred group membership of
 the nodes.

We can obtain the group memberships as a
:class:`~graph_tool.PropertyMap` on the vertices via the
:mod:`~graph_tool.inference.blockmodel.BlockState.get_blocks` method:

.. testcode:: football

 b = state.get_blocks()
 r = b[10] # group membership of vertex 10
 print(r)

which yields:

.. testoutput:: football

 3

We may also access the matrix of edge counts between groups via
:mod:`~graph_tool.inference.blockmodel.BlockState.get_matrix`

.. testcode:: football

 e = state.get_matrix()

 matshow(e.todense())
 savefig("footballedgecounts.svg")

.. figure:: footballedgecounts.*
 :align: center

 Matrix of edge counts between groups.

We may obtain the same matrix of edge counts as a graph, which has
internal edge and vertex property maps with the edge and vertex counts,
respectively:

.. testcode:: football

 bg = state.get_bg()
 ers = state.mrs # edge counts
 nr = state.wr # node counts

.. _sec_model_selection:

Hierarchical partitions
+++++++++++++++++++++++

The inference of the nested family of SBMs is done in a similar manner,
but we must use instead the
:func:`~graph_tool.inference.minimize.minimize_nested_blockmodel_dl` function. We
illustrate its use with the neural network of the `C. elegans
`_ worm:

.. testsetup:: celegans

 gt.seed_rng(47)

.. testcode:: celegans

 g = gt.collection.data["celegansneural"]
 print(g)

which has 297 vertices and 2359 edges.

.. testoutput:: celegans



A hierarchical fit of the degreecorrected model is performed as follows.

.. testcode:: celegans

 state = gt.minimize_nested_blockmodel_dl(g)

The object returned is an instance of a
:class:`~graph_tool.inference.nested_blockmodel.NestedBlockState` class, which
encapsulates the results. We can again draw the resulting hierarchical
clustering using the
:meth:`~graph_tool.inference.nested_blockmodel.NestedBlockState.draw` method:

.. testcode:: celegans

 state.draw(output="celeganshsbmfit.svg")

.. figure:: celeganshsbmfit.*
 :align: center

 Most likely hierarchical partition of the neural network of
 the C. elegans worm according to the nested degreecorrected SBM.

.. note::

 If the ``output`` parameter to
 :meth:`~graph_tool.inference.nested_blockmodel.NestedBlockState.draw` is omitted, an
 interactive visualization is performed, where the user can reorder
 the hierarchy nodes using the mouse and pressing the ``r`` key.

A summary of the inferred hierarchy can be obtained with the
:meth:`~graph_tool.inference.nested_blockmodel.NestedBlockState.print_summary` method,
which shows the number of nodes and groups in all levels:

.. testcode:: celegans

 state.print_summary()

.. testoutput:: celegans

 l: 0, N: 297, B: 17
 l: 1, N: 17, B: 9
 l: 2, N: 9, B: 3
 l: 3, N: 3, B: 1

The hierarchical levels themselves are represented by individual
:meth:`~graph_tool.inference.blockmodel.BlockState` instances obtained via the
:meth:`~graph_tool.inference.nested_blockmodel.NestedBlockState.get_levels()` method:

.. testcode:: celegans

 levels = state.get_levels()
 for s in levels:
 print(s)

.. testoutput:: celegans

 , at 0x...>
 , at 0x...>
 , at 0x...>
 , at 0x...>

This means that we can inspect the hierarchical partition just as before:

.. testcode:: celegans

 r = levels[0].get_blocks()[46] # group membership of node 46 in level 0
 print(r)
 r = levels[0].get_blocks()[r] # group membership of node 46 in level 1
 print(r)
 r = levels[0].get_blocks()[r] # group membership of node 46 in level 2
 print(r)

.. testoutput:: celegans

 7
 0
 0

.. _model_selection:

Model selection
+++++++++++++++

As mentioned above, one can select the best model according to the
choice that yields the smallest description length
[peixotomodel2016]_. For instance, in case of the `C. elegans` network
we have

.. testsetup:: modelselection

 gt.seed_rng(43)

.. testcode:: modelselection

 g = gt.collection.data["celegansneural"]

 state_ndc = gt.minimize_nested_blockmodel_dl(g, deg_corr=False)
 state_dc = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)

 print("Nondegreecorrected DL:\t", state_ndc.entropy())
 print("Degreecorrected DL:\t", state_dc.entropy())

.. testoutput:: modelselection
 :options: +NORMALIZE_WHITESPACE

 Nondegreecorrected DL: 8456.994339...
 Degreecorrected DL: 8233.850036...

Since it yields the smallest description length, the degreecorrected
fit should be preferred. The statistical significance of the choice can
be accessed by inspecting the posterior odds ratio
[peixotononparametric2017]_

.. math::

 \Lambda &= \frac{P(\boldsymbol b, \mathcal{H}_\text{NDC}  \boldsymbol G)}{P(\boldsymbol b, \mathcal{H}_\text{DC}  \boldsymbol G)} \\
 &= \frac{P(\boldsymbol G, \boldsymbol b  \mathcal{H}_\text{NDC})}{P(\boldsymbol G, \boldsymbol b  \mathcal{H}_\text{DC})}\times\frac{P(\mathcal{H}_\text{NDC})}{P(\mathcal{H}_\text{DC})} \\
 &= \exp(\Delta\Sigma)

where :math:`\mathcal{H}_\text{NDC}` and :math:`\mathcal{H}_\text{DC}`
correspond to the nondegreecorrected and degreecorrected model
hypotheses (assumed to be equally likely `a priori`), respectively, and
:math:`\Delta\Sigma` is the difference of the description length of both
fits. In our particular case, we have

.. testcode:: modelselection

 print(u"ln \u039b: ", state_dc.entropy()  state_ndc.entropy())

.. testoutput:: modelselection
 :options: +NORMALIZE_WHITESPACE

 ln Λ: 223.144303...

The precise threshold that should be used to decide when to `reject a
hypothesis `_ is
subjective and contextdependent, but the value above implies that the
particular degreecorrected fit is around :math:`\mathrm{e}^{233} \approx 10^{96}`
times more likely than the nondegree corrected one, and hence it can be
safely concluded that it provides a substantially better fit.

Although it is often true that the degreecorrected model provides a
better fit for many empirical networks, there are also exceptions. For
example, for the American football network above, we have:

.. testcode:: modelselection

 g = gt.collection.data["football"]

 state_ndc = gt.minimize_nested_blockmodel_dl(g, deg_corr=False)
 state_dc = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)

 print("Nondegreecorrected DL:\t", state_ndc.entropy())
 print("Degreecorrected DL:\t", state_dc.entropy())
 print(u"ln \u039b:\t\t\t", state_ndc.entropy()  state_dc.entropy())

.. testoutput:: modelselection
 :options: +NORMALIZE_WHITESPACE

 Nondegreecorrected DL: 1734.814739...
 Degreecorrected DL: 1780.576716...
 ln Λ: 45.761977...

Hence, with a posterior odds ratio of :math:`\Lambda \approx \mathrm{e}^{45} \approx
10^{19}` in favor of the nondegreecorrected model, it seems like the
degreecorrected variant is an unnecessarily complex description for
this network.

.. _sampling:

Sampling from the posterior distribution


When analyzing empirical networks, one should be open to the possibility
that there will be more than one fit of the SBM with similar posterior
probabilities. In such situations, one should instead `sample`
partitions from the posterior distribution, instead of simply finding
its maximum. One can then compute quantities that are averaged over the
different model fits, weighted according to their posterior
probabilities.

Full support for model averaging is implemented in ``graphtool`` via an
efficient `Markov chain Monte Carlo (MCMC)
`_ algorithm
[peixotoefficient2014]_. It works by attempting to move nodes into
different groups with specific probabilities, and `accepting or
rejecting
`_
such moves so that, after a sufficiently long time, the partitions will
be observed with the desired posterior probability. The algorithm is
designed so that its runtime (i.e. each sweep of the MCMC) is linear on
the number of edges in the network, and independent on the number of
groups being used in the model, and hence is suitable for use on very
large networks.

In order to perform such moves, one needs again to operate with
:class:`~graph_tool.inference.blockmodel.BlockState` or
:class:`~graph_tool.inference.nested_blockmodel.NestedBlockState` instances, and calling
their :meth:`~graph_tool.inference.blockmodel.BlockState.mcmc_sweep` methods. For
example, the following will perform 1000 sweeps of the algorithm with
the network of characters in the novel Les Misérables, starting from a
random partition into 20 groups

.. testcode:: modelaveraging

 g = gt.collection.data["lesmis"]

 state = gt.BlockState(g, B=20) # This automatically initializes the state
 # with a random partition into B=20
 # nonempty groups; The user could
 # also pass an arbitrary initial
 # partition using the 'b' parameter.

 # Now we run 1,000 sweeps of the MCMC. Note that the number of groups
 # is allowed to change, so it will eventually move from the initial
 # value of B=20 to whatever is most appropriate for the data.

 dS, nattempts, nmoves = state.mcmc_sweep(niter=1000)

 print("Change in description length:", dS)
 print("Number of accepted vertex moves:", nmoves)

.. testoutput:: modelaveraging

 Change in description length: 365.317522...
 Number of accepted vertex moves: 38213

.. note::

 Starting from a random partition is rarely the best option, since it
 may take a long time for it to equilibrate. It was done above simply
 as an illustration on how to initialize
 :class:`~graph_tool.inference.blockmodel.BlockState` by hand. Instead, a much
 better option in practice is to start from an approximation to the
 "ground state" obtained with
 :func:`~graph_tool.inference.minimize.minimize_blockmodel_dl`, e.g.

 .. testcode:: modelaveraging

 state = gt.minimize_blockmodel_dl(g)
 state = state.copy(B=g.num_vertices())
 dS, nattempts, nmoves = state.mcmc_sweep(niter=1000)

 print("Change in description length:", dS)
 print("Number of accepted vertex moves:", nmoves)

 .. testoutput:: modelaveraging

 Change in description length: 1.660677...
 Number of accepted vertex moves: 40461

Although the above is sufficient to implement model averaging, there is a
convenience function called
:func:`~graph_tool.inference.mcmc.mcmc_equilibrate` that is intend to
simplify the detection of equilibration, by keeping track of the maximum
and minimum values of description length encountered and how many sweeps
have been made without a "record breaking" event. For example,

.. testcode:: modelaveraging

 # We will accept equilibration if 10 sweeps are completed without a
 # record breaking event, 2 consecutive times.

 gt.mcmc_equilibrate(state, wait=10, nbreaks=2, mcmc_args=dict(niter=10), verbose=True)

will output:

.. testoutput:: modelaveraging
 :options: +NORMALIZE_WHITESPACE

 niter: 1 count: 0 breaks: 0 min_S: 706.26857 max_S: 708.14483 S: 708.14483 ΔS: 1.87626 moves: 418
 niter: 2 count: 0 breaks: 0 min_S: 699.23453 max_S: 708.14483 S: 699.23453 ΔS: 8.91030 moves: 409
 niter: 3 count: 0 breaks: 0 min_S: 699.23453 max_S: 715.33531 S: 715.33531 ΔS: 16.1008 moves: 414
 niter: 4 count: 0 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 723.13301 ΔS: 7.79770 moves: 391
 niter: 5 count: 1 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 702.93354 ΔS: 20.1995 moves: 411
 niter: 6 count: 2 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 706.39029 ΔS: 3.45675 moves: 389
 niter: 7 count: 3 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 706.80859 ΔS: 0.418293 moves: 404
 niter: 8 count: 4 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 707.61960 ΔS: 0.811010 moves: 417
 niter: 9 count: 5 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 706.46577 ΔS: 1.15383 moves: 392
 niter: 10 count: 6 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 714.34671 ΔS: 7.88094 moves: 410
 niter: 11 count: 7 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 706.43194 ΔS: 7.91477 moves: 383
 niter: 12 count: 8 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 705.19434 ΔS: 1.23760 moves: 405
 niter: 13 count: 9 breaks: 0 min_S: 699.23453 max_S: 723.13301 S: 702.21395 ΔS: 2.98039 moves: 423
 niter: 14 count: 0 breaks: 1 min_S: 715.54878 max_S: 715.54878 S: 715.54878 ΔS: 13.3348 moves: 400
 niter: 15 count: 0 breaks: 1 min_S: 715.54878 max_S: 716.65842 S: 716.65842 ΔS: 1.10964 moves: 413
 niter: 16 count: 0 breaks: 1 min_S: 701.19994 max_S: 716.65842 S: 701.19994 ΔS: 15.4585 moves: 382
 niter: 17 count: 1 breaks: 1 min_S: 701.19994 max_S: 716.65842 S: 715.56997 ΔS: 14.3700 moves: 394
 niter: 18 count: 0 breaks: 1 min_S: 701.19994 max_S: 719.25577 S: 719.25577 ΔS: 3.68580 moves: 404
 niter: 19 count: 0 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 723.78811 ΔS: 4.53233 moves: 413
 niter: 20 count: 1 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 709.77340 ΔS: 14.0147 moves: 387
 niter: 21 count: 2 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 714.14891 ΔS: 4.37551 moves: 419
 niter: 22 count: 3 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 722.05875 ΔS: 7.90984 moves: 399
 niter: 23 count: 4 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 714.32503 ΔS: 7.73371 moves: 422
 niter: 24 count: 5 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 708.53927 ΔS: 5.78576 moves: 392
 niter: 25 count: 6 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 714.05889 ΔS: 5.51962 moves: 404
 niter: 26 count: 7 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 713.93196 ΔS: 0.126937 moves: 414
 niter: 27 count: 8 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 709.49863 ΔS: 4.43333 moves: 410
 niter: 28 count: 9 breaks: 1 min_S: 701.19994 max_S: 723.78811 S: 707.42167 ΔS: 2.07696 moves: 397
 niter: 29 count: 0 breaks: 1 min_S: 699.89982 max_S: 723.78811 S: 699.89982 ΔS: 7.52185 moves: 388
 niter: 30 count: 0 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 698.57305 ΔS: 1.32677 moves: 391
 niter: 31 count: 1 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 706.02629 ΔS: 7.45324 moves: 412
 niter: 32 count: 2 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 701.97778 ΔS: 4.04852 moves: 421
 niter: 33 count: 3 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 707.50134 ΔS: 5.52356 moves: 410
 niter: 34 count: 4 breaks: 1 min_S: 698.57305 max_S: 723.78811 S: 708.56686 ΔS: 1.06552 moves: 424
 niter: 35 count: 0 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 724.07361 ΔS: 15.5067 moves: 399
 niter: 36 count: 1 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 723.51969 ΔS: 0.553915 moves: 384
 niter: 37 count: 2 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 702.36708 ΔS: 21.1526 moves: 406
 niter: 38 count: 3 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 707.60129 ΔS: 5.23420 moves: 405
 niter: 39 count: 4 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 709.67542 ΔS: 2.07413 moves: 400
 niter: 40 count: 5 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 714.52753 ΔS: 4.85212 moves: 398
 niter: 41 count: 6 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 707.86563 ΔS: 6.66190 moves: 409
 niter: 42 count: 7 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 718.80926 ΔS: 10.9436 moves: 400
 niter: 43 count: 8 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 716.37312 ΔS: 2.43615 moves: 378
 niter: 44 count: 9 breaks: 1 min_S: 698.57305 max_S: 724.07361 S: 713.76944 ΔS: 2.60368 moves: 399
 niter: 45 count: 10 breaks: 2 min_S: 698.57305 max_S: 724.07361 S: 715.29009 ΔS: 1.52066 moves: 421

Note that the value of ``wait`` above was made purposefully low so that
the output would not be overly long. The most appropriate value requires
experimentation, but a typically good value is ``wait=1000``.

The function :func:`~graph_tool.inference.mcmc.mcmc_equilibrate` accepts a
``callback`` argument that takes an optional function to be invoked
after each call to
:meth:`~graph_tool.inference.blockmodel.BlockState.mcmc_sweep`. This function
should accept a single parameter which will contain the actual
:class:`~graph_tool.inference.blockmodel.BlockState` instance. We will use this in
the example below to collect the posterior vertex marginals (via
:class:`~graph_tool.inference.blockmodel.BlockState.collect_vertex_marginals`),
i.e. the posterior probability that a node belongs to a given group:

.. testcode:: modelaveraging

 # We will first equilibrate the Markov chain
 gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))

 pv = None

 def collect_marginals(s):
 global pv
 pv = s.collect_vertex_marginals(pv)

 # Now we collect the marginals for exactly 100,000 sweeps, at
 # intervals of 10 sweeps:
 gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
 callback=collect_marginals)

 # Now the node marginals are stored in property map pv. We can
 # visualize them as pie charts on the nodes:
 state.draw(pos=g.vp.pos, vertex_shape="pie", vertex_pie_fractions=pv,
 edge_gradient=None, output="lesmissbmmarginals.svg")

.. figure:: lesmissbmmarginals.*
 :align: center
 :width: 450px

 Marginal probabilities of group memberships of the network of
 characters in the novel Les Misérables, according to the
 degreecorrected SBM. The `pie fractions
 `_ on the nodes correspond
 to the probability of being in group associated with the respective
 color.

We can also obtain a marginal probability on the number of groups
itself, as follows.

.. testcode:: modelaveraging

 h = np.zeros(g.num_vertices() + 1)

 def collect_num_groups(s):
 B = s.get_nonempty_B()
 h[B] += 1

 # Now we collect the marginals for exactly 100,000 sweeps, at
 # intervals of 10 sweeps:
 gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
 callback=collect_num_groups)

.. testcode:: modelaveraging
 :hide:

 figure()
 Bs = np.arange(len(h))
 idx = h > 0
 bar(Bs[idx], h[idx] / h.sum(), width=1, color="#ccb974")
 gca().set_xticks([6,7,8,9])
 xlabel("$B$")
 ylabel(r"$P(B\boldsymbol G)$")
 savefig("lesmisBposterior.svg")

.. figure:: lesmisBposterior.*
 :align: center

 Marginal posterior probability of the number of nonempty groups for
 the network of characters in the novel Les Misérables, according to
 the degreecorrected SBM.


Hierarchical partitions
+++++++++++++++++++++++

We can also perform model averaging using the nested SBM, which will
give us a distribution over hierarchies. The whole procedure is fairly
analogous, but now we make use of
:class:`~graph_tool.inference.nested_blockmodel.NestedBlockState` instances.

.. note::

 When using :class:`~graph_tool.inference.nested_blockmodel.NestedBlockState` instances
 to perform model averaging, they need to be constructed with the
 option ``sampling=True``.

Here we perform the sampling of hierarchical partitions using the same
network as above.

.. testcode:: nestedmodelaveraging

 g = gt.collection.data["lesmis"]

 state = gt.minimize_nested_blockmodel_dl(g) # Initialize he Markov
 # chain from the "ground
 # state"

 # Before doing model averaging, the need to create a NestedBlockState
 # by passing sampling = True.

 # We also want to increase the maximum hierarchy depth to L = 10

 # We can do both of the above by copying.

 bs = state.get_bs() # Get hierarchical partition.
 bs += [np.zeros(1)] * (10  len(bs)) # Augment it to L = 10 with
 # singlegroup levels.

 state = state.copy(bs=bs, sampling=True)

 # Now we run 1000 sweeps of the MCMC

 dS, nattempts, nmoves = state.mcmc_sweep(niter=1000)

 print("Change in description length:", dS)
 print("Number of accepted vertex moves:", nmoves)

.. testoutput:: nestedmodelaveraging

 Change in description length: 2.371018...
 Number of accepted vertex moves: 56087

Similarly to the the nonnested case, we can use
:func:`~graph_tool.inference.mcmc.mcmc_equilibrate` to do most of the boring
work, and we can now obtain vertex marginals on all hierarchical levels:


.. testcode:: nestedmodelaveraging

 # We will first equilibrate the Markov chain
 gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))

 pv = [None] * len(state.get_levels())

 def collect_marginals(s):
 global pv
 pv = [sl.collect_vertex_marginals(pv[l]) for l, sl in enumerate(s.get_levels())]

 # Now we collect the marginals for exactly 100,000 sweeps
 gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
 callback=collect_marginals)

 # Now the node marginals for all levels are stored in property map
 # list pv. We can visualize the first level as pie charts on the nodes:
 state_0 = state.get_levels()[0]
 state_0.draw(pos=g.vp.pos, vertex_shape="pie", vertex_pie_fractions=pv[0],
 edge_gradient=None, output="lesmisnestedsbmmarginals.svg")

.. figure:: lesmisnestedsbmmarginals.*
 :align: center
 :width: 450px

 Marginal probabilities of group memberships of the network of
 characters in the novel Les Misérables, according to the nested
 degreecorrected SBM. The pie fractions on the nodes correspond to
 the probability of being in group associated with the respective
 color.

We can also obtain a marginal probability of the number of groups
itself, as follows.

.. testcode:: nestedmodelaveraging

 h = [np.zeros(g.num_vertices() + 1) for s in state.get_levels()]

 def collect_num_groups(s):
 for l, sl in enumerate(s.get_levels()):
 B = sl.get_nonempty_B()
 h[l][B] += 1

 # Now we collect the marginal distribution for exactly 100,000 sweeps
 gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
 callback=collect_num_groups)

.. testcode:: nestedmodelaveraging
 :hide:

 figure()
 f, ax = plt.subplots(1, 5, figsize=(10, 3))
 for i, h_ in enumerate(h[:5]):
 Bs = np.arange(len(h_))
 idx = h_ > 0
 ax[i].bar(Bs[idx], h_[idx] / h_.sum(), width=1, color="#ccb974")
 ax[i].set_xticks(Bs[idx])
 ax[i].set_xlabel("$B_{%d}$" % i)
 ax[i].set_ylabel(r"$P(B_{%d}\boldsymbol G)$" % i)
 locator = MaxNLocator(prune='both', nbins=5)
 ax[i].yaxis.set_major_locator(locator)
 tight_layout()
 savefig("lesmisnestedBposterior.svg")

.. figure:: lesmisnestedBposterior.*
 :align: center

 Marginal posterior probability of the number of nonempty groups
 :math:`B_l` at each hierarchy level :math:`l` for the network of
 characters in the novel Les Misérables, according to the nested
 degreecorrected SBM.

Below we obtain some hierarchical partitions sampled from the posterior
distribution.

.. testcode:: nestedmodelaveraging

 for i in range(10):
 state.mcmc_sweep(niter=1000)
 state.draw(output="lesmispartitionsample%i.svg" % i, empty_branches=False)

.. image:: lesmispartitionsample0.svg
 :width: 200px
.. image:: lesmispartitionsample1.svg
 :width: 200px
.. image:: lesmispartitionsample2.svg
 :width: 200px
.. image:: lesmispartitionsample3.svg
 :width: 200px
.. image:: lesmispartitionsample4.svg
 :width: 200px
.. image:: lesmispartitionsample5.svg
 :width: 200px
.. image:: lesmispartitionsample6.svg
 :width: 200px
.. image:: lesmispartitionsample7.svg
 :width: 200px
.. image:: lesmispartitionsample8.svg
 :width: 200px
.. image:: lesmispartitionsample9.svg
 :width: 200px

Model class selection
+++++++++++++++++++++

When averaging over partitions, we may be interested in evaluating which
**model class** provides a better fit of the data, considering all
possible parameter choices. This is done by evaluating the model
evidence summed over all possible partitions [peixotononparametric2017]_:

.. math::

 P(\boldsymbol G) = \sum_{\boldsymbol\theta,\boldsymbol b}P(\boldsymbol G,\boldsymbol\theta, \boldsymbol b) = \sum_{\boldsymbol b}P(\boldsymbol G,\boldsymbol b).

This quantity is analogous to a `partition function
`_
in statistical physics, which we can write more conveniently as a
negative `free energy
`_ by taking
its logarithm

.. math::
 :label: freeenergy

 \ln P(\boldsymbol G) = \underbrace{\sum_{\boldsymbol b}q(\boldsymbol b)\ln P(\boldsymbol G,\boldsymbol b)}_{\left<\Sigma\right>}\;
 \underbrace{ \sum_{\boldsymbol b}q(\boldsymbol b)\ln q(\boldsymbol b)}_{\mathcal{S}}

where

.. math::

 q(\boldsymbol b) = \frac{P(\boldsymbol G,\boldsymbol b)}{\sum_{\boldsymbol b'}P(\boldsymbol G,\boldsymbol b')}

is the posterior probability of partition :math:`\boldsymbol b`. The
first term of Eq. :eq:`freeenergy` (the "negative energy") is minus the
average of description length :math:`\left<\Sigma\right>`, weighted
according to the posterior distribution. The second term
:math:`\mathcal{S}` is the `entropy
`_ of the
posterior distribution, and measures, in a sense, the "quality of fit"
of the model: If the posterior is very "peaked", i.e. dominated by a
single partition with a very large probability, the entropy will tend to
zero. However, if there are many partitions with similar probabilities
 meaning that there is no single partition that describes the network
uniquely well  it will take a large value instead.

Since the MCMC algorithm samples partitions from the distribution
:math:`q(\boldsymbol b)`, it can be used to compute
:math:`\left<\Sigma\right>` easily, simply by averaging the description
length values encountered by sampling from the posterior distribution
many times.

The computation of the posterior entropy :math:`\mathcal{S}`, however,
is significantly more difficult, since it involves measuring the precise
value of :math:`q(\boldsymbol b)`. A direct "brute force" computation of
:math:`\mathcal{S}` is implemented via
:meth:`~graph_tool.inference.blockmodel.BlockState.collect_partition_histogram` and
:func:`~graph_tool.inference.blockmodel.microstate_entropy`, however this is only
feasible for very small networks. For larger networks, we are forced to
perform approximations. The simplest is a "mean field" one, where we
assume the posterior factorizes as

.. math::

 q(\boldsymbol b) \approx \prod_i{q_i(b_i)}

where

.. math::

 q_i(r) = P(b_i = r  \boldsymbol G)

is the marginal group membership distribution of node :math:`i`. This
yields an entropy value given by

.. math::

 S \approx \sum_i\sum_rq_i(r)\ln q_i(r).

This approximation should be seen as an upper bound, since any existing
correlation between the nodes (which are ignored here) will yield
smaller entropy values.

A more accurate assumption is called the `Bethe approximation`
[mezardinformation2009]_, and takes into account the correlation
between adjacent nodes in the network,

.. math::

 q(\boldsymbol b) \approx \prod_{i`_, :math:`k_i` is the
degree of node :math:`i`, and

.. math::

 q_{ij}(r, s) = P(b_i = r, b_j = s\boldsymbol G)

is the joint group membership distribution of nodes :math:`i` and
:math:`j` (a.k.a. the `edge marginals`). This yields an entropy value
given by

.. math::

 S \approx \sum_{i0` only the meanfield approximation is applicable, since the
adjacency matrix of the higher layers is not constant. We show below the
approach for the same network, using the nested model.


.. testcode:: modelevidence

 g = gt.collection.data["lesmis"]

 nL = 10

 for deg_corr in [True, False]:
 state = gt.minimize_nested_blockmodel_dl(g, deg_corr=deg_corr) # Initialize the Markov
 # chain from the "ground
 # state"
 bs = state.get_bs() # Get hierarchical partition.
 bs += [np.zeros(1)] * (nL  len(bs)) # Augment it to L = 10 with
 # singlegroup levels.

 state = state.copy(bs=bs, sampling=True)

 dls = [] # description length history
 vm = [None] * len(state.get_levels()) # vertex marginals
 em = None # edge marginals

 def collect_marginals(s):
 global vm, em
 levels = s.get_levels()
 vm = [sl.collect_vertex_marginals(vm[l]) for l, sl in enumerate(levels)]
 em = levels[0].collect_edge_marginals(em)
 dls.append(s.entropy())

 # Now we collect the marginal distributions for exactly 200,000 sweeps
 gt.mcmc_equilibrate(state, force_niter=20000, mcmc_args=dict(niter=10),
 callback=collect_marginals)

 S_mf = [gt.mf_entropy(sl.g, vm[l]) for l, sl in enumerate(state.get_levels())]
 S_bethe = gt.bethe_entropy(g, em)[0]
 L = mean(dls)

 print("Model evidence for deg_corr = %s:" % deg_corr,
 L + sum(S_mf), "(mean field),", L + S_bethe + sum(S_mf[1:]), "(Bethe)")


.. testoutput:: modelevidence

 Model evidence for deg_corr = True: 551.228195... (mean field), 740.460493... (Bethe)
 Model evidence for deg_corr = False: 544.660366... (mean field), 649.135026... (Bethe)

The results are similar: If we consider the most accurate approximation,
the nondegreecorrected model possesses the largest evidence. Note also
that we observe a better evidence for the nested models themselves, when
comparing to the evidences for the nonnested model  which is not
quite surprising, since the nonnested model is a special case of the
nested one.

.. _weights:

Edge weights and covariates


Very often networks cannot be completely represented by simple graphs,
but instead have arbitrary "weights" :math:`x_{ij}` on the edges. Edge
weights can be continuous or discrete numbers, and either strictly
positive or positive or negative, depending on context. The SBM can be
extended to cover these cases by treating edge weights as covariates
that are sampled from some distribution conditioned on the node
partition [aicherlearning2015]_ [peixotoweighted2017]_, i.e.

.. math::

 P(\boldsymbol x,\boldsymbol G\boldsymbol b) =
 P(\boldsymbol x\boldsymbol G,\boldsymbol b) P(\boldsymbol G\boldsymbol b),

where :math:`P(\boldsymbol G\boldsymbol b)` is the likelihood of the
unweighted SBM described previously, and :math:`P(\boldsymbol
x\boldsymbol G,\boldsymbol b)` is the integrated likelihood of the edge
weights

.. math::

 P(\boldsymbol x\boldsymbol G,\boldsymbol b) =
 \prod_{r\le s}\int P({\boldsymbol x}_{rs}\gamma)P(\gamma)\,\mathrm{d}\gamma,

where :math:`P({\boldsymbol x}_{rs}\gamma)` is some model for the weights
:math:`{\boldsymbol x}_{rs}` between groups :math:`(r,s)`, conditioned on
some parameter :math:`\gamma`, sampled from its prior
:math:`P(\gamma)`. A hierarchical version of the model can also be
implemented by replacing this prior by a nested sequence of priors and
hyperpriors, as described in [peixotoweighted2017]_. The posterior
partition distribution is then simply

.. math::

 P(\boldsymbol b  \boldsymbol G,\boldsymbol x) =
 \frac{P(\boldsymbol x\boldsymbol G,\boldsymbol b) P(\boldsymbol G\boldsymbol b)
 P(\boldsymbol b)}{P(\boldsymbol G,\boldsymbol x)},

which can be sampled from, or maximized, just like with the unweighted
case, but will use the information on the weights to guide the partitions.

A variety of weight models is supported, reflecting different kinds of
edge covariates:

.. csvtable::
 :header: "Name", "Domain", "Bounds", "Shape"
 :widths: 10, 5, 5, 5
 :delim: 
 :align: center

 ``"realexponential"``  Real :math:`(\mathbb{R})`  :math:`[0,\infty]`  `Exponential `_
 ``"realnormal"``  Real :math:`(\mathbb{R})`  :math:`[\infty,\infty]`  `Normal `_
 ``"discretegeometric"``  Natural :math:`(\mathbb{N})`  :math:`[0,\infty]`  `Geometric `_
 ``"discretebinomial"``  Natural :math:`(\mathbb{N})`  :math:`[0,M]`  `Binomial `_
 ``"discretepoisson"``  Natural :math:`(\mathbb{N})`  :math:`[0,\infty]`  `Poisson `_

In fact, the actual model implements `microcanonical
`_ versions of
these distributions that are asymptotically equivalent, as described in
[peixotoweighted2017]_. These can be combined with arbitrary weight
transformations to achieve a large family of associated
distributions. For example, to use a `lognormal
`_ weight model
for positive real weights :math:`\boldsymbol x`, we can use the
transformation :math:`y_{ij} = \ln x_{ij}` together with the
``"realnormal"`` model for :math:`\boldsymbol y`. To model weights that
are positive or negative integers in :math:`\mathbb{Z}`, we could either
subtract the minimum value, :math:`y_{ij} = x_{ij}  x^*`, with
:math:`x^*=\operatorname{min}_{ij}x_{ij}`, and use any of the above
models for nonnegative integers in :math:`\mathbb{N}`, or
alternatively, consider the sign as an additional covariate,
i.e. :math:`s_{ij} = [\operatorname{sign}(x_{ij})+1]/2 \in \{0,1\}`,
using the Binomial distribution with :math:`M=1` (a.k.a. the `Bernoulli
distribution `_),
and any of the other discrete distributions for the magnitude,
:math:`y_{ij} = \operatorname{abs}(x_{ij})`.

The support for weighted networks is activated by passing the parameters
``recs`` and ``rec_types`` to
:class:`~graph_tool.inference.blockmodel.BlockState` (or
:class:`~graph_tool.inference.overlap_blockmodel.OverlapBlockState`),
that specify the edge covariates (an edge
:class:`~graph_tool.PropertyMap`) and their types (a string from the
table above), respectively. Note that these parameters expect *lists*,
so that multiple edge weights can be used simultaneously.

For example, let us consider a network of suspected terrorists involved
in the train bombing of Madrid on March 11, 2004
[hayesconnecting2006]_. An edge indicates that a connection between
the two persons have been identified, and the weight of the edge (an
integer in the range :math:`[0,3]`) indicates the "strength" of the
connection. We can apply the weighted SBM, using a Binomial model for
the weights, as follows:


.. testsetup:: weightedmodel

 import os
 try:
 os.chdir("demos/inference")
 except FileNotFoundError:
 pass
 gt.seed_rng(42)

.. testcode:: weightedmodel

 g = gt.collection.konect_data["moreno_train"]

 # This network contains an internal edge property map with name
 # "weight" that contains the strength of interactions. The values
 # integers in the range [0, 3].

 state = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[g.ep.weight],
 rec_types=["discretebinomial"]))

 state.draw(edge_color=g.ep.weight, ecmap=(matplotlib.cm.inferno, .6),
 eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1),
 edge_gradient=[], output="morenotrainwsbm.svg")

.. figure:: morenotrainwsbm.*
 :align: center
 :width: 350px

 Best fit of the Binomialweighted degreecorrected SBM for a network
 of terror suspects, using the strength of connection as edge
 covariates. The edge colors and widths correspond to the strengths.

Model selection
+++++++++++++++

In order to select the best weighted model, we proceed in the same
manner as described in Sec. :ref:`model_selection`. However, when using
transformations on continuous weights, we must include the associated
scaling of the probability density, as described in
[peixotoweighted2017]_.

For example, consider a `food web
`_ between species in south
Florida [ulanowicznetwork2005]_. A directed link exists from species
:math:`i` to :math:`j` if a biomass flow exists between them, and a
weight :math:`x_{ij}` on this edge indicates the magnitude of biomass
flow (a positive real value, i.e. :math:`x_{ij}\in [0,\infty]`). One
possibility, therefore, is to use the ``"realexponential"`` model, as
follows:

.. testsetup:: foodweb

 import os
 try:
 os.chdir("demos/inference")
 except FileNotFoundError:
 pass
 gt.seed_rng(44)

.. testcode:: foodweb

 g = gt.collection.konect_data["foodwebbaywet"]

 # This network contains an internal edge property map with name
 # "weight" that contains the biomass flow between species. The values
 # are continuous in the range [0, infinity].

 state = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[g.ep.weight],
 rec_types=["realexponential"]))

 state.draw(edge_color=gt.prop_to_size(g.ep.weight, power=1, log=True), ecmap=(matplotlib.cm.inferno, .6),
 eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1, log=True),
 edge_gradient=[], output="foodwebwsbm.svg")

.. figure:: foodwebwsbm.*
 :align: center
 :width: 350px

 Best fit of the exponentialweighted degreecorrected SBM for a food
 web, using the biomass flow as edge covariates (indicated by the edge
 colors and widths).

Alternatively, we may consider a transformation of the type

.. math::
 :label: log_transform

 y_{ij} = \ln x_{ij}

so that :math:`y_{ij} \in [\infty,\infty]`. If we use a model
``"realnormal"`` for :math:`\boldsymbol y`, it amounts to a `lognormal
`_ model for
:math:`\boldsymbol x`. This can be a better choice if the weights are
distributed across many orders of magnitude, or show multimodality. We
can fit this alternative model simply by using the transformed weights:

.. testcode:: foodweb

 # Apply the weight transformation
 y = g.ep.weight.copy()
 y.a = log(y.a)

 state_ln = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[y],
 rec_types=["realnormal"]))

 state_ln.draw(edge_color=gt.prop_to_size(g.ep.weight, power=1, log=True), ecmap=(matplotlib.cm.inferno, .6),
 eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1, log=True),
 edge_gradient=[], output="foodwebwsbmlognormal.svg")

.. figure:: foodwebwsbmlognormal.*
 :align: center
 :width: 350px

 Best fit of the lognormalweighted degreecorrected SBM for a food
 web, using the biomass flow as edge covariates (indicated by the edge
 colors and widths).

At this point, we ask ourselves which of the above models yields the
best fit of the data. This is answered by performing model selection via
posterior odds ratios just like in Sec. :ref:`model_selection`. However,
here we need to take into account the scaling of the probability density
incurred by the variable transformation, i.e.

.. math::

 P(\boldsymbol x  \boldsymbol G, \boldsymbol b) =
 P(\boldsymbol y(\boldsymbol x)  \boldsymbol G, \boldsymbol b)
 \prod_{ij}\left[\frac{\mathrm{d}y_{ij}}{\mathrm{d}x_{ij}}(x_{ij})\right]^{A_{ij}}.

In the particular case of Eq. :eq:`log_transform`, we have

.. math::

 \prod_{ij}\left[\frac{\mathrm{d}y_{ij}}{\mathrm{d}x_{ij}}(x_{ij})\right]^{A_{ij}}
 = \prod_{ij}\frac{1}{x_{ij}^{A_{ij}}}.

Therefore, we can compute the posterior odds ratio between both models as:

.. testcode:: foodweb

 L1 = state.entropy()
 L2 = state_ln.entropy()  log(g.ep.weight.a).sum()

 print(u"ln \u039b: ", L2  L1)

.. testoutput:: foodweb
 :options: +NORMALIZE_WHITESPACE

 ln Λ: 70.145685...

A value of :math:`\Lambda \approx \mathrm{e}^{70} \approx 10^{30}` in
favor the exponential model indicates that the lognormal model does not
provide a better fit for this particular data. Based on this, we
conclude that the exponential model should be preferred in this case.


Posterior sampling
++++++++++++++++++

The procedure to sample from the posterior distribution is identical to
what is described in Sec. :ref:`sampling`, but with the appropriate
initialization, i.e.

.. testcode:: weightedmodel

 state = gt.BlockState(g, B=20, recs=[g.ep.weight], rec_types=["discretepoisson"])

or for the nested model

.. testcode:: weightedmodel

 state = gt.NestedBlockState(g, bs=[np.random.randint(0, 20, g.num_vertices())] + [zeros(1)] * 10,
 state_args=dict(recs=[g.ep.weight],
 rec_types=["discretepoisson"]))

Layered networks


The edges of the network may be distributed in discrete "layers",
representing distinct types if interactions
[peixotoinferring2015]_. Extensions to the SBM may be defined for such
data, and they can be inferred using the exact same interface shown
above, except one should use the
:class:`~graph_tool.inference.layered_blockmodel.LayeredBlockState`
class, instead of
:class:`~graph_tool.inference.blockmodel.BlockState`. This class takes
two additional parameters: the ``ec`` parameter, that must correspond to
an edge :class:`~graph_tool.PropertyMap` with the layer/covariate values
on the edges, and the Boolean ``layers`` parameter, which if ``True``
specifies a layered model, otherwise one with categorical edge
covariates (not to be confused with the weighted models in
Sec. :ref:`weights`).

If we use :func:`~graph_tool.inference.minimize.minimize_blockmodel_dl`, this can
be achieved simply by passing the option ``layers=True`` as well as the
appropriate value of ``state_args``, which will be propagated to
:class:`~graph_tool.inference.layered_blockmodel.LayeredBlockState`'s constructor.

As an example, let us consider a social network of tribes, where two
types of interactions were recorded, amounting to either friendship or
enmity [readcultures1954]_. We may apply the layered model by
separating these two types of interactions in two layers:

.. testsetup:: layeredmodel

 import os
 try:
 os.chdir("demos/inference")
 except FileNotFoundError:
 pass
 gt.seed_rng(42)

.. testcode:: layeredmodel

 g = gt.collection.konect_data["ucidatagama"]

 # The edge types are stored in the edge property map "weights".

 # Note the different meanings of the two 'layers' parameters below: The
 # first enables the use of LayeredBlockState, and the second selects
 # the 'edge layers' version (instead of 'edge covariates').

 state = gt.minimize_nested_blockmodel_dl(g, layers=True,
 state_args=dict(ec=g.ep.weight, layers=True))

 state.draw(edge_color=g.ep.weight, edge_gradient=[],
 ecmap=(matplotlib.cm.coolwarm_r, .6), edge_pen_width=5,
 output="tribessbmedgelayers.svg")

.. figure:: tribessbmedgelayers.*
 :align: center
 :width: 350px

 Best fit of the degreecorrected SBM with edge layers for a network
 of tribes, with edge layers shown as colors. The groups show two
 enemy tribes.

It is possible to perform model averaging of all layered variants
exactly like for the regular SBMs as was shown above.

Predicting spurious and missing edges


An important application of generative models is to be able to
generalize from observations and make predictions that go beyond what
is seen in the data. This is particularly useful when the network we
observe is incomplete, or contains errors, i.e. some of the edges are
either missing or are outcomes of mistakes in measurement. In this
situation, the fit we make of the observed network can help us
predict missing or spurious edges in the network
[clausethierarchical2008]_ [guimeramissing2009]_.

We do so by dividing the edges into two sets :math:`\boldsymbol G` and
:math:`\delta \boldsymbol G`, where the former corresponds to the
observed network and the latter either to the missing or spurious
edges. We may compute the posterior of :math:`\delta \boldsymbol G` as
[vallescatalaconsistency2017]_

.. math::
 :label: posteriormissing

 P(\delta \boldsymbol G  \boldsymbol G) \propto
 \sum_{\boldsymbol b}\frac{P(\boldsymbol G \cup \delta\boldsymbol G \boldsymbol b)}{P(\boldsymbol G \boldsymbol b)}P(\boldsymbol b  \boldsymbol G)

up to a normalization constant. Although the normalization constant is
difficult to obtain in general (since we need to perform a sum over all
possible spurious/missing edges), the numerator of
Eq. :eq:`posteriormissing` can be computed by sampling partitions from
the posterior, and then inserting or deleting edges from the graph and
computing the new likelihood. This means that we can easily compare
alternative predictive hypotheses :math:`\{\delta \boldsymbol G_i\}` via
their likelihood ratios

.. math::

 \lambda_i = \frac{P(\delta \boldsymbol G_i  \boldsymbol G)}{\sum_j P(\delta \boldsymbol G_j  \boldsymbol G)}

which do not depend on the normalization constant.

The values :math:`P(\delta \boldsymbol G  \boldsymbol G, \boldsymbol b)`
can be computed with
:meth:`~graph_tool.inference.blockmodel.BlockState.get_edges_prob`. Hence, we can
compute spurious/missing edge probabilities just as if we were
collecting marginal distributions when doing model averaging.

Below is an example for predicting the two following edges in the
football network, using the nested model (for which we need to replace
:math:`\boldsymbol b` by :math:`\{\boldsymbol b_l\}` in the equations
above).

.. testcode:: missingedges
 :hide:

 import os
 try:
 os.chdir("demos/inference")
 except FileNotFoundError:
 pass

 g = gt.collection.data["football"].copy()
 color = g.new_vp("string", val="#cccccc")
 ecolor = g.new_ep("string", val="#cccccc")
 ewidth = g.new_ep("double", 1)
 e = g.add_edge(101, 102)
 ecolor[e] = "#a40000"
 ewidth[e] = 5
 e = g.add_edge(17, 56)
 ecolor[e] = "#a40000"
 ewidth[e] = 5
 eorder = g.edge_index.copy("int")

 gt.graph_draw(g, pos=g.vp.pos, vertex_color=color,
 vertex_fill_color=color, edge_color=ecolor,
 eorder=eorder, edge_pen_width=ewidth,
 output="football_missing.svg")

.. figure:: football_missing.*
 :align: center
 :width: 350px

 Two nonexisting edges in the football network (in red):
 :math:`(101,102)` in the middle, and :math:`(17,56)` in the upper
 right region of the figure.

.. testsetup:: missingedges

 gt.seed_rng(7)

.. testcode:: missingedges

 g = gt.collection.data["football"]

 missing_edges = [(101, 102), (17, 56)]

 L = 10

 state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)

 bs = state.get_bs() # Get hierarchical partition.
 bs += [np.zeros(1)] * (L  len(bs)) # Augment it to L = 10 with
 # singlegroup levels.

 state = state.copy(bs=bs, sampling=True)

 probs = ([], [])

 def collect_edge_probs(s):
 p1 = s.get_edges_prob([missing_edges[0]], entropy_args=dict(partition_dl=False))
 p2 = s.get_edges_prob([missing_edges[1]], entropy_args=dict(partition_dl=False))
 probs[0].append(p1)
 probs[1].append(p2)

 # Now we collect the probabilities for exactly 100,000 sweeps
 gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
 callback=collect_edge_probs)


 def get_avg(p):
 p = np.array(p)
 pmax = p.max()
 p = pmax
 return pmax + log(exp(p).mean())

 p1 = get_avg(probs[0])
 p2 = get_avg(probs[1])

 p_sum = get_avg([p1, p2]) + log(2)

 l1 = p1  p_sum
 l2 = p2  p_sum

 print("likelihoodratio for %s: %g" % (missing_edges[0], exp(l1)))
 print("likelihoodratio for %s: %g" % (missing_edges[1], exp(l2)))


.. testoutput:: missingedges

 likelihoodratio for (101, 102): 0.37...
 likelihoodratio for (17, 56): 0.62...

From which we can conclude that edge :math:`(17, 56)` is more likely
than :math:`(101, 102)` to be a missing edge.

The prediction using the nonnested model can be performed in an
entirely analogous fashion.
References

@@ 1694,6 +72,13 @@ References
Rev. E 89, 012804 (2014). :doi:`10.1103/PhysRevE.89.012804`,
:arxiv:`1310.4378`
+.. [peixotoreconstructing2018] Tiago P. Peixoto, "Reconstructing
+ networks with unknown and heterogeneous errors", :arxiv:`1806.07956`
+
+.. [martinstructural2015] Travis Martin, Brian Ball, M. E. J. Newman,
+ "Structural inference for uncertain networks", Phys. Rev. E 93,
+ 012306 (2016). :doi:`10.1103/PhysRevE.93.012306`, :arxiv:`1506.05490`
+
.. [clausethierarchical2008] Aaron Clauset, Cristopher
Moore, M. E. J. Newman, "Hierarchical structure and the prediction of
missing links in networks", Nature 453, 98101 (2008).
@@ 1730,3 +115,12 @@ References
.. [readcultures1954] Kenneth E. Read, "Cultures of the Central
Highlands, New Guinea", Southwestern J. of Anthropology,
10(1):143 (1954). :doi:`10.1086/soutjanth.10.1.3629074`
+
+.. rubric:: Footnotes
+
+.. [#prediction_posterior] Note that the posterior of Eq. :eq:`posteriormissing`
+ cannot be used to sample the reconstruction :math:`\delta \boldsymbol
+ G`, as it is not informative of the overall network density
+ (i.e. absolute number of missing and spurious edges). It can,
+ however, be used to compare different reconstructions with the same
+ density.
\ No newline at end of file
diff git a/src/graph_tool/inference/uncertain_blockmodel.py b/src/graph_tool/inference/uncertain_blockmodel.py
index 7c462dde53738fa752085ce253246769c2908c5a..a36105e35ae7736c0462b7a083d3eb0c3ce3d415 100644
 a/src/graph_tool/inference/uncertain_blockmodel.py
+++ b/src/graph_tool/inference/uncertain_blockmodel.py
@@ 113,9 +113,17 @@ class UncertainBaseState(object):
init_q_cache()
def get_block_state(self):
 return self.bstate
+ """Return the underlying block state, which can be either
+ :class:`~graph_tool.inference.blockmodel.BlockState` or
+ :class:`~graph_tool.inference.nested_blockmodel.NestedBlockState`.
+ """
+ if self.nbstate is None:
+ return self.bstate
+ else:
+ return self.nbstate
def entropy(self, latent_edges=True, density=True, **kwargs):
+ """Return the entropy, i.e. negative loglikelihood."""
if self.nbstate is None:
S = self._state.entropy(latent_edges, density) + \
self.bstate.entropy(**kwargs)