#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2026 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .. import _check_props, Graph, GraphView, _get_rng, EdgePropertyMap, \
VertexPropertyMap, group_vector_property, _check_prop_vector, \
_check_prop_scalar, _parallel
from collections.abc import Iterable
from abc import ABC, abstractmethod
import numpy
import numpy.random
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_dynamics as lib_dynamics")
[docs]
class BPBaseState(ABC):
"""Base class for belief propagation (BP) states."""
@abstractmethod
def __init__(self):
pass
[docs]
def copy(self, **kwargs):
"""Return a copy of the state. The keyword arguments override the
constructor parameters."""
return type(self)(**dict(dict(self.__getstate__(), converge=False),
**kwargs))
@abstractmethod
def __getstate__(self):
pass
def __setstate__(self, state):
self.__init__(**state, converge=False)
[docs]
@_parallel
def iterate(self, niter=1, parallel=True, update_marginals=True):
"""Updates messages synchronously (or asynchronously if
``parallel=False``), `niter` number of times. This function returns the
iteration delta of the last iteration.
If ``update_marginals=True``, this function calls
:meth:`~BPBaseState.update_marginals()` at the end.
@parallel@
"""
if parallel:
delta = self._state.iterate_parallel(self.g, niter)
else:
delta = self._state.iterate(self.g, niter)
if update_marginals:
self.update_marginals()
return delta
[docs]
def converge(self, epsilon=1e-8, max_niter=1000, update_marginals=True,
**kwargs):
"""Calls :meth:`~BPBaseState.iterate()` until delta falls below
``epsilon`` or the number of iterations exceeds ``max_niter``.
If ``update_marginals=True``, the function
:meth:`~BPBaseState.update_marginals()` is called at the end.
The remaining keyword arguments are passed to
:meth:`~BPBaseState.iterate()`.
This function returns a tuple ``(niter, delta)``, with the number of
iterations performed and the delta of the last iteration.
"""
delta = epsilon + 1
niter = 0
while delta > epsilon and niter < max_niter:
delta = self.iterate(**dict(kwargs, update_marginals=False))
niter += kwargs.get("niter", 1)
if update_marginals:
self.update_marginals()
return niter, delta
[docs]
def update_marginals(self):
"""Update the node marginals from the current messages."""
return self._state.update_marginals(self.g)
[docs]
def log_Z(self):
"""Obtains the log-partition function (a.k.a. free entropy) from the
current messages."""
return self._state.log_Z(self.g)
def _check_values(self, s):
"""Raise an exception if the values of state ``s`` cannot be
evaluated. This is done only by models with discrete states, where an
invalid value would be accessed out of bounds."""
pass
[docs]
@_check_props(graph="self.g", v=("s",))
def sample_energy(self, s):
"""Obtains the energy (Hamiltonian) of state ``s`` (a
:class:`~graph_tool.VertexPropertyMap`).
If ``s`` is vector valued, it's assumed to correspond to multiple
states, and the total energy sum is returned.
"""
self._check_values(s)
if "vector" in s.value_type():
_check_prop_vector(s, scalar=True)
return self._state.sample_energies(self.g,
s)
else:
_check_prop_scalar(s)
return self._state.sample_energy(self.g,
s)
[docs]
def log_prob(self, s):
"""Obtains the log-probability of state ``s`` (a
:class:`~graph_tool.VertexPropertyMap`), computed as the negative energy
of ``s`` minus the logarithm of the partition function.
If ``s`` is vector valued, it's assumed to correspond to multiple
states, and the total log-probability sum is returned.
"""
H = self.sample_energy(s)
lZ = self.log_Z()
if "vector" in s.value_type():
_check_prop_vector(s, scalar=True)
return -H - lZ * len(s[next(self.g.vertices())])
else:
return -H - lZ
[docs]
@_check_props(graph="self.g", v=("s",))
def marginal_log_prob(self, s):
"""Obtains the marginal log-probability of state ``s`` (a
:class:`~graph_tool.VertexPropertyMap`).
If ``s`` is vector valued, it's assumed to correspond to multiple
states, and the total marginal log-probability sum is returned.
"""
self._check_values(s)
if "vector" in s.value_type():
_check_prop_vector(s, scalar=True)
return self._state.marginal_lprobs(self.g,
s)
else:
_check_prop_scalar(s)
return self._state.marginal_lprob(self.g,
s)
[docs]
def marginal_sample(self, update_marginals=True, val_type="int"):
"""Samples a state from the marginal distribution. This function returns
a :class:`~graph_tool.VertexPropertyMap` of type given by ``val_type``.
If ``update_marginals=True``, this function calls
:meth:`~BPBaseState.update_marginals()` before sampling.
"""
if update_marginals:
self.update_marginals()
s = self.g.new_vp(val_type)
self._state.marginal_sample(self.g, s,
_get_rng())
return s
[docs]
class GenPottsBPState(BPBaseState):
@_check_props(v=("theta", "vm", "frozen"), e=("x", "m", "em"))
def __init__(self, g, f, x=1, theta=0, m=None, em=None, vm=None,
marginal_init=False, frozen=None, converge=True):
r"""Belief-propagation equations for a generalized Potts model.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used for the dynamics.
f : :class:`~numpy.ndarray` or list of list
:math:`q\times q` 2D symmetric matrix with interaction strengths
between the :math:`q` spin values.
x : ``float`` or :class:`~graph_tool.EdgePropertyMap` (optional, default: ``1``)
Edge coupling weights. If a :class:`~graph_tool.EdgePropertyMap` is
given, it needs to be of type ``double``. If a scalar is given, this
will determine the value for every edge.
theta : ``float`` or iterable or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``0.``)
Vertex fields. If :class:`~graph_tool.VertexPropertyMap`, this needs
to be of type ``vector<double>``, containing :math:`q` field values
for every node. If it's an iterable, it should contain :math:`q`
field values, which are the same for every node. If a scalar is
given, this will determine the value for every field and vertex.
m : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.EdgePropertyMap`
of type ``vector<double>``, containing the edge messages.
em : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.EdgePropertyMap`
of type ``vector<double>``, containing the edge marginals.
vm : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.VertexPropertyMap`
of type ``vector<double>``, containing the node marginals.
The values of ``m``, ``em``, and ``vm`` must be in the format of
the attributes of the same name of an existing state (e.g. with
:math:`q+1` values per node for ``vm``), otherwise a
:class:`ValueError` is raised.
marginal_init : ``boolean`` (optional, default: ``False``)
If ``True``, the messages will be initialized from the node marginals.
frozen : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.VertexPropertyMap`
of type ``bool``, where a value ``True`` means that a vertex is not
a variable, but a fixed field.
converge : ``boolean`` (optional, default: ``True``)
If ``True``, the function :meth:`GenPottsBPState.converge()` will be
called just after construction.
Notes
-----
This implements belief-propagation (BP) equations
[mezard_information_2009]_ for a generalized Potts model given by
.. math::
P(\boldsymbol s | \boldsymbol A, \boldsymbol x, \boldsymbol\theta)
= \frac{\exp\left(\sum_{i<j}A_{ij}x_{ij}f_{s_i,s_j} + \sum_i\theta_{i,s_i}\right)}
{Z(\boldsymbol A, \boldsymbol x, \boldsymbol\theta)}
where :math:`Z(\boldsymbol A, \boldsymbol x, \boldsymbol\theta)` is the
partition function.
The BP equations consist in the Bethe approximation
.. math::
\log Z(\boldsymbol A, \boldsymbol x, \boldsymbol\theta) = \sum_i\log Z_i
- \sum_{i<j}A_{ij}\log Z_{ij}
with :math:`Z_{ij}=Z_j/Z_{j\to i}=Z_i/Z_{i\to j}`, obtained from the
message-passing equations
.. math::
P_{i\to j}(s_i) = \frac{e^{\theta_{i,s_i}}}{Z_{i\to j}}
\prod_{k\in \partial i\setminus j}\sum_{s_k=1}^{q}P_{k\to i}(s_k)e^{x_{ik}f_{s_i,s_k}},
where :math:`Z_{i\to j}` is a normalization constant. From these
equations, the marginal node probabilities are similarly obtained:
.. math::
P_i(s_i) = \frac{e^{\theta_{i,s_i}}}{z_i}
\prod_{j\in \partial i}\sum_{s_j=1}^{q}P_{j\to i}(s_j)e^{x_{ij}f_{s_i,s_j}},
with :math:`z_i` being another normalization constant. Likewise, the
edge marginals are
.. math::
P_{ij}(s_i, s_j) = \frac{1}{z_{ij}}e^{x_{ij}f_{s_i,s_j}}P_{i\to j}(s_i)P_{j\to i}(s_j),
with :math:`z_{ij}` being a normalization constant.
Examples
--------
.. testsetup:: BPPotts
gt.seed_rng(43)
np.random.seed(43)
.. doctest:: BPPotts
>>> g = gt.GraphView(gt.collection.data["polblogs"].copy(), directed=False)
>>> gt.remove_parallel_edges(g)
>>> g = gt.extract_largest_component(g, prune=True)
>>> state = gt.GenPottsBPState(g, f=array([[ 1, 0, -1],
... [ 0, 1, -1],
... [-1, -1, 1.25]])/20)
>>> s = state.marginal_sample()
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=s,
... output="bp-potts.svg")
<...>
.. figure:: bp-potts.svg
:align: center
:width: 80%
Marginal sample of a 3-state Potts model.
References
----------
.. [mezard_information_2009] Marc Mézard, and Andrea Montanari,
"Information, physics, and computation", Oxford University Press, 2009.
https://web.stanford.edu/~montanar/RESEARCH/book.html
"""
self.g = g
self.f = numpy.asarray(f, dtype="float")
if (self.f.ndim != 2 or self.f.shape[0] != self.f.shape[1] or
self.f.shape[0] == 0):
raise ValueError("f must be a non-empty square matrix, not of "
f"shape {self.f.shape}")
q = self.f.shape[0]
if not isinstance(x, EdgePropertyMap):
x = g.new_ep("double", val=x)
elif x.value_type() != "double":
x = x.copy("double")
self.x = self.g.own_property(x)
if not isinstance(theta, VertexPropertyMap):
if isinstance(theta, Iterable):
theta = list(theta)
if len(theta) != q:
raise ValueError(f"theta has {len(theta)} values, but "
f"q = {q}")
theta = g.new_vp("vector<double>", val=theta)
else:
theta = g.new_vp("vector<double>", val=[theta] * q)
elif theta.value_type() != "vector<double>":
theta = theta.copy("vector<double>")
self.theta = self.g.own_property(theta)
init_m = True
if m is None:
m = g.new_ep("vector<double>")
else:
init_m = False
m = m.copy("vector<double>")
self.m = self.g.own_property(m)
init_em = True
if em is None:
em = g.new_ep("vector<double>")
else:
em = em.copy("vector<double>")
init_em = False
self.em = self.g.own_property(em)
init_vm = True
if vm is None:
vm = g.new_vp("vector<double>")
else:
vm = vm.copy("vector<double>")
init_vm = False
self.vm = self.g.own_property(vm)
if frozen is None:
frozen = g.new_vp("bool")
elif frozen.value_type() != "bool":
frozen = frozen.copy("bool")
self.frozen = self.g.own_property(frozen)
self._state = lib_dynamics.make_potts_bp_state(self.g,
self.f,
self.x,
self.theta,
self.m,
self.em,
self.vm,
marginal_init,
self.frozen,
init_vm, init_em, init_m,
_get_rng())
if converge:
self.converge()
def __getstate__(self):
return dict(g=self.g, f=self.f, x=self.x, theta=self.theta, m=self.m,
em=self.em, vm=self.vm, frozen=self.frozen)
[docs]
def energy(self):
r"""Obtains the average energy from the current messages.
This is given by
.. math::
U = -\sum_{i<j}A_{ij}\sum_{s_i,s_j}x_{ij}f_{s_i,s_j}P_{ij}(s_i,s_j)
-\sum_i\sum_{s_i}P_i(s_i)\theta_{i,s_i}
with :math:`P_{ij}(s_i,s_j)` and :math:`P_i(s_i)` being the marginal
edge and node distributions, respectively.
"""
return self._state.energy(self.g)
[docs]
def entropy(self):
r"""Obtains the entropy from the current messages.
This is given by
.. math::
S = -\sum_i(1-k_i)\sum_{s_i}P_i(s_i)\ln P_i(s_i)
-\sum_{i<j}A_{ij}\sum_{s_i,s_j}P_{ij}(s_i,s_j)\ln P_{ij}(s_i,s_j)
with :math:`P_i(s_i)` and :math:`P_{ij}(s_i,s_j)` being the marginal
node and edge distributions, respectively, and :math:`k_i` is the degree
of node i.
"""
return self._state.entropy(self.g)
[docs]
@_check_props(graph="self.g", v=("s",))
def bethe_log_prob(self, s):
r"""Obtains the Bethe approximation of the log-probability of state ``s``
(a :class:`~graph_tool.VertexPropertyMap`), based on node and edge
marginals, i.e.
.. math::
\ln P(\boldsymbol s | \boldsymbol A, \boldsymbol x) =
\sum_i(1-k_i)\ln P_i(s_i) + \sum_{i<j}A_{ij}\ln P_{ij}(s_i,s_j)
where the node and edge marginals are obtained from the messages, and
:math:`k_i` is the degree of node :math:`i`.
.. warning::
The results of :meth:`~GenPottsBPState.bethe_log_prob` and
:meth:`~GenPottsBPState.log_prob` will be the same only for trees.
The value of :meth:`~GenPottsBPState.bethe_log_prob`, even when
approximate (i.e. for loopy graphs), is nevertheless more consistent
with the BP ansatz.
"""
self._check_values(s)
return self._state.bethe_lprob(self.g,
s)
def _check_values(self, s):
q = self.f.shape[0]
if "vector" in s.value_type():
vals = [s[v].a for v in self.g.vertices()]
if len(set(len(x) for x in vals)) > 1:
raise ValueError("all vertices must have the same number of "
"states")
a = numpy.concatenate(vals) if len(vals) > 0 else numpy.zeros(0)
else:
a = self.g.own_property(s).fa
if len(a) > 0 and (a.min() < 0 or a.max() >= q):
raise ValueError(f"the states must lie in the range [0, {q - 1}],"
f" but they lie in [{a.min()}, {a.max()}]")
def _check_vertex(self, v):
try:
return int(self.g.vertex(v))
except (ValueError, TypeError):
raise ValueError(f"invalid vertex: {v}")
[docs]
def marginal_pair_log_prob(self, u, v, r, s):
r"""Obtains the marginal joint log-probability of node pairs :math:`u`
and :math:`v` with values :math:`s_u = r` and :math:`s_v = s`.
"""
u = self._check_vertex(u)
v = self._check_vertex(v)
q = self.f.shape[0]
for x in (r, s):
if x != int(x) or x < 0 or x >= q:
raise ValueError(f"invalid state {x}, which must lie in the "
f"range [0, {q - 1}]")
return self._state.marginal_pair_lprob(self.g, u, v, int(r), int(s))
[docs]
def marginal_entropy(self):
"""Obtains the marginal entropy from the current messages."""
return self._state.marginal_entropy(self.g)
[docs]
def marginal_mean(self):
"""Obtains the marginal mean from the current messages."""
return self._state.marginal_mean(self.g)
[docs]
def sample(self, vorder=None, parallel=True, max_niter=1000, epsilon=1e-8):
"""Sample from the joint distribution by repeatedly conditioning and
marginalizing using the BP equations.
The optional parameter ``vorder`` is a list of vertices giving the
marginalization order. If it does not contain every vertex, the
remaining ones are sampled after it, in the order of their indices.
The remaining parameters control the BP convergence; see
:meth:`GenPottsBPState.converge`.
.. warning::
This algorithm has a quadratic complexity :math:`O(NE)`, where
:math:`N` and :math:`E` are the number of nodes and edges,
respectively.
"""
s = self.g.new_vp("int")
vs = self.g.vertex_index.copy("int64_t").fa
if vorder is None:
vorder = vs
else:
vorder = numpy.asarray(vorder, dtype="int64").ravel()
if not numpy.isin(vorder, vs).all():
raise ValueError("vorder contains invalid vertices")
vorder = numpy.concatenate((vorder,
vs[~numpy.isin(vs, vorder)]))
vorder = numpy.asarray(vorder, dtype="uint64")
self._state.sample(self.g, vorder,
s, parallel, max_niter,
epsilon, _get_rng())
return s
[docs]
class IsingBPState(GenPottsBPState):
def __init__(self, g, x=1, theta=0, m=None, em=None, vm=None, marginal_init=False,
frozen=None, has_zero=False, converge=True):
r"""Belief-propagation equations for the Ising model.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used for the dynamics.
x : ``float`` or :class:`~graph_tool.EdgePropertyMap` (optional, default: ``1``)
Edge coupling weights. If a :class:`~graph_tool.EdgePropertyMap` is
given, it needs to be of type ``double``. If a scalar is given, this
will determine the value for every edge.
theta : ``float`` or iterable or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``0.``)
Vertex fields. If :class:`~graph_tool.VertexPropertyMap`, this needs
to be of type ``double``. If a scalar is given, this will
determine the value for every vertex.
m : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.EdgePropertyMap`
of type ``vector<double>``, containing the edge messages.
em : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.EdgePropertyMap`
of type ``vector<double>``, containing the edge marginals.
vm : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.VertexPropertyMap`
of type ``vector<double>``, containing the node marginals.
The values of ``m``, ``em``, and ``vm`` must be in the format of
the attributes of the same name of an existing state (e.g. with
:math:`q+1` values per node for ``vm``), otherwise a
:class:`ValueError` is raised.
marginal_init : ``boolean`` (optional, default: ``False``)
If ``True``, the messages will be initialized from the node marginals.
frozen : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.VertexPropertyMap`
of type ``bool``, where a value ``True`` means that a vertex is not
a variable, but a fixed field.
has_zero : ``boolean`` (optional, default: ``False``)
If ``True``, a three-state model with :math:`\sigma_i\in\{-1,0,1\}`
is used.
converge : ``boolean`` (optional, default: ``True``)
If ``True``, the function :meth:`GenPottsBPState.converge()` will be
called just after construction.
Notes
-----
This implements BP equations [mezard_information_2009]_ for the Ising
model given by
.. math::
P(\boldsymbol \sigma | \boldsymbol A, \boldsymbol x, \boldsymbol\theta)
= \frac{\exp\left(\sum_{i<j}A_{ij}x_{ij}\sigma_i\sigma_j + \sum_i\theta_{i}\sigma_i\right)}
{Z(\boldsymbol A, \boldsymbol x, \boldsymbol\theta)}
where :math:`\sigma_i\in\{-1,1\}` and :math:`Z(\boldsymbol A,
\boldsymbol x, \boldsymbol\theta)` is the partition function. This is
equivalent to a generalized Potts model with :math:`s_i=(\sigma_i +
1)/2` and :math:`f_{rs} = (2r-1)(2s-1)`. See
:class:`~graph_tool.dynamics.GenPottsBPState` for more details.
If ``has_zero == True``, then it is assumed :math:`\sigma_i\in\{-1,0,1\}`.
Examples
--------
.. testsetup:: BPIsing
gt.seed_rng(42)
np.random.seed(42)
.. doctest:: BPIsing
>>> g = gt.GraphView(gt.collection.data["polblogs"].copy(), directed=False)
>>> gt.remove_parallel_edges(g)
>>> g = gt.extract_largest_component(g, prune=True)
>>> state = gt.IsingBPState(g, x=1/20,
... theta=g.vp.value.t(lambda x: np.arctanh((2*x-1)*.9)))
>>> s = state.sample()
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=s,
... output="bp-ising.svg")
<...>
.. figure:: bp-ising.svg
:align: center
:width: 80%
Marginal sample of an Ising model.
References
----------
.. [mezard_information_2009] Marc Mézard, and Andrea Montanari,
"Information, physics, and computation", Oxford University Press, 2009.
https://web.stanford.edu/~montanar/RESEARCH/book.html
"""
if not has_zero:
f = [[1, -1],
[-1, 1]]
else:
f = [[ 1, 0, -1],
[ 0, 0, 0],
[-1, 0, 1]]
# the Potts states s = 0, 1 (, 2) correspond to the spins
# sigma = -1, 1 (or -1, 0, 1), so that theta_s = theta * sigma
if not isinstance(theta, VertexPropertyMap):
if not has_zero:
theta = g.new_vp("vector<double>", val=[-theta, theta])
else:
theta = g.new_vp("vector<double>", val=[-theta, 0, theta])
elif theta.value_type() == "double":
ntheta = theta.copy()
ntheta.a *= -1
if not has_zero:
theta = group_vector_property([ntheta, theta])
else:
zero = g.new_vp("double")
theta = group_vector_property([ntheta, zero, theta])
elif theta.value_type() != "vector<double>":
theta = theta.copy("vector<double>")
self.has_zero = has_zero
super().__init__(g=g, f=f, x=x, theta=theta, m=m, em=em, vm=vm,
marginal_init=marginal_init, frozen=frozen,
converge=converge)
def __getstate__(self):
return dict(g=self.g, x=self.x, theta=self.theta, m=self.m,
em=self.em, vm=self.vm, frozen=self.frozen,
has_zero=self.has_zero)
def _check_spin(self, x):
vals = (-1, 0, 1) if self.has_zero else (-1, 1)
if not numpy.isin(x, vals).all():
raise ValueError(f"the spin values must be in {vals}")
[docs]
def from_spin(self, s):
s = s.copy()
if "vector" in s.value_type():
for v in self.g.vertices():
self._check_spin(s[v].a)
else:
self._check_spin(s.fa)
f = 2 if not self.has_zero else 1
if "vector" in s.value_type():
for v in self.g.vertices():
s[v].a = (s[v].a + 1)/f
else:
s.fa = (s.fa + 1)/f
return s
[docs]
def to_spin(self, s):
s = s.copy()
f = 2 if not self.has_zero else 1
if "vector" in s.value_type():
for v in self.g.vertices():
s[v].a = f * s[v].a - 1
else:
s.fa = f * s.fa - 1
return s
[docs]
def mag(self):
"""Obtains the average magnetization from the current messages."""
f = 2 if not self.has_zero else 1
return f * self.marginal_mean() - 1
[docs]
def sample_energy(self, s):
return GenPottsBPState.sample_energy(self, self.from_spin(s))
[docs]
def log_prob(self, s):
return GenPottsBPState.log_prob(self, self.from_spin(s))
[docs]
def bethe_log_prob(self, s):
return GenPottsBPState.bethe_log_prob(self, self.from_spin(s))
[docs]
def marginal_log_prob(self, s):
return GenPottsBPState.marginal_log_prob(self, self.from_spin(s))
[docs]
def marginal_pair_log_prob(self, u, v, r, s):
self._check_spin([r, s])
f = 2 if not self.has_zero else 1
return GenPottsBPState.marginal_pair_log_prob(self, u, v,
int((r + 1) // f),
int((s + 1) // f))
[docs]
def marginal_sample(self, update_marginals=True, val_type="int"):
s = GenPottsBPState.marginal_sample(self, update_marginals=update_marginals,
val_type=val_type)
return self.to_spin(s)
[docs]
def sample(self, **kwargs):
s = GenPottsBPState.sample(self, **kwargs)
return self.to_spin(s)
[docs]
class NormalBPState(BPBaseState):
@_check_props(v=("mu", "theta", "vm_m", "vm_s", "frozen"),
e=("x", "m_m", "m_s"))
def __init__(self, g, x=1, mu=0, theta=1, m_m=None, m_s=None, vm_m=None,
vm_s=None, marginal_init=False, frozen=None, converge=True):
r"""Belief-propagation equations for the multivariate Normal distribution.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used for the dynamics.
x : ``float`` or :class:`~graph_tool.EdgePropertyMap` (optional, default: ``1.``)
Inverse covariance couplings. If a :class:`~graph_tool.EdgePropertyMap` is
given, it needs to be of type ``double``. If a scalar is given, this
will determine the value for every edge.
mu : ``float`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``0.``)
Node means. If a :class:`~graph_tool.VertexPropertyMap` is given, it
needs to be of type ``double``. If a scalar is given, this will
determine the value for every vertex.
theta : ``float`` or iterable or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``1.``)
Diagonal of the inverse covariance matrix. If
:class:`~graph_tool.VertexPropertyMap`, this needs to be of type
``double``. If a scalar is given, this will determine the value
for every vertex.
m_m : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.EdgePropertyMap` of
type ``vector<double>``, containing the edge messages for the means.
m_s : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.EdgePropertyMap` of
type ``vector<double>``, containing the edge messages for the
variances.
vm_m : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.VertexPropertyMap`
of type ``double``, containing the node marginal means.
vm_s : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.VertexPropertyMap`
of type ``double``, containing the node marginal variances.
The values of ``m_m`` and ``m_s`` must be in the format of the
attributes of the same name of an existing state (two values per
edge), otherwise a :class:`ValueError` is raised.
marginal_init : ``boolean`` (optional, default: ``False``)
If ``True``, the messages will be initialized from the node marginals.
frozen : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, it should be an :class:`~graph_tool.VertexPropertyMap`
of type ``bool``, where a value ``True`` means that a vertex is not
a variable, but a fixed field.
converge : ``boolean`` (optional, default: ``True``)
If ``True``, the function :meth:`~BPBaseState.converge()` will be
called just after construction.
Notes
-----
This implements BP equations [mezard_information_2009]_ for the
multivariate Normal distribution given by
.. math::
P(\boldsymbol s | \boldsymbol A, \boldsymbol x, \boldsymbol \mu, \boldsymbol\theta)
= \frac{\exp\left(-\frac{1}{2}(\boldsymbol s-\boldsymbol\mu)^{\intercal} \boldsymbol X (\boldsymbol s - \boldsymbol\mu)\right)}
{Z(\boldsymbol X)}
where :math:`X_{ij}=A_{ij}x_{ij}` for :math:`i\neq j`,
:math:`X_{ii}=\theta_i`, and :math:`Z(\boldsymbol X) =
(2\pi)^{N/2}\left|\boldsymbol X\right|^{-1/2}`. The energy is
therefore quadratic in :math:`\boldsymbol s`, with the linear term
:math:`\boldsymbol h = \boldsymbol X\boldsymbol\mu`, i.e.
.. math::
h_i = \theta_i\mu_i + \sum_jA_{ij}x_{ij}\mu_j.
The frozen vertices are not variables, and the values of their states
are their fixed marginal means given by ``vm_m``. The energy and the
partition function then include only the terms that involve at least
one variable.
The BP equations consist in the Bethe approximation
.. math::
\log Z(\boldsymbol X) = \sum_i\log Z_i
- \sum_{i<j}A_{ij}\log Z_{ij}
with :math:`Z_{ij}=Z_j/Z_{j\to i}=Z_i/Z_{i\to j}`, obtained from the
message-passing equations
.. math::
\begin{aligned}
m_{i\to j} &= \frac{h_i - \sum_{k\in \partial i\setminus j}A_{ik}x_{ik}m_{k\to i}}
{\theta_i - \sum_{k\in \partial i\setminus j}A_{ik}x_{ik}^2\sigma_{k\to i}^2},\\
\sigma_{i\to j}^2 &= \frac{1}{\theta_i - \sum_{k\in \partial i\setminus j}A_{ik}x_{ik}^2\sigma_{k\to i}^2},
\end{aligned}
with
.. math::
\begin{aligned}
\log Z_{i\to j} &= \frac{\beta_{i\to j}^2}{4\alpha_{i\to j}} - \frac{1}{2}\log\alpha_{i\to j} + \frac{1}{2}\log\pi - \frac{\theta_i\mu_i^2}{2}\\
\log Z_{i} &= \frac{\beta_{i}^2}{4\alpha_{i}} - \frac{1}{2}\log\alpha_{i} + \frac{1}{2}\log\pi - \frac{\theta_i\mu_i^2}{2}
\end{aligned}
where
.. math::
\begin{aligned}
\alpha_{i\to j} &= \frac{\theta_i - \sum_{k\in \partial i\setminus j}A_{ik}x_{ik}^2\sigma_{k\to i}^2}{2}\\
\beta_{i\to j} &= h_i - \sum_{k\in \partial i\setminus j}A_{ik}x_{ik}m_{k\to i}\\
\alpha_{i} &= \frac{\theta_i - \sum_{j\in \partial i}A_{ij}x_{ij}^2\sigma_{j\to i}^2}{2}\\
\beta_{i} &= h_i - \sum_{j\in \partial i}A_{ij}x_{ij}m_{j\to i},
\end{aligned}
and the constant terms :math:`A_{ij}x_{ij}\mu_i\mu_j` of the energy
are subtracted from :math:`\log Z(\boldsymbol X)` for every edge.
From these equations, the marginal node probability densities are normal
distributions with mean and variance given by
.. math::
\begin{aligned}
m_i &= \frac{h_i - \sum_{j}A_{ij}x_{ij}m_{j\to i}}
{\theta_i - \sum_{j}A_{ij}x_{ij}^2\sigma_{j\to i}^2},\\
\sigma_i^2 &= \frac{1}{\theta_i - \sum_{j}A_{ij}x_{ij}^2\sigma_{j\to i}^2}.
\end{aligned}
Examples
--------
.. testsetup:: BPnormal
gt.seed_rng(42)
np.random.seed(42)
.. doctest:: BPnormal
>>> g = gt.GraphView(gt.collection.data["polblogs"].copy(), directed=False)
>>> gt.remove_parallel_edges(g)
>>> g = gt.extract_largest_component(g, prune=True)
>>> state = gt.NormalBPState(g, x=1/200, mu=g.vp.value.t(lambda x: arctanh((2*x-1)*.9)))
>>> s = state.marginal_sample()
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=s,
... output="bp-normal.svg")
<...>
.. figure:: bp-normal.svg
:align: center
:width: 80%
Marginal sample of a multivariate normal distribution.
References
----------
.. [mezard_information_2009] Marc Mézard, and Andrea Montanari,
"Information, physics, and computation", Oxford University Press, 2009.
https://web.stanford.edu/~montanar/RESEARCH/book.html
"""
self.g = g
if not isinstance(x, EdgePropertyMap):
x = g.new_ep("double", val=x)
elif x.value_type() != "double":
x = x.copy("double")
self.x = self.g.own_property(x)
if not isinstance(mu, VertexPropertyMap):
mu = g.new_vp("double", val=mu)
elif mu.value_type() != "double":
mu = mu.copy("double")
self.mu = self.g.own_property(mu)
if not isinstance(theta, VertexPropertyMap):
theta = g.new_vp("double", val=theta)
elif theta.value_type() != "double":
theta = theta.copy("double")
self.theta = self.g.own_property(theta)
# The given maps are copied, since they are modified in place, and
# their value types must be the ones used by the C++ code.
init_m = m_m is None
if init_m:
m_m = g.new_ep("vector<double>")
else:
m_m = m_m.copy("vector<double>")
init_s = m_s is None
if init_s:
m_s = g.new_ep("vector<double>")
else:
m_s = m_s.copy("vector<double>")
self.m_m = self.g.own_property(m_m)
self.m_s = self.g.own_property(m_s)
if vm_m is None:
vm_m = g.new_vp("double")
else:
vm_m = vm_m.copy("double")
if vm_s is None:
vm_s = g.new_vp("double")
else:
vm_s = vm_s.copy("double")
self.vm_m = self.g.own_property(vm_m)
self.vm_s = self.g.own_property(vm_s)
if frozen is None:
frozen = g.new_vp("bool")
elif frozen.value_type() != "bool":
frozen = frozen.copy("bool")
self.frozen = self.g.own_property(frozen)
self._state = lib_dynamics.make_normal_bp_state(self.g,
self.x,
self.mu,
self.theta,
self.m_m,
self.m_s,
self.vm_m,
self.vm_s,
marginal_init,
self.frozen,
init_m, init_s,
_get_rng())
if converge:
self.converge()
def __getstate__(self):
return dict(g=self.g, x=self.x, mu=self.mu, theta=self.theta,
m_m=self.m_m, m_s=self.m_s, vm_m=self.vm_m,
vm_s=self.vm_s, frozen=self.frozen)
[docs]
def marginal_sample(self, update_marginals=True):
return BPBaseState.marginal_sample(self,
update_marginals=update_marginals,
val_type="double")